repo_name
stringlengths
6
100
path
stringlengths
4
294
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
606
896k
license
stringclasses
15 values
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_trainer.py
6
10247
# Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Training implementation for inception model. """ import logging import os import tensorflow as tf import time from . import _util def start_server(cluster, task): if not task.type: raise ValueError('--task_type must be specified.') if task.index is None: raise ValueError('--task_index must be specified.') # Create and start a server. return tf.train.Server( tf.train.ClusterSpec(cluster), protocol='grpc', job_name=task.type, task_index=task.index) class Evaluator(object): """Loads variables from latest checkpoint and performs model evaluation.""" def __init__(self, model, data_paths, batch_size, output_path, dataset='eval'): data_size = self._data_size(data_paths) if data_size <= batch_size: raise Exception('Data size is smaller than batch size.') self.num_eval_batches = data_size // batch_size self.batch_of_examples = [] self.checkpoint_path = os.path.join(output_path, 'train') self.output_path = os.path.join(output_path, dataset) self.eval_data_paths = data_paths self.batch_size = batch_size self.model = model def _data_size(self, data_paths): n = 0 options = tf.python_io.TFRecordOptions( compression_type=tf.python_io.TFRecordCompressionType.GZIP) for file in data_paths: for line in tf.python_io.tf_record_iterator(file, options=options): n += 1 return n def evaluate(self, num_eval_batches=None): """Run one round of evaluation, return loss and accuracy.""" num_eval_batches = num_eval_batches or self.num_eval_batches with tf.Graph().as_default() as graph: self.tensors = self.model.build_eval_graph(self.eval_data_paths, self.batch_size) self.summary = tf.summary.merge_all() self.saver = tf.train.Saver() self.summary_writer = tf.summary.FileWriter(self.output_path) self.sv = tf.train.Supervisor( graph=graph, logdir=self.output_path, summary_op=None, global_step=None, saver=self.saver) last_checkpoint = tf.train.latest_checkpoint(self.checkpoint_path) with self.sv.managed_session(master='', start_standard_services=False) as session: self.sv.saver.restore(session, last_checkpoint) if not self.batch_of_examples: self.sv.start_queue_runners(session) for i in range(num_eval_batches): self.batch_of_examples.append(session.run(self.tensors.examples)) for i in range(num_eval_batches): session.run(self.tensors.metric_updates, {self.tensors.examples: self.batch_of_examples[i]}) metric_values = session.run(self.tensors.metric_values) global_step = tf.train.global_step(session, self.tensors.global_step) summary = session.run(self.summary) self.summary_writer.add_summary(summary, global_step) self.summary_writer.flush() return metric_values class Trainer(object): """Performs model training and optionally evaluation.""" def __init__(self, input_dir, batch_size, max_steps, output_path, model, cluster, task): train_files, eval_files = _util.get_train_eval_files(input_dir) self.train_data_paths = train_files self.output_path = output_path self.batch_size = batch_size self.model = model self.max_steps = max_steps self.cluster = cluster self.task = task self.evaluator = Evaluator(self.model, eval_files, batch_size, output_path, 'eval_set') self.train_evaluator = Evaluator(self.model, train_files, batch_size, output_path, 'train_set') self.min_train_eval_rate = 8 def run_training(self): """Runs a Master.""" self.train_path = os.path.join(self.output_path, 'train') self.model_path = os.path.join(self.output_path, 'model') self.is_master = self.task.type != 'worker' log_interval = 15 self.eval_interval = 30 if self.is_master and self.task.index > 0: raise Exception('Only one replica of master expected') if self.cluster: logging.info('Starting %s/%d', self.task.type, self.task.index) server = start_server(self.cluster, self.task) target = server.target device_fn = tf.train.replica_device_setter( ps_device='/job:ps', worker_device='/job:%s/task:%d' % (self.task.type, self.task.index), cluster=self.cluster) # We use a device_filter to limit the communication between this job # and the parameter servers, i.e., there is no need to directly # communicate with the other workers; attempting to do so can result # in reliability problems. device_filters = [ '/job:ps', '/job:%s/task:%d' % (self.task.type, self.task.index) ] config = tf.ConfigProto(device_filters=device_filters) else: target = '' device_fn = '' config = None with tf.Graph().as_default() as graph: with tf.device(device_fn): # Build the training graph. self.tensors = self.model.build_train_graph(self.train_data_paths, self.batch_size) # Add the variable initializer Op. init_op = tf.global_variables_initializer() # Create a saver for writing training checkpoints. self.saver = tf.train.Saver() # Build the summary operation based on the TF collection of Summaries. self.summary_op = tf.summary.merge_all() # Create a "supervisor", which oversees the training process. self.sv = tf.train.Supervisor( graph, is_chief=self.is_master, logdir=self.train_path, init_op=init_op, saver=self.saver, # Write summary_ops by hand. summary_op=None, global_step=self.tensors.global_step, # No saving; we do it manually in order to easily evaluate immediately # afterwards. save_model_secs=0) should_retry = True to_run = [self.tensors.global_step, self.tensors.train] while should_retry: try: should_retry = False with self.sv.managed_session(target, config=config) as session: self.start_time = start_time = time.time() self.last_save = self.last_log = 0 self.global_step = self.last_global_step = 0 self.local_step = self.last_local_step = 0 self.last_global_time = self.last_local_time = start_time # Loop until the supervisor shuts down or max_steps have # completed. max_steps = self.max_steps while not self.sv.should_stop() and self.global_step < max_steps: try: # Run one step of the model. self.global_step = session.run(to_run)[0] self.local_step += 1 self.now = time.time() is_time_to_eval = (self.now - self.last_save) > self.eval_interval is_time_to_log = (self.now - self.last_log) > log_interval should_eval = self.is_master and is_time_to_eval should_log = is_time_to_log or should_eval if should_log: self.log(session) if should_eval: self.eval(session) except tf.errors.AbortedError: should_retry = True if self.is_master: # Take the final checkpoint and compute the final accuracy. # self.saver.save(session, self.sv.save_path, self.tensors.global_step) self.eval(session) except tf.errors.AbortedError: print('Hitting an AbortedError. Trying it again.') should_retry = True # Export the model for inference. if self.is_master: self.model.export(tf.train.latest_checkpoint(self.train_path), self.model_path) # Ask for all the services to stop. self.sv.stop() def log(self, session): """Logs training progress.""" logging.info('Train [%s/%d], step %d (%.3f sec) %.1f ' 'global steps/s, %.1f local steps/s', self.task.type, self.task.index, self.global_step, (self.now - self.start_time), (self.global_step - self.last_global_step) / (self.now - self.last_global_time), (self.local_step - self.last_local_step) / (self.now - self.last_local_time)) self.last_log = self.now self.last_global_step, self.last_global_time = self.global_step, self.now self.last_local_step, self.last_local_time = self.local_step, self.now def eval(self, session): """Runs evaluation loop.""" eval_start = time.time() self.saver.save(session, self.sv.save_path, self.tensors.global_step) logging.info( 'Eval, step %d:\n- on train set %s\n-- on eval set %s', self.global_step, self.model.format_metric_values(self.train_evaluator.evaluate()), self.model.format_metric_values(self.evaluator.evaluate())) now = time.time() # Make sure eval doesn't consume too much of total time. eval_time = now - eval_start train_eval_rate = self.eval_interval / eval_time if train_eval_rate < self.min_train_eval_rate and self.last_save > 0: logging.info('Adjusting eval interval from %.2fs to %.2fs', self.eval_interval, self.min_train_eval_rate * eval_time) self.eval_interval = self.min_train_eval_rate * eval_time self.last_save = now self.last_log = now def save_summaries(self, session): self.sv.summary_computed(session, session.run(self.summary_op), self.global_step) self.sv.summary_writer.flush()
apache-2.0
hazrpg/calibre
src/chardet/euctwfreq.py
323
34864
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # EUCTW frequency table # Converted from big5 work # by Taiwan's Mandarin Promotion Council # <http:#www.edu.tw:81/mandr/> # 128 --> 0.42261 # 256 --> 0.57851 # 512 --> 0.74851 # 1024 --> 0.89384 # 2048 --> 0.97583 # # Idea Distribution Ratio = 0.74851/(1-0.74851) =2.98 # Random Distribution Ration = 512/(5401-512)=0.105 # # Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR EUCTW_TYPICAL_DISTRIBUTION_RATIO = 0.75 # Char to FreqOrder table , EUCTW_TABLE_SIZE = 8102 EUCTWCharToFreqOrder = ( \ 1,1800,1506, 255,1431, 198, 9, 82, 6,7310, 177, 202,3615,1256,2808, 110, # 2742 3735, 33,3241, 261, 76, 44,2113, 16,2931,2184,1176, 659,3868, 26,3404,2643, # 2758 1198,3869,3313,4060, 410,2211, 302, 590, 361,1963, 8, 204, 58,4296,7311,1931, # 2774 63,7312,7313, 317,1614, 75, 222, 159,4061,2412,1480,7314,3500,3068, 224,2809, # 2790 3616, 3, 10,3870,1471, 29,2774,1135,2852,1939, 873, 130,3242,1123, 312,7315, # 2806 4297,2051, 507, 252, 682,7316, 142,1914, 124, 206,2932, 34,3501,3173, 64, 604, # 2822 7317,2494,1976,1977, 155,1990, 645, 641,1606,7318,3405, 337, 72, 406,7319, 80, # 2838 630, 238,3174,1509, 263, 939,1092,2644, 756,1440,1094,3406, 449, 69,2969, 591, # 2854 179,2095, 471, 115,2034,1843, 60, 50,2970, 134, 806,1868, 734,2035,3407, 180, # 2870 995,1607, 156, 537,2893, 688,7320, 319,1305, 779,2144, 514,2374, 298,4298, 359, # 2886 2495, 90,2707,1338, 663, 11, 906,1099,2545, 20,2436, 182, 532,1716,7321, 732, # 2902 1376,4062,1311,1420,3175, 25,2312,1056, 113, 399, 382,1949, 242,3408,2467, 529, # 2918 3243, 475,1447,3617,7322, 117, 21, 656, 810,1297,2295,2329,3502,7323, 126,4063, # 2934 706, 456, 150, 613,4299, 71,1118,2036,4064, 145,3069, 85, 835, 486,2114,1246, # 2950 1426, 428, 727,1285,1015, 800, 106, 623, 303,1281,7324,2127,2354, 347,3736, 221, # 2966 3503,3110,7325,1955,1153,4065, 83, 296,1199,3070, 192, 624, 93,7326, 822,1897, # 2982 2810,3111, 795,2064, 991,1554,1542,1592, 27, 43,2853, 859, 139,1456, 860,4300, # 2998 437, 712,3871, 164,2392,3112, 695, 211,3017,2096, 195,3872,1608,3504,3505,3618, # 3014 3873, 234, 811,2971,2097,3874,2229,1441,3506,1615,2375, 668,2076,1638, 305, 228, # 3030 1664,4301, 467, 415,7327, 262,2098,1593, 239, 108, 300, 200,1033, 512,1247,2077, # 3046 7328,7329,2173,3176,3619,2673, 593, 845,1062,3244, 88,1723,2037,3875,1950, 212, # 3062 266, 152, 149, 468,1898,4066,4302, 77, 187,7330,3018, 37, 5,2972,7331,3876, # 3078 7332,7333, 39,2517,4303,2894,3177,2078, 55, 148, 74,4304, 545, 483,1474,1029, # 3094 1665, 217,1869,1531,3113,1104,2645,4067, 24, 172,3507, 900,3877,3508,3509,4305, # 3110 32,1408,2811,1312, 329, 487,2355,2247,2708, 784,2674, 4,3019,3314,1427,1788, # 3126 188, 109, 499,7334,3620,1717,1789, 888,1217,3020,4306,7335,3510,7336,3315,1520, # 3142 3621,3878, 196,1034, 775,7337,7338, 929,1815, 249, 439, 38,7339,1063,7340, 794, # 3158 3879,1435,2296, 46, 178,3245,2065,7341,2376,7342, 214,1709,4307, 804, 35, 707, # 3174 324,3622,1601,2546, 140, 459,4068,7343,7344,1365, 839, 272, 978,2257,2572,3409, # 3190 2128,1363,3623,1423, 697, 100,3071, 48, 70,1231, 495,3114,2193,7345,1294,7346, # 3206 2079, 462, 586,1042,3246, 853, 256, 988, 185,2377,3410,1698, 434,1084,7347,3411, # 3222 314,2615,2775,4308,2330,2331, 569,2280, 637,1816,2518, 757,1162,1878,1616,3412, # 3238 287,1577,2115, 768,4309,1671,2854,3511,2519,1321,3737, 909,2413,7348,4069, 933, # 3254 3738,7349,2052,2356,1222,4310, 765,2414,1322, 786,4311,7350,1919,1462,1677,2895, # 3270 1699,7351,4312,1424,2437,3115,3624,2590,3316,1774,1940,3413,3880,4070, 309,1369, # 3286 1130,2812, 364,2230,1653,1299,3881,3512,3882,3883,2646, 525,1085,3021, 902,2000, # 3302 1475, 964,4313, 421,1844,1415,1057,2281, 940,1364,3116, 376,4314,4315,1381, 7, # 3318 2520, 983,2378, 336,1710,2675,1845, 321,3414, 559,1131,3022,2742,1808,1132,1313, # 3334 265,1481,1857,7352, 352,1203,2813,3247, 167,1089, 420,2814, 776, 792,1724,3513, # 3350 4071,2438,3248,7353,4072,7354, 446, 229, 333,2743, 901,3739,1200,1557,4316,2647, # 3366 1920, 395,2744,2676,3740,4073,1835, 125, 916,3178,2616,4317,7355,7356,3741,7357, # 3382 7358,7359,4318,3117,3625,1133,2547,1757,3415,1510,2313,1409,3514,7360,2145, 438, # 3398 2591,2896,2379,3317,1068, 958,3023, 461, 311,2855,2677,4074,1915,3179,4075,1978, # 3414 383, 750,2745,2617,4076, 274, 539, 385,1278,1442,7361,1154,1964, 384, 561, 210, # 3430 98,1295,2548,3515,7362,1711,2415,1482,3416,3884,2897,1257, 129,7363,3742, 642, # 3446 523,2776,2777,2648,7364, 141,2231,1333, 68, 176, 441, 876, 907,4077, 603,2592, # 3462 710, 171,3417, 404, 549, 18,3118,2393,1410,3626,1666,7365,3516,4319,2898,4320, # 3478 7366,2973, 368,7367, 146, 366, 99, 871,3627,1543, 748, 807,1586,1185, 22,2258, # 3494 379,3743,3180,7368,3181, 505,1941,2618,1991,1382,2314,7369, 380,2357, 218, 702, # 3510 1817,1248,3418,3024,3517,3318,3249,7370,2974,3628, 930,3250,3744,7371, 59,7372, # 3526 585, 601,4078, 497,3419,1112,1314,4321,1801,7373,1223,1472,2174,7374, 749,1836, # 3542 690,1899,3745,1772,3885,1476, 429,1043,1790,2232,2116, 917,4079, 447,1086,1629, # 3558 7375, 556,7376,7377,2020,1654, 844,1090, 105, 550, 966,1758,2815,1008,1782, 686, # 3574 1095,7378,2282, 793,1602,7379,3518,2593,4322,4080,2933,2297,4323,3746, 980,2496, # 3590 544, 353, 527,4324, 908,2678,2899,7380, 381,2619,1942,1348,7381,1341,1252, 560, # 3606 3072,7382,3420,2856,7383,2053, 973, 886,2080, 143,4325,7384,7385, 157,3886, 496, # 3622 4081, 57, 840, 540,2038,4326,4327,3421,2117,1445, 970,2259,1748,1965,2081,4082, # 3638 3119,1234,1775,3251,2816,3629, 773,1206,2129,1066,2039,1326,3887,1738,1725,4083, # 3654 279,3120, 51,1544,2594, 423,1578,2130,2066, 173,4328,1879,7386,7387,1583, 264, # 3670 610,3630,4329,2439, 280, 154,7388,7389,7390,1739, 338,1282,3073, 693,2857,1411, # 3686 1074,3747,2440,7391,4330,7392,7393,1240, 952,2394,7394,2900,1538,2679, 685,1483, # 3702 4084,2468,1436, 953,4085,2054,4331, 671,2395, 79,4086,2441,3252, 608, 567,2680, # 3718 3422,4087,4088,1691, 393,1261,1791,2396,7395,4332,7396,7397,7398,7399,1383,1672, # 3734 3748,3182,1464, 522,1119, 661,1150, 216, 675,4333,3888,1432,3519, 609,4334,2681, # 3750 2397,7400,7401,7402,4089,3025, 0,7403,2469, 315, 231,2442, 301,3319,4335,2380, # 3766 7404, 233,4090,3631,1818,4336,4337,7405, 96,1776,1315,2082,7406, 257,7407,1809, # 3782 3632,2709,1139,1819,4091,2021,1124,2163,2778,1777,2649,7408,3074, 363,1655,3183, # 3798 7409,2975,7410,7411,7412,3889,1567,3890, 718, 103,3184, 849,1443, 341,3320,2934, # 3814 1484,7413,1712, 127, 67, 339,4092,2398, 679,1412, 821,7414,7415, 834, 738, 351, # 3830 2976,2146, 846, 235,1497,1880, 418,1992,3749,2710, 186,1100,2147,2746,3520,1545, # 3846 1355,2935,2858,1377, 583,3891,4093,2573,2977,7416,1298,3633,1078,2549,3634,2358, # 3862 78,3750,3751, 267,1289,2099,2001,1594,4094, 348, 369,1274,2194,2175,1837,4338, # 3878 1820,2817,3635,2747,2283,2002,4339,2936,2748, 144,3321, 882,4340,3892,2749,3423, # 3894 4341,2901,7417,4095,1726, 320,7418,3893,3026, 788,2978,7419,2818,1773,1327,2859, # 3910 3894,2819,7420,1306,4342,2003,1700,3752,3521,2359,2650, 787,2022, 506, 824,3636, # 3926 534, 323,4343,1044,3322,2023,1900, 946,3424,7421,1778,1500,1678,7422,1881,4344, # 3942 165, 243,4345,3637,2521, 123, 683,4096, 764,4346, 36,3895,1792, 589,2902, 816, # 3958 626,1667,3027,2233,1639,1555,1622,3753,3896,7423,3897,2860,1370,1228,1932, 891, # 3974 2083,2903, 304,4097,7424, 292,2979,2711,3522, 691,2100,4098,1115,4347, 118, 662, # 3990 7425, 611,1156, 854,2381,1316,2861, 2, 386, 515,2904,7426,7427,3253, 868,2234, # 4006 1486, 855,2651, 785,2212,3028,7428,1040,3185,3523,7429,3121, 448,7430,1525,7431, # 4022 2164,4348,7432,3754,7433,4099,2820,3524,3122, 503, 818,3898,3123,1568, 814, 676, # 4038 1444, 306,1749,7434,3755,1416,1030, 197,1428, 805,2821,1501,4349,7435,7436,7437, # 4054 1993,7438,4350,7439,7440,2195, 13,2779,3638,2980,3124,1229,1916,7441,3756,2131, # 4070 7442,4100,4351,2399,3525,7443,2213,1511,1727,1120,7444,7445, 646,3757,2443, 307, # 4086 7446,7447,1595,3186,7448,7449,7450,3639,1113,1356,3899,1465,2522,2523,7451, 519, # 4102 7452, 128,2132, 92,2284,1979,7453,3900,1512, 342,3125,2196,7454,2780,2214,1980, # 4118 3323,7455, 290,1656,1317, 789, 827,2360,7456,3758,4352, 562, 581,3901,7457, 401, # 4134 4353,2248, 94,4354,1399,2781,7458,1463,2024,4355,3187,1943,7459, 828,1105,4101, # 4150 1262,1394,7460,4102, 605,4356,7461,1783,2862,7462,2822, 819,2101, 578,2197,2937, # 4166 7463,1502, 436,3254,4103,3255,2823,3902,2905,3425,3426,7464,2712,2315,7465,7466, # 4182 2332,2067, 23,4357, 193, 826,3759,2102, 699,1630,4104,3075, 390,1793,1064,3526, # 4198 7467,1579,3076,3077,1400,7468,4105,1838,1640,2863,7469,4358,4359, 137,4106, 598, # 4214 3078,1966, 780, 104, 974,2938,7470, 278, 899, 253, 402, 572, 504, 493,1339,7471, # 4230 3903,1275,4360,2574,2550,7472,3640,3029,3079,2249, 565,1334,2713, 863, 41,7473, # 4246 7474,4361,7475,1657,2333, 19, 463,2750,4107, 606,7476,2981,3256,1087,2084,1323, # 4262 2652,2982,7477,1631,1623,1750,4108,2682,7478,2864, 791,2714,2653,2334, 232,2416, # 4278 7479,2983,1498,7480,2654,2620, 755,1366,3641,3257,3126,2025,1609, 119,1917,3427, # 4294 862,1026,4109,7481,3904,3760,4362,3905,4363,2260,1951,2470,7482,1125, 817,4110, # 4310 4111,3906,1513,1766,2040,1487,4112,3030,3258,2824,3761,3127,7483,7484,1507,7485, # 4326 2683, 733, 40,1632,1106,2865, 345,4113, 841,2524, 230,4364,2984,1846,3259,3428, # 4342 7486,1263, 986,3429,7487, 735, 879, 254,1137, 857, 622,1300,1180,1388,1562,3907, # 4358 3908,2939, 967,2751,2655,1349, 592,2133,1692,3324,2985,1994,4114,1679,3909,1901, # 4374 2185,7488, 739,3642,2715,1296,1290,7489,4115,2198,2199,1921,1563,2595,2551,1870, # 4390 2752,2986,7490, 435,7491, 343,1108, 596, 17,1751,4365,2235,3430,3643,7492,4366, # 4406 294,3527,2940,1693, 477, 979, 281,2041,3528, 643,2042,3644,2621,2782,2261,1031, # 4422 2335,2134,2298,3529,4367, 367,1249,2552,7493,3530,7494,4368,1283,3325,2004, 240, # 4438 1762,3326,4369,4370, 836,1069,3128, 474,7495,2148,2525, 268,3531,7496,3188,1521, # 4454 1284,7497,1658,1546,4116,7498,3532,3533,7499,4117,3327,2684,1685,4118, 961,1673, # 4470 2622, 190,2005,2200,3762,4371,4372,7500, 570,2497,3645,1490,7501,4373,2623,3260, # 4486 1956,4374, 584,1514, 396,1045,1944,7502,4375,1967,2444,7503,7504,4376,3910, 619, # 4502 7505,3129,3261, 215,2006,2783,2553,3189,4377,3190,4378, 763,4119,3763,4379,7506, # 4518 7507,1957,1767,2941,3328,3646,1174, 452,1477,4380,3329,3130,7508,2825,1253,2382, # 4534 2186,1091,2285,4120, 492,7509, 638,1169,1824,2135,1752,3911, 648, 926,1021,1324, # 4550 4381, 520,4382, 997, 847,1007, 892,4383,3764,2262,1871,3647,7510,2400,1784,4384, # 4566 1952,2942,3080,3191,1728,4121,2043,3648,4385,2007,1701,3131,1551, 30,2263,4122, # 4582 7511,2026,4386,3534,7512, 501,7513,4123, 594,3431,2165,1821,3535,3432,3536,3192, # 4598 829,2826,4124,7514,1680,3132,1225,4125,7515,3262,4387,4126,3133,2336,7516,4388, # 4614 4127,7517,3912,3913,7518,1847,2383,2596,3330,7519,4389, 374,3914, 652,4128,4129, # 4630 375,1140, 798,7520,7521,7522,2361,4390,2264, 546,1659, 138,3031,2445,4391,7523, # 4646 2250, 612,1848, 910, 796,3765,1740,1371, 825,3766,3767,7524,2906,2554,7525, 692, # 4662 444,3032,2624, 801,4392,4130,7526,1491, 244,1053,3033,4131,4132, 340,7527,3915, # 4678 1041,2987, 293,1168, 87,1357,7528,1539, 959,7529,2236, 721, 694,4133,3768, 219, # 4694 1478, 644,1417,3331,2656,1413,1401,1335,1389,3916,7530,7531,2988,2362,3134,1825, # 4710 730,1515, 184,2827, 66,4393,7532,1660,2943, 246,3332, 378,1457, 226,3433, 975, # 4726 3917,2944,1264,3537, 674, 696,7533, 163,7534,1141,2417,2166, 713,3538,3333,4394, # 4742 3918,7535,7536,1186, 15,7537,1079,1070,7538,1522,3193,3539, 276,1050,2716, 758, # 4758 1126, 653,2945,3263,7539,2337, 889,3540,3919,3081,2989, 903,1250,4395,3920,3434, # 4774 3541,1342,1681,1718, 766,3264, 286, 89,2946,3649,7540,1713,7541,2597,3334,2990, # 4790 7542,2947,2215,3194,2866,7543,4396,2498,2526, 181, 387,1075,3921, 731,2187,3335, # 4806 7544,3265, 310, 313,3435,2299, 770,4134, 54,3034, 189,4397,3082,3769,3922,7545, # 4822 1230,1617,1849, 355,3542,4135,4398,3336, 111,4136,3650,1350,3135,3436,3035,4137, # 4838 2149,3266,3543,7546,2784,3923,3924,2991, 722,2008,7547,1071, 247,1207,2338,2471, # 4854 1378,4399,2009, 864,1437,1214,4400, 373,3770,1142,2216, 667,4401, 442,2753,2555, # 4870 3771,3925,1968,4138,3267,1839, 837, 170,1107, 934,1336,1882,7548,7549,2118,4139, # 4886 2828, 743,1569,7550,4402,4140, 582,2384,1418,3437,7551,1802,7552, 357,1395,1729, # 4902 3651,3268,2418,1564,2237,7553,3083,3772,1633,4403,1114,2085,4141,1532,7554, 482, # 4918 2446,4404,7555,7556,1492, 833,1466,7557,2717,3544,1641,2829,7558,1526,1272,3652, # 4934 4142,1686,1794, 416,2556,1902,1953,1803,7559,3773,2785,3774,1159,2316,7560,2867, # 4950 4405,1610,1584,3036,2419,2754, 443,3269,1163,3136,7561,7562,3926,7563,4143,2499, # 4966 3037,4406,3927,3137,2103,1647,3545,2010,1872,4144,7564,4145, 431,3438,7565, 250, # 4982 97, 81,4146,7566,1648,1850,1558, 160, 848,7567, 866, 740,1694,7568,2201,2830, # 4998 3195,4147,4407,3653,1687, 950,2472, 426, 469,3196,3654,3655,3928,7569,7570,1188, # 5014 424,1995, 861,3546,4148,3775,2202,2685, 168,1235,3547,4149,7571,2086,1674,4408, # 5030 3337,3270, 220,2557,1009,7572,3776, 670,2992, 332,1208, 717,7573,7574,3548,2447, # 5046 3929,3338,7575, 513,7576,1209,2868,3339,3138,4409,1080,7577,7578,7579,7580,2527, # 5062 3656,3549, 815,1587,3930,3931,7581,3550,3439,3777,1254,4410,1328,3038,1390,3932, # 5078 1741,3933,3778,3934,7582, 236,3779,2448,3271,7583,7584,3657,3780,1273,3781,4411, # 5094 7585, 308,7586,4412, 245,4413,1851,2473,1307,2575, 430, 715,2136,2449,7587, 270, # 5110 199,2869,3935,7588,3551,2718,1753, 761,1754, 725,1661,1840,4414,3440,3658,7589, # 5126 7590, 587, 14,3272, 227,2598, 326, 480,2265, 943,2755,3552, 291, 650,1883,7591, # 5142 1702,1226, 102,1547, 62,3441, 904,4415,3442,1164,4150,7592,7593,1224,1548,2756, # 5158 391, 498,1493,7594,1386,1419,7595,2055,1177,4416, 813, 880,1081,2363, 566,1145, # 5174 4417,2286,1001,1035,2558,2599,2238, 394,1286,7596,7597,2068,7598, 86,1494,1730, # 5190 3936, 491,1588, 745, 897,2948, 843,3340,3937,2757,2870,3273,1768, 998,2217,2069, # 5206 397,1826,1195,1969,3659,2993,3341, 284,7599,3782,2500,2137,2119,1903,7600,3938, # 5222 2150,3939,4151,1036,3443,1904, 114,2559,4152, 209,1527,7601,7602,2949,2831,2625, # 5238 2385,2719,3139, 812,2560,7603,3274,7604,1559, 737,1884,3660,1210, 885, 28,2686, # 5254 3553,3783,7605,4153,1004,1779,4418,7606, 346,1981,2218,2687,4419,3784,1742, 797, # 5270 1642,3940,1933,1072,1384,2151, 896,3941,3275,3661,3197,2871,3554,7607,2561,1958, # 5286 4420,2450,1785,7608,7609,7610,3942,4154,1005,1308,3662,4155,2720,4421,4422,1528, # 5302 2600, 161,1178,4156,1982, 987,4423,1101,4157, 631,3943,1157,3198,2420,1343,1241, # 5318 1016,2239,2562, 372, 877,2339,2501,1160, 555,1934, 911,3944,7611, 466,1170, 169, # 5334 1051,2907,2688,3663,2474,2994,1182,2011,2563,1251,2626,7612, 992,2340,3444,1540, # 5350 2721,1201,2070,2401,1996,2475,7613,4424, 528,1922,2188,1503,1873,1570,2364,3342, # 5366 3276,7614, 557,1073,7615,1827,3445,2087,2266,3140,3039,3084, 767,3085,2786,4425, # 5382 1006,4158,4426,2341,1267,2176,3664,3199, 778,3945,3200,2722,1597,2657,7616,4427, # 5398 7617,3446,7618,7619,7620,3277,2689,1433,3278, 131, 95,1504,3946, 723,4159,3141, # 5414 1841,3555,2758,2189,3947,2027,2104,3665,7621,2995,3948,1218,7622,3343,3201,3949, # 5430 4160,2576, 248,1634,3785, 912,7623,2832,3666,3040,3786, 654, 53,7624,2996,7625, # 5446 1688,4428, 777,3447,1032,3950,1425,7626, 191, 820,2120,2833, 971,4429, 931,3202, # 5462 135, 664, 783,3787,1997, 772,2908,1935,3951,3788,4430,2909,3203, 282,2723, 640, # 5478 1372,3448,1127, 922, 325,3344,7627,7628, 711,2044,7629,7630,3952,2219,2787,1936, # 5494 3953,3345,2220,2251,3789,2300,7631,4431,3790,1258,3279,3954,3204,2138,2950,3955, # 5510 3956,7632,2221, 258,3205,4432, 101,1227,7633,3280,1755,7634,1391,3281,7635,2910, # 5526 2056, 893,7636,7637,7638,1402,4161,2342,7639,7640,3206,3556,7641,7642, 878,1325, # 5542 1780,2788,4433, 259,1385,2577, 744,1183,2267,4434,7643,3957,2502,7644, 684,1024, # 5558 4162,7645, 472,3557,3449,1165,3282,3958,3959, 322,2152, 881, 455,1695,1152,1340, # 5574 660, 554,2153,4435,1058,4436,4163, 830,1065,3346,3960,4437,1923,7646,1703,1918, # 5590 7647, 932,2268, 122,7648,4438, 947, 677,7649,3791,2627, 297,1905,1924,2269,4439, # 5606 2317,3283,7650,7651,4164,7652,4165, 84,4166, 112, 989,7653, 547,1059,3961, 701, # 5622 3558,1019,7654,4167,7655,3450, 942, 639, 457,2301,2451, 993,2951, 407, 851, 494, # 5638 4440,3347, 927,7656,1237,7657,2421,3348, 573,4168, 680, 921,2911,1279,1874, 285, # 5654 790,1448,1983, 719,2167,7658,7659,4441,3962,3963,1649,7660,1541, 563,7661,1077, # 5670 7662,3349,3041,3451, 511,2997,3964,3965,3667,3966,1268,2564,3350,3207,4442,4443, # 5686 7663, 535,1048,1276,1189,2912,2028,3142,1438,1373,2834,2952,1134,2012,7664,4169, # 5702 1238,2578,3086,1259,7665, 700,7666,2953,3143,3668,4170,7667,4171,1146,1875,1906, # 5718 4444,2601,3967, 781,2422, 132,1589, 203, 147, 273,2789,2402, 898,1786,2154,3968, # 5734 3969,7668,3792,2790,7669,7670,4445,4446,7671,3208,7672,1635,3793, 965,7673,1804, # 5750 2690,1516,3559,1121,1082,1329,3284,3970,1449,3794, 65,1128,2835,2913,2759,1590, # 5766 3795,7674,7675, 12,2658, 45, 976,2579,3144,4447, 517,2528,1013,1037,3209,7676, # 5782 3796,2836,7677,3797,7678,3452,7679,2602, 614,1998,2318,3798,3087,2724,2628,7680, # 5798 2580,4172, 599,1269,7681,1810,3669,7682,2691,3088, 759,1060, 489,1805,3351,3285, # 5814 1358,7683,7684,2386,1387,1215,2629,2252, 490,7685,7686,4173,1759,2387,2343,7687, # 5830 4448,3799,1907,3971,2630,1806,3210,4449,3453,3286,2760,2344, 874,7688,7689,3454, # 5846 3670,1858, 91,2914,3671,3042,3800,4450,7690,3145,3972,2659,7691,3455,1202,1403, # 5862 3801,2954,2529,1517,2503,4451,3456,2504,7692,4452,7693,2692,1885,1495,1731,3973, # 5878 2365,4453,7694,2029,7695,7696,3974,2693,1216, 237,2581,4174,2319,3975,3802,4454, # 5894 4455,2694,3560,3457, 445,4456,7697,7698,7699,7700,2761, 61,3976,3672,1822,3977, # 5910 7701, 687,2045, 935, 925, 405,2660, 703,1096,1859,2725,4457,3978,1876,1367,2695, # 5926 3352, 918,2105,1781,2476, 334,3287,1611,1093,4458, 564,3146,3458,3673,3353, 945, # 5942 2631,2057,4459,7702,1925, 872,4175,7703,3459,2696,3089, 349,4176,3674,3979,4460, # 5958 3803,4177,3675,2155,3980,4461,4462,4178,4463,2403,2046, 782,3981, 400, 251,4179, # 5974 1624,7704,7705, 277,3676, 299,1265, 476,1191,3804,2121,4180,4181,1109, 205,7706, # 5990 2582,1000,2156,3561,1860,7707,7708,7709,4464,7710,4465,2565, 107,2477,2157,3982, # 6006 3460,3147,7711,1533, 541,1301, 158, 753,4182,2872,3562,7712,1696, 370,1088,4183, # 6022 4466,3563, 579, 327, 440, 162,2240, 269,1937,1374,3461, 968,3043, 56,1396,3090, # 6038 2106,3288,3354,7713,1926,2158,4467,2998,7714,3564,7715,7716,3677,4468,2478,7717, # 6054 2791,7718,1650,4469,7719,2603,7720,7721,3983,2661,3355,1149,3356,3984,3805,3985, # 6070 7722,1076, 49,7723, 951,3211,3289,3290, 450,2837, 920,7724,1811,2792,2366,4184, # 6086 1908,1138,2367,3806,3462,7725,3212,4470,1909,1147,1518,2423,4471,3807,7726,4472, # 6102 2388,2604, 260,1795,3213,7727,7728,3808,3291, 708,7729,3565,1704,7730,3566,1351, # 6118 1618,3357,2999,1886, 944,4185,3358,4186,3044,3359,4187,7731,3678, 422, 413,1714, # 6134 3292, 500,2058,2345,4188,2479,7732,1344,1910, 954,7733,1668,7734,7735,3986,2404, # 6150 4189,3567,3809,4190,7736,2302,1318,2505,3091, 133,3092,2873,4473, 629, 31,2838, # 6166 2697,3810,4474, 850, 949,4475,3987,2955,1732,2088,4191,1496,1852,7737,3988, 620, # 6182 3214, 981,1242,3679,3360,1619,3680,1643,3293,2139,2452,1970,1719,3463,2168,7738, # 6198 3215,7739,7740,3361,1828,7741,1277,4476,1565,2047,7742,1636,3568,3093,7743, 869, # 6214 2839, 655,3811,3812,3094,3989,3000,3813,1310,3569,4477,7744,7745,7746,1733, 558, # 6230 4478,3681, 335,1549,3045,1756,4192,3682,1945,3464,1829,1291,1192, 470,2726,2107, # 6246 2793, 913,1054,3990,7747,1027,7748,3046,3991,4479, 982,2662,3362,3148,3465,3216, # 6262 3217,1946,2794,7749, 571,4480,7750,1830,7751,3570,2583,1523,2424,7752,2089, 984, # 6278 4481,3683,1959,7753,3684, 852, 923,2795,3466,3685, 969,1519, 999,2048,2320,1705, # 6294 7754,3095, 615,1662, 151, 597,3992,2405,2321,1049, 275,4482,3686,4193, 568,3687, # 6310 3571,2480,4194,3688,7755,2425,2270, 409,3218,7756,1566,2874,3467,1002, 769,2840, # 6326 194,2090,3149,3689,2222,3294,4195, 628,1505,7757,7758,1763,2177,3001,3993, 521, # 6342 1161,2584,1787,2203,2406,4483,3994,1625,4196,4197, 412, 42,3096, 464,7759,2632, # 6358 4484,3363,1760,1571,2875,3468,2530,1219,2204,3814,2633,2140,2368,4485,4486,3295, # 6374 1651,3364,3572,7760,7761,3573,2481,3469,7762,3690,7763,7764,2271,2091, 460,7765, # 6390 4487,7766,3002, 962, 588,3574, 289,3219,2634,1116, 52,7767,3047,1796,7768,7769, # 6406 7770,1467,7771,1598,1143,3691,4198,1984,1734,1067,4488,1280,3365, 465,4489,1572, # 6422 510,7772,1927,2241,1812,1644,3575,7773,4490,3692,7774,7775,2663,1573,1534,7776, # 6438 7777,4199, 536,1807,1761,3470,3815,3150,2635,7778,7779,7780,4491,3471,2915,1911, # 6454 2796,7781,3296,1122, 377,3220,7782, 360,7783,7784,4200,1529, 551,7785,2059,3693, # 6470 1769,2426,7786,2916,4201,3297,3097,2322,2108,2030,4492,1404, 136,1468,1479, 672, # 6486 1171,3221,2303, 271,3151,7787,2762,7788,2049, 678,2727, 865,1947,4493,7789,2013, # 6502 3995,2956,7790,2728,2223,1397,3048,3694,4494,4495,1735,2917,3366,3576,7791,3816, # 6518 509,2841,2453,2876,3817,7792,7793,3152,3153,4496,4202,2531,4497,2304,1166,1010, # 6534 552, 681,1887,7794,7795,2957,2958,3996,1287,1596,1861,3154, 358, 453, 736, 175, # 6550 478,1117, 905,1167,1097,7796,1853,1530,7797,1706,7798,2178,3472,2287,3695,3473, # 6566 3577,4203,2092,4204,7799,3367,1193,2482,4205,1458,2190,2205,1862,1888,1421,3298, # 6582 2918,3049,2179,3474, 595,2122,7800,3997,7801,7802,4206,1707,2636, 223,3696,1359, # 6598 751,3098, 183,3475,7803,2797,3003, 419,2369, 633, 704,3818,2389, 241,7804,7805, # 6614 7806, 838,3004,3697,2272,2763,2454,3819,1938,2050,3998,1309,3099,2242,1181,7807, # 6630 1136,2206,3820,2370,1446,4207,2305,4498,7808,7809,4208,1055,2605, 484,3698,7810, # 6646 3999, 625,4209,2273,3368,1499,4210,4000,7811,4001,4211,3222,2274,2275,3476,7812, # 6662 7813,2764, 808,2606,3699,3369,4002,4212,3100,2532, 526,3370,3821,4213, 955,7814, # 6678 1620,4214,2637,2427,7815,1429,3700,1669,1831, 994, 928,7816,3578,1260,7817,7818, # 6694 7819,1948,2288, 741,2919,1626,4215,2729,2455, 867,1184, 362,3371,1392,7820,7821, # 6710 4003,4216,1770,1736,3223,2920,4499,4500,1928,2698,1459,1158,7822,3050,3372,2877, # 6726 1292,1929,2506,2842,3701,1985,1187,2071,2014,2607,4217,7823,2566,2507,2169,3702, # 6742 2483,3299,7824,3703,4501,7825,7826, 666,1003,3005,1022,3579,4218,7827,4502,1813, # 6758 2253, 574,3822,1603, 295,1535, 705,3823,4219, 283, 858, 417,7828,7829,3224,4503, # 6774 4504,3051,1220,1889,1046,2276,2456,4004,1393,1599, 689,2567, 388,4220,7830,2484, # 6790 802,7831,2798,3824,2060,1405,2254,7832,4505,3825,2109,1052,1345,3225,1585,7833, # 6806 809,7834,7835,7836, 575,2730,3477, 956,1552,1469,1144,2323,7837,2324,1560,2457, # 6822 3580,3226,4005, 616,2207,3155,2180,2289,7838,1832,7839,3478,4506,7840,1319,3704, # 6838 3705,1211,3581,1023,3227,1293,2799,7841,7842,7843,3826, 607,2306,3827, 762,2878, # 6854 1439,4221,1360,7844,1485,3052,7845,4507,1038,4222,1450,2061,2638,4223,1379,4508, # 6870 2585,7846,7847,4224,1352,1414,2325,2921,1172,7848,7849,3828,3829,7850,1797,1451, # 6886 7851,7852,7853,7854,2922,4006,4007,2485,2346, 411,4008,4009,3582,3300,3101,4509, # 6902 1561,2664,1452,4010,1375,7855,7856, 47,2959, 316,7857,1406,1591,2923,3156,7858, # 6918 1025,2141,3102,3157, 354,2731, 884,2224,4225,2407, 508,3706, 726,3583, 996,2428, # 6934 3584, 729,7859, 392,2191,1453,4011,4510,3707,7860,7861,2458,3585,2608,1675,2800, # 6950 919,2347,2960,2348,1270,4511,4012, 73,7862,7863, 647,7864,3228,2843,2255,1550, # 6966 1346,3006,7865,1332, 883,3479,7866,7867,7868,7869,3301,2765,7870,1212, 831,1347, # 6982 4226,4512,2326,3830,1863,3053, 720,3831,4513,4514,3832,7871,4227,7872,7873,4515, # 6998 7874,7875,1798,4516,3708,2609,4517,3586,1645,2371,7876,7877,2924, 669,2208,2665, # 7014 2429,7878,2879,7879,7880,1028,3229,7881,4228,2408,7882,2256,1353,7883,7884,4518, # 7030 3158, 518,7885,4013,7886,4229,1960,7887,2142,4230,7888,7889,3007,2349,2350,3833, # 7046 516,1833,1454,4014,2699,4231,4519,2225,2610,1971,1129,3587,7890,2766,7891,2961, # 7062 1422, 577,1470,3008,1524,3373,7892,7893, 432,4232,3054,3480,7894,2586,1455,2508, # 7078 2226,1972,1175,7895,1020,2732,4015,3481,4520,7896,2733,7897,1743,1361,3055,3482, # 7094 2639,4016,4233,4521,2290, 895, 924,4234,2170, 331,2243,3056, 166,1627,3057,1098, # 7110 7898,1232,2880,2227,3374,4522, 657, 403,1196,2372, 542,3709,3375,1600,4235,3483, # 7126 7899,4523,2767,3230, 576, 530,1362,7900,4524,2533,2666,3710,4017,7901, 842,3834, # 7142 7902,2801,2031,1014,4018, 213,2700,3376, 665, 621,4236,7903,3711,2925,2430,7904, # 7158 2431,3302,3588,3377,7905,4237,2534,4238,4525,3589,1682,4239,3484,1380,7906, 724, # 7174 2277, 600,1670,7907,1337,1233,4526,3103,2244,7908,1621,4527,7909, 651,4240,7910, # 7190 1612,4241,2611,7911,2844,7912,2734,2307,3058,7913, 716,2459,3059, 174,1255,2701, # 7206 4019,3590, 548,1320,1398, 728,4020,1574,7914,1890,1197,3060,4021,7915,3061,3062, # 7222 3712,3591,3713, 747,7916, 635,4242,4528,7917,7918,7919,4243,7920,7921,4529,7922, # 7238 3378,4530,2432, 451,7923,3714,2535,2072,4244,2735,4245,4022,7924,1764,4531,7925, # 7254 4246, 350,7926,2278,2390,2486,7927,4247,4023,2245,1434,4024, 488,4532, 458,4248, # 7270 4025,3715, 771,1330,2391,3835,2568,3159,2159,2409,1553,2667,3160,4249,7928,2487, # 7286 2881,2612,1720,2702,4250,3379,4533,7929,2536,4251,7930,3231,4252,2768,7931,2015, # 7302 2736,7932,1155,1017,3716,3836,7933,3303,2308, 201,1864,4253,1430,7934,4026,7935, # 7318 7936,7937,7938,7939,4254,1604,7940, 414,1865, 371,2587,4534,4535,3485,2016,3104, # 7334 4536,1708, 960,4255, 887, 389,2171,1536,1663,1721,7941,2228,4027,2351,2926,1580, # 7350 7942,7943,7944,1744,7945,2537,4537,4538,7946,4539,7947,2073,7948,7949,3592,3380, # 7366 2882,4256,7950,4257,2640,3381,2802, 673,2703,2460, 709,3486,4028,3593,4258,7951, # 7382 1148, 502, 634,7952,7953,1204,4540,3594,1575,4541,2613,3717,7954,3718,3105, 948, # 7398 3232, 121,1745,3837,1110,7955,4259,3063,2509,3009,4029,3719,1151,1771,3838,1488, # 7414 4030,1986,7956,2433,3487,7957,7958,2093,7959,4260,3839,1213,1407,2803, 531,2737, # 7430 2538,3233,1011,1537,7960,2769,4261,3106,1061,7961,3720,3721,1866,2883,7962,2017, # 7446 120,4262,4263,2062,3595,3234,2309,3840,2668,3382,1954,4542,7963,7964,3488,1047, # 7462 2704,1266,7965,1368,4543,2845, 649,3383,3841,2539,2738,1102,2846,2669,7966,7967, # 7478 1999,7968,1111,3596,2962,7969,2488,3842,3597,2804,1854,3384,3722,7970,7971,3385, # 7494 2410,2884,3304,3235,3598,7972,2569,7973,3599,2805,4031,1460, 856,7974,3600,7975, # 7510 2885,2963,7976,2886,3843,7977,4264, 632,2510, 875,3844,1697,3845,2291,7978,7979, # 7526 4544,3010,1239, 580,4545,4265,7980, 914, 936,2074,1190,4032,1039,2123,7981,7982, # 7542 7983,3386,1473,7984,1354,4266,3846,7985,2172,3064,4033, 915,3305,4267,4268,3306, # 7558 1605,1834,7986,2739, 398,3601,4269,3847,4034, 328,1912,2847,4035,3848,1331,4270, # 7574 3011, 937,4271,7987,3602,4036,4037,3387,2160,4546,3388, 524, 742, 538,3065,1012, # 7590 7988,7989,3849,2461,7990, 658,1103, 225,3850,7991,7992,4547,7993,4548,7994,3236, # 7606 1243,7995,4038, 963,2246,4549,7996,2705,3603,3161,7997,7998,2588,2327,7999,4550, # 7622 8000,8001,8002,3489,3307, 957,3389,2540,2032,1930,2927,2462, 870,2018,3604,1746, # 7638 2770,2771,2434,2463,8003,3851,8004,3723,3107,3724,3490,3390,3725,8005,1179,3066, # 7654 8006,3162,2373,4272,3726,2541,3163,3108,2740,4039,8007,3391,1556,2542,2292, 977, # 7670 2887,2033,4040,1205,3392,8008,1765,3393,3164,2124,1271,1689, 714,4551,3491,8009, # 7686 2328,3852, 533,4273,3605,2181, 617,8010,2464,3308,3492,2310,8011,8012,3165,8013, # 7702 8014,3853,1987, 618, 427,2641,3493,3394,8015,8016,1244,1690,8017,2806,4274,4552, # 7718 8018,3494,8019,8020,2279,1576, 473,3606,4275,3395, 972,8021,3607,8022,3067,8023, # 7734 8024,4553,4554,8025,3727,4041,4042,8026, 153,4555, 356,8027,1891,2888,4276,2143, # 7750 408, 803,2352,8028,3854,8029,4277,1646,2570,2511,4556,4557,3855,8030,3856,4278, # 7766 8031,2411,3396, 752,8032,8033,1961,2964,8034, 746,3012,2465,8035,4279,3728, 698, # 7782 4558,1892,4280,3608,2543,4559,3609,3857,8036,3166,3397,8037,1823,1302,4043,2706, # 7798 3858,1973,4281,8038,4282,3167, 823,1303,1288,1236,2848,3495,4044,3398, 774,3859, # 7814 8039,1581,4560,1304,2849,3860,4561,8040,2435,2161,1083,3237,4283,4045,4284, 344, # 7830 1173, 288,2311, 454,1683,8041,8042,1461,4562,4046,2589,8043,8044,4563, 985, 894, # 7846 8045,3399,3168,8046,1913,2928,3729,1988,8047,2110,1974,8048,4047,8049,2571,1194, # 7862 425,8050,4564,3169,1245,3730,4285,8051,8052,2850,8053, 636,4565,1855,3861, 760, # 7878 1799,8054,4286,2209,1508,4566,4048,1893,1684,2293,8055,8056,8057,4287,4288,2210, # 7894 479,8058,8059, 832,8060,4049,2489,8061,2965,2490,3731, 990,3109, 627,1814,2642, # 7910 4289,1582,4290,2125,2111,3496,4567,8062, 799,4291,3170,8063,4568,2112,1737,3013, # 7926 1018, 543, 754,4292,3309,1676,4569,4570,4050,8064,1489,8065,3497,8066,2614,2889, # 7942 4051,8067,8068,2966,8069,8070,8071,8072,3171,4571,4572,2182,1722,8073,3238,3239, # 7958 1842,3610,1715, 481, 365,1975,1856,8074,8075,1962,2491,4573,8076,2126,3611,3240, # 7974 433,1894,2063,2075,8077, 602,2741,8078,8079,8080,8081,8082,3014,1628,3400,8083, # 7990 3172,4574,4052,2890,4575,2512,8084,2544,2772,8085,8086,8087,3310,4576,2891,8088, # 8006 4577,8089,2851,4578,4579,1221,2967,4053,2513,8090,8091,8092,1867,1989,8093,8094, # 8022 8095,1895,8096,8097,4580,1896,4054, 318,8098,2094,4055,4293,8099,8100, 485,8101, # 8038 938,3862, 553,2670, 116,8102,3863,3612,8103,3498,2671,2773,3401,3311,2807,8104, # 8054 3613,2929,4056,1747,2930,2968,8105,8106, 207,8107,8108,2672,4581,2514,8109,3015, # 8070 890,3614,3864,8110,1877,3732,3402,8111,2183,2353,3403,1652,8112,8113,8114, 941, # 8086 2294, 208,3499,4057,2019, 330,4294,3865,2892,2492,3733,4295,8115,8116,8117,8118, # 8102 #Everything below is of no interest for detection purpose 2515,1613,4582,8119,3312,3866,2516,8120,4058,8121,1637,4059,2466,4583,3867,8122, # 8118 2493,3016,3734,8123,8124,2192,8125,8126,2162,8127,8128,8129,8130,8131,8132,8133, # 8134 8134,8135,8136,8137,8138,8139,8140,8141,8142,8143,8144,8145,8146,8147,8148,8149, # 8150 8150,8151,8152,8153,8154,8155,8156,8157,8158,8159,8160,8161,8162,8163,8164,8165, # 8166 8166,8167,8168,8169,8170,8171,8172,8173,8174,8175,8176,8177,8178,8179,8180,8181, # 8182 8182,8183,8184,8185,8186,8187,8188,8189,8190,8191,8192,8193,8194,8195,8196,8197, # 8198 8198,8199,8200,8201,8202,8203,8204,8205,8206,8207,8208,8209,8210,8211,8212,8213, # 8214 8214,8215,8216,8217,8218,8219,8220,8221,8222,8223,8224,8225,8226,8227,8228,8229, # 8230 8230,8231,8232,8233,8234,8235,8236,8237,8238,8239,8240,8241,8242,8243,8244,8245, # 8246 8246,8247,8248,8249,8250,8251,8252,8253,8254,8255,8256,8257,8258,8259,8260,8261, # 8262 8262,8263,8264,8265,8266,8267,8268,8269,8270,8271,8272,8273,8274,8275,8276,8277, # 8278 8278,8279,8280,8281,8282,8283,8284,8285,8286,8287,8288,8289,8290,8291,8292,8293, # 8294 8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,8304,8305,8306,8307,8308,8309, # 8310 8310,8311,8312,8313,8314,8315,8316,8317,8318,8319,8320,8321,8322,8323,8324,8325, # 8326 8326,8327,8328,8329,8330,8331,8332,8333,8334,8335,8336,8337,8338,8339,8340,8341, # 8342 8342,8343,8344,8345,8346,8347,8348,8349,8350,8351,8352,8353,8354,8355,8356,8357, # 8358 8358,8359,8360,8361,8362,8363,8364,8365,8366,8367,8368,8369,8370,8371,8372,8373, # 8374 8374,8375,8376,8377,8378,8379,8380,8381,8382,8383,8384,8385,8386,8387,8388,8389, # 8390 8390,8391,8392,8393,8394,8395,8396,8397,8398,8399,8400,8401,8402,8403,8404,8405, # 8406 8406,8407,8408,8409,8410,8411,8412,8413,8414,8415,8416,8417,8418,8419,8420,8421, # 8422 8422,8423,8424,8425,8426,8427,8428,8429,8430,8431,8432,8433,8434,8435,8436,8437, # 8438 8438,8439,8440,8441,8442,8443,8444,8445,8446,8447,8448,8449,8450,8451,8452,8453, # 8454 8454,8455,8456,8457,8458,8459,8460,8461,8462,8463,8464,8465,8466,8467,8468,8469, # 8470 8470,8471,8472,8473,8474,8475,8476,8477,8478,8479,8480,8481,8482,8483,8484,8485, # 8486 8486,8487,8488,8489,8490,8491,8492,8493,8494,8495,8496,8497,8498,8499,8500,8501, # 8502 8502,8503,8504,8505,8506,8507,8508,8509,8510,8511,8512,8513,8514,8515,8516,8517, # 8518 8518,8519,8520,8521,8522,8523,8524,8525,8526,8527,8528,8529,8530,8531,8532,8533, # 8534 8534,8535,8536,8537,8538,8539,8540,8541,8542,8543,8544,8545,8546,8547,8548,8549, # 8550 8550,8551,8552,8553,8554,8555,8556,8557,8558,8559,8560,8561,8562,8563,8564,8565, # 8566 8566,8567,8568,8569,8570,8571,8572,8573,8574,8575,8576,8577,8578,8579,8580,8581, # 8582 8582,8583,8584,8585,8586,8587,8588,8589,8590,8591,8592,8593,8594,8595,8596,8597, # 8598 8598,8599,8600,8601,8602,8603,8604,8605,8606,8607,8608,8609,8610,8611,8612,8613, # 8614 8614,8615,8616,8617,8618,8619,8620,8621,8622,8623,8624,8625,8626,8627,8628,8629, # 8630 8630,8631,8632,8633,8634,8635,8636,8637,8638,8639,8640,8641,8642,8643,8644,8645, # 8646 8646,8647,8648,8649,8650,8651,8652,8653,8654,8655,8656,8657,8658,8659,8660,8661, # 8662 8662,8663,8664,8665,8666,8667,8668,8669,8670,8671,8672,8673,8674,8675,8676,8677, # 8678 8678,8679,8680,8681,8682,8683,8684,8685,8686,8687,8688,8689,8690,8691,8692,8693, # 8694 8694,8695,8696,8697,8698,8699,8700,8701,8702,8703,8704,8705,8706,8707,8708,8709, # 8710 8710,8711,8712,8713,8714,8715,8716,8717,8718,8719,8720,8721,8722,8723,8724,8725, # 8726 8726,8727,8728,8729,8730,8731,8732,8733,8734,8735,8736,8737,8738,8739,8740,8741) # 8742
gpl-3.0
dpazel/music_rep
tests/transformation_tests/functions_tests/tonalfunctions_tests/test_tonality_permutation.py
1
1747
import logging import sys import unittest from tonalmodel.diatonic_tone import DiatonicTone from tonalmodel.diatonic_tone_cache import DiatonicToneCache from tonalmodel.modality import ModalityType from tonalmodel.tonality import Tonality from transformation.functions.tonalfunctions.tonality_permutation import TonalityPermutation class TestTonalityPermutation(unittest.TestCase): logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) def setUp(self): pass def tearDown(self): pass def test_simple_tonal_permutation(self): t_domain = Tonality.create(ModalityType.Major, DiatonicTone('E')) cycles = [['E', 'G#', 'A', 'B'], ('F#', 'G#')] p = TonalityPermutation(t_domain, cycles) print(p) assert DiatonicToneCache.get_tone('G#') == p['E'] assert DiatonicToneCache.get_tone('A') == p['F#'] assert DiatonicToneCache.get_tone('F#') == p['G#'] assert DiatonicToneCache.get_tone('B') == p['A'] assert DiatonicToneCache.get_tone('E') == p['B'] assert DiatonicToneCache.get_tone('C#') == p['C#'] assert DiatonicToneCache.get_tone('D#') == p['D#'] def test_simple_id(self): t_domain = Tonality.create(ModalityType.Major, DiatonicTone('E')) p = TonalityPermutation(t_domain) print(p) assert DiatonicToneCache.get_tone('E') == p['E'] assert DiatonicToneCache.get_tone('F#') == p['F#'] assert DiatonicToneCache.get_tone('G#') == p['G#'] assert DiatonicToneCache.get_tone('A') == p['A'] assert DiatonicToneCache.get_tone('B') == p['B'] assert DiatonicToneCache.get_tone('C#') == p['C#'] assert DiatonicToneCache.get_tone('D#') == p['D#']
mit
pschella/scipy
scipy/signal/tests/test_fir_filter_design.py
16
23142
from __future__ import division, print_function, absolute_import import warnings import numpy as np from numpy.testing import TestCase, run_module_suite, assert_raises, \ assert_almost_equal, assert_array_almost_equal, assert_equal, \ assert_, assert_allclose, assert_warns from scipy.special import sinc from scipy.signal import kaiser_beta, kaiser_atten, kaiserord, \ firwin, firwin2, freqz, remez, firls, minimum_phase def test_kaiser_beta(): b = kaiser_beta(58.7) assert_almost_equal(b, 0.1102 * 50.0) b = kaiser_beta(22.0) assert_almost_equal(b, 0.5842 + 0.07886) b = kaiser_beta(21.0) assert_equal(b, 0.0) b = kaiser_beta(10.0) assert_equal(b, 0.0) def test_kaiser_atten(): a = kaiser_atten(1, 1.0) assert_equal(a, 7.95) a = kaiser_atten(2, 1/np.pi) assert_equal(a, 2.285 + 7.95) def test_kaiserord(): assert_raises(ValueError, kaiserord, 1.0, 1.0) numtaps, beta = kaiserord(2.285 + 7.95 - 0.001, 1/np.pi) assert_equal((numtaps, beta), (2, 0.0)) class TestFirwin(TestCase): def check_response(self, h, expected_response, tol=.05): N = len(h) alpha = 0.5 * (N-1) m = np.arange(0,N) - alpha # time indices of taps for freq, expected in expected_response: actual = abs(np.sum(h*np.exp(-1.j*np.pi*m*freq))) mse = abs(actual-expected)**2 self.assertTrue(mse < tol, 'response not as expected, mse=%g > %g' % (mse, tol)) def test_response(self): N = 51 f = .5 # increase length just to try even/odd h = firwin(N, f) # low-pass from 0 to f self.check_response(h, [(.25,1), (.75,0)]) h = firwin(N+1, f, window='nuttall') # specific window self.check_response(h, [(.25,1), (.75,0)]) h = firwin(N+2, f, pass_zero=False) # stop from 0 to f --> high-pass self.check_response(h, [(.25,0), (.75,1)]) f1, f2, f3, f4 = .2, .4, .6, .8 h = firwin(N+3, [f1, f2], pass_zero=False) # band-pass filter self.check_response(h, [(.1,0), (.3,1), (.5,0)]) h = firwin(N+4, [f1, f2]) # band-stop filter self.check_response(h, [(.1,1), (.3,0), (.5,1)]) h = firwin(N+5, [f1, f2, f3, f4], pass_zero=False, scale=False) self.check_response(h, [(.1,0), (.3,1), (.5,0), (.7,1), (.9,0)]) h = firwin(N+6, [f1, f2, f3, f4]) # multiband filter self.check_response(h, [(.1,1), (.3,0), (.5,1), (.7,0), (.9,1)]) h = firwin(N+7, 0.1, width=.03) # low-pass self.check_response(h, [(.05,1), (.75,0)]) h = firwin(N+8, 0.1, pass_zero=False) # high-pass self.check_response(h, [(.05,0), (.75,1)]) def mse(self, h, bands): """Compute mean squared error versus ideal response across frequency band. h -- coefficients bands -- list of (left, right) tuples relative to 1==Nyquist of passbands """ w, H = freqz(h, worN=1024) f = w/np.pi passIndicator = np.zeros(len(w), bool) for left, right in bands: passIndicator |= (f >= left) & (f < right) Hideal = np.where(passIndicator, 1, 0) mse = np.mean(abs(abs(H)-Hideal)**2) return mse def test_scaling(self): """ For one lowpass, bandpass, and highpass example filter, this test checks two things: - the mean squared error over the frequency domain of the unscaled filter is smaller than the scaled filter (true for rectangular window) - the response of the scaled filter is exactly unity at the center of the first passband """ N = 11 cases = [ ([.5], True, (0, 1)), ([0.2, .6], False, (.4, 1)), ([.5], False, (1, 1)), ] for cutoff, pass_zero, expected_response in cases: h = firwin(N, cutoff, scale=False, pass_zero=pass_zero, window='ones') hs = firwin(N, cutoff, scale=True, pass_zero=pass_zero, window='ones') if len(cutoff) == 1: if pass_zero: cutoff = [0] + cutoff else: cutoff = cutoff + [1] self.assertTrue(self.mse(h, [cutoff]) < self.mse(hs, [cutoff]), 'least squares violation') self.check_response(hs, [expected_response], 1e-12) class TestFirWinMore(TestCase): """Different author, different style, different tests...""" def test_lowpass(self): width = 0.04 ntaps, beta = kaiserord(120, width) taps = firwin(ntaps, cutoff=0.5, window=('kaiser', beta), scale=False) # Check the symmetry of taps. assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) # Check the gain at a few samples where we know it should be approximately 0 or 1. freq_samples = np.array([0.0, 0.25, 0.5-width/2, 0.5+width/2, 0.75, 1.0]) freqs, response = freqz(taps, worN=np.pi*freq_samples) assert_array_almost_equal(np.abs(response), [1.0, 1.0, 1.0, 0.0, 0.0, 0.0], decimal=5) def test_highpass(self): width = 0.04 ntaps, beta = kaiserord(120, width) # Ensure that ntaps is odd. ntaps |= 1 taps = firwin(ntaps, cutoff=0.5, window=('kaiser', beta), pass_zero=False, scale=False) # Check the symmetry of taps. assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) # Check the gain at a few samples where we know it should be approximately 0 or 1. freq_samples = np.array([0.0, 0.25, 0.5-width/2, 0.5+width/2, 0.75, 1.0]) freqs, response = freqz(taps, worN=np.pi*freq_samples) assert_array_almost_equal(np.abs(response), [0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5) def test_bandpass(self): width = 0.04 ntaps, beta = kaiserord(120, width) taps = firwin(ntaps, cutoff=[0.3, 0.7], window=('kaiser', beta), pass_zero=False, scale=False) # Check the symmetry of taps. assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) # Check the gain at a few samples where we know it should be approximately 0 or 1. freq_samples = np.array([0.0, 0.2, 0.3-width/2, 0.3+width/2, 0.5, 0.7-width/2, 0.7+width/2, 0.8, 1.0]) freqs, response = freqz(taps, worN=np.pi*freq_samples) assert_array_almost_equal(np.abs(response), [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0], decimal=5) def test_multi(self): width = 0.04 ntaps, beta = kaiserord(120, width) taps = firwin(ntaps, cutoff=[0.2, 0.5, 0.8], window=('kaiser', beta), pass_zero=True, scale=False) # Check the symmetry of taps. assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) # Check the gain at a few samples where we know it should be approximately 0 or 1. freq_samples = np.array([0.0, 0.1, 0.2-width/2, 0.2+width/2, 0.35, 0.5-width/2, 0.5+width/2, 0.65, 0.8-width/2, 0.8+width/2, 0.9, 1.0]) freqs, response = freqz(taps, worN=np.pi*freq_samples) assert_array_almost_equal(np.abs(response), [1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0], decimal=5) def test_nyq(self): """Test the nyq keyword.""" nyquist = 1000 width = 40.0 relative_width = width/nyquist ntaps, beta = kaiserord(120, relative_width) taps = firwin(ntaps, cutoff=[300, 700], window=('kaiser', beta), pass_zero=False, scale=False, nyq=nyquist) # Check the symmetry of taps. assert_array_almost_equal(taps[:ntaps//2], taps[ntaps:ntaps-ntaps//2-1:-1]) # Check the gain at a few samples where we know it should be approximately 0 or 1. freq_samples = np.array([0.0, 200, 300-width/2, 300+width/2, 500, 700-width/2, 700+width/2, 800, 1000]) freqs, response = freqz(taps, worN=np.pi*freq_samples/nyquist) assert_array_almost_equal(np.abs(response), [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0], decimal=5) def test_bad_cutoff(self): """Test that invalid cutoff argument raises ValueError.""" # cutoff values must be greater than 0 and less than 1. assert_raises(ValueError, firwin, 99, -0.5) assert_raises(ValueError, firwin, 99, 1.5) # Don't allow 0 or 1 in cutoff. assert_raises(ValueError, firwin, 99, [0, 0.5]) assert_raises(ValueError, firwin, 99, [0.5, 1]) # cutoff values must be strictly increasing. assert_raises(ValueError, firwin, 99, [0.1, 0.5, 0.2]) assert_raises(ValueError, firwin, 99, [0.1, 0.5, 0.5]) # Must have at least one cutoff value. assert_raises(ValueError, firwin, 99, []) # 2D array not allowed. assert_raises(ValueError, firwin, 99, [[0.1, 0.2],[0.3, 0.4]]) # cutoff values must be less than nyq. assert_raises(ValueError, firwin, 99, 50.0, nyq=40) assert_raises(ValueError, firwin, 99, [10, 20, 30], nyq=25) def test_even_highpass_raises_value_error(self): """Test that attempt to create a highpass filter with an even number of taps raises a ValueError exception.""" assert_raises(ValueError, firwin, 40, 0.5, pass_zero=False) assert_raises(ValueError, firwin, 40, [.25, 0.5]) class TestFirwin2(TestCase): def test_invalid_args(self): # `freq` and `gain` have different lengths. assert_raises(ValueError, firwin2, 50, [0, 0.5, 1], [0.0, 1.0]) # `nfreqs` is less than `ntaps`. assert_raises(ValueError, firwin2, 50, [0, 0.5, 1], [0.0, 1.0, 1.0], nfreqs=33) # Decreasing value in `freq` assert_raises(ValueError, firwin2, 50, [0, 0.5, 0.4, 1.0], [0, .25, .5, 1.0]) # Value in `freq` repeated more than once. assert_raises(ValueError, firwin2, 50, [0, .1, .1, .1, 1.0], [0.0, 0.5, 0.75, 1.0, 1.0]) # `freq` does not start at 0.0. assert_raises(ValueError, firwin2, 50, [0.5, 1.0], [0.0, 1.0]) # Type II filter, but the gain at nyquist rate is not zero. assert_raises(ValueError, firwin2, 16, [0.0, 0.5, 1.0], [0.0, 1.0, 1.0]) # Type III filter, but the gains at nyquist and zero rate are not zero. assert_raises(ValueError, firwin2, 17, [0.0, 0.5, 1.0], [0.0, 1.0, 1.0], antisymmetric=True) assert_raises(ValueError, firwin2, 17, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0], antisymmetric=True) assert_raises(ValueError, firwin2, 17, [0.0, 0.5, 1.0], [1.0, 1.0, 1.0], antisymmetric=True) # Type VI filter, but the gain at zero rate is not zero. assert_raises(ValueError, firwin2, 16, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0], antisymmetric=True) def test01(self): width = 0.04 beta = 12.0 ntaps = 400 # Filter is 1 from w=0 to w=0.5, then decreases linearly from 1 to 0 as w # increases from w=0.5 to w=1 (w=1 is the Nyquist frequency). freq = [0.0, 0.5, 1.0] gain = [1.0, 1.0, 0.0] taps = firwin2(ntaps, freq, gain, window=('kaiser', beta)) freq_samples = np.array([0.0, 0.25, 0.5-width/2, 0.5+width/2, 0.75, 1.0-width/2]) freqs, response = freqz(taps, worN=np.pi*freq_samples) assert_array_almost_equal(np.abs(response), [1.0, 1.0, 1.0, 1.0-width, 0.5, width], decimal=5) def test02(self): width = 0.04 beta = 12.0 # ntaps must be odd for positive gain at Nyquist. ntaps = 401 # An ideal highpass filter. freq = [0.0, 0.5, 0.5, 1.0] gain = [0.0, 0.0, 1.0, 1.0] taps = firwin2(ntaps, freq, gain, window=('kaiser', beta)) freq_samples = np.array([0.0, 0.25, 0.5-width, 0.5+width, 0.75, 1.0]) freqs, response = freqz(taps, worN=np.pi*freq_samples) assert_array_almost_equal(np.abs(response), [0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5) def test03(self): width = 0.02 ntaps, beta = kaiserord(120, width) # ntaps must be odd for positive gain at Nyquist. ntaps = int(ntaps) | 1 freq = [0.0, 0.4, 0.4, 0.5, 0.5, 1.0] gain = [1.0, 1.0, 0.0, 0.0, 1.0, 1.0] taps = firwin2(ntaps, freq, gain, window=('kaiser', beta)) freq_samples = np.array([0.0, 0.4-width, 0.4+width, 0.45, 0.5-width, 0.5+width, 0.75, 1.0]) freqs, response = freqz(taps, worN=np.pi*freq_samples) assert_array_almost_equal(np.abs(response), [1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0], decimal=5) def test04(self): """Test firwin2 when window=None.""" ntaps = 5 # Ideal lowpass: gain is 1 on [0,0.5], and 0 on [0.5, 1.0] freq = [0.0, 0.5, 0.5, 1.0] gain = [1.0, 1.0, 0.0, 0.0] taps = firwin2(ntaps, freq, gain, window=None, nfreqs=8193) alpha = 0.5 * (ntaps - 1) m = np.arange(0, ntaps) - alpha h = 0.5 * sinc(0.5 * m) assert_array_almost_equal(h, taps) def test05(self): """Test firwin2 for calculating Type IV filters""" ntaps = 1500 freq = [0.0, 1.0] gain = [0.0, 1.0] taps = firwin2(ntaps, freq, gain, window=None, antisymmetric=True) assert_array_almost_equal(taps[: ntaps // 2], -taps[ntaps // 2:][::-1]) freqs, response = freqz(taps, worN=2048) assert_array_almost_equal(abs(response), freqs / np.pi, decimal=4) def test06(self): """Test firwin2 for calculating Type III filters""" ntaps = 1501 freq = [0.0, 0.5, 0.55, 1.0] gain = [0.0, 0.5, 0.0, 0.0] taps = firwin2(ntaps, freq, gain, window=None, antisymmetric=True) assert_equal(taps[ntaps // 2], 0.0) assert_array_almost_equal(taps[: ntaps // 2], -taps[ntaps // 2 + 1:][::-1]) freqs, response1 = freqz(taps, worN=2048) response2 = np.interp(freqs / np.pi, freq, gain) assert_array_almost_equal(abs(response1), response2, decimal=3) def test_nyq(self): taps1 = firwin2(80, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0]) taps2 = firwin2(80, [0.0, 30.0, 60.0], [1.0, 1.0, 0.0], nyq=60.0) assert_array_almost_equal(taps1, taps2) class TestRemez(TestCase): def test_bad_args(self): assert_raises(ValueError, remez, 11, [0.1, 0.4], [1], type='pooka') def test_hilbert(self): N = 11 # number of taps in the filter a = 0.1 # width of the transition band # design an unity gain hilbert bandpass filter from w to 0.5-w h = remez(11, [a, 0.5-a], [1], type='hilbert') # make sure the filter has correct # of taps assert_(len(h) == N, "Number of Taps") # make sure it is type III (anti-symmetric tap coefficients) assert_array_almost_equal(h[:(N-1)//2], -h[:-(N-1)//2-1:-1]) # Since the requested response is symmetric, all even coeffcients # should be zero (or in this case really small) assert_((abs(h[1::2]) < 1e-15).all(), "Even Coefficients Equal Zero") # now check the frequency response w, H = freqz(h, 1) f = w/2/np.pi Hmag = abs(H) # should have a zero at 0 and pi (in this case close to zero) assert_((Hmag[[0, -1]] < 0.02).all(), "Zero at zero and pi") # check that the pass band is close to unity idx = np.logical_and(f > a, f < 0.5-a) assert_((abs(Hmag[idx] - 1) < 0.015).all(), "Pass Band Close To Unity") def test_compare(self): # test comparison to MATLAB k = [0.024590270518440, -0.041314581814658, -0.075943803756711, -0.003530911231040, 0.193140296954975, 0.373400753484939, 0.373400753484939, 0.193140296954975, -0.003530911231040, -0.075943803756711, -0.041314581814658, 0.024590270518440] h = remez(12, [0, 0.3, 0.5, 1], [1, 0], Hz=2.) assert_allclose(h, k) h = [-0.038976016082299, 0.018704846485491, -0.014644062687875, 0.002879152556419, 0.016849978528150, -0.043276706138248, 0.073641298245579, -0.103908158578635, 0.129770906801075, -0.147163447297124, 0.153302248456347, -0.147163447297124, 0.129770906801075, -0.103908158578635, 0.073641298245579, -0.043276706138248, 0.016849978528150, 0.002879152556419, -0.014644062687875, 0.018704846485491, -0.038976016082299] assert_allclose(remez(21, [0, 0.8, 0.9, 1], [0, 1], Hz=2.), h) class TestFirls(TestCase): def test_bad_args(self): # even numtaps assert_raises(ValueError, firls, 10, [0.1, 0.2], [0, 0]) # odd bands assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.4], [0, 0, 0]) # len(bands) != len(desired) assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.3, 0.4], [0, 0, 0]) # non-monotonic bands assert_raises(ValueError, firls, 11, [0.2, 0.1], [0, 0]) assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.3, 0.3], [0] * 4) assert_raises(ValueError, firls, 11, [0.3, 0.4, 0.1, 0.2], [0] * 4) assert_raises(ValueError, firls, 11, [0.1, 0.3, 0.2, 0.4], [0] * 4) # negative desired assert_raises(ValueError, firls, 11, [0.1, 0.2], [-1, 1]) # len(weight) != len(pairs) assert_raises(ValueError, firls, 11, [0.1, 0.2], [0, 0], [1, 2]) # negative weight assert_raises(ValueError, firls, 11, [0.1, 0.2], [0, 0], [-1]) def test_firls(self): N = 11 # number of taps in the filter a = 0.1 # width of the transition band # design a halfband symmetric low-pass filter h = firls(11, [0, a, 0.5-a, 0.5], [1, 1, 0, 0], nyq=0.5) # make sure the filter has correct # of taps assert_equal(len(h), N) # make sure it is symmetric midx = (N-1) // 2 assert_array_almost_equal(h[:midx], h[:-midx-1:-1]) # make sure the center tap is 0.5 assert_almost_equal(h[midx], 0.5) # For halfband symmetric, odd coefficients (except the center) # should be zero (really small) hodd = np.hstack((h[1:midx:2], h[-midx+1::2])) assert_array_almost_equal(hodd, 0) # now check the frequency response w, H = freqz(h, 1) f = w/2/np.pi Hmag = np.abs(H) # check that the pass band is close to unity idx = np.logical_and(f > 0, f < a) assert_array_almost_equal(Hmag[idx], 1, decimal=3) # check that the stop band is close to zero idx = np.logical_and(f > 0.5-a, f < 0.5) assert_array_almost_equal(Hmag[idx], 0, decimal=3) def test_compare(self): # compare to OCTAVE output taps = firls(9, [0, 0.5, 0.55, 1], [1, 1, 0, 0], [1, 2]) # >> taps = firls(8, [0 0.5 0.55 1], [1 1 0 0], [1, 2]); known_taps = [-6.26930101730182e-04, -1.03354450635036e-01, -9.81576747564301e-03, 3.17271686090449e-01, 5.11409425599933e-01, 3.17271686090449e-01, -9.81576747564301e-03, -1.03354450635036e-01, -6.26930101730182e-04] assert_allclose(taps, known_taps) # compare to MATLAB output taps = firls(11, [0, 0.5, 0.5, 1], [1, 1, 0, 0], [1, 2]) # >> taps = firls(10, [0 0.5 0.5 1], [1 1 0 0], [1, 2]); known_taps = [ 0.058545300496815, -0.014233383714318, -0.104688258464392, 0.012403323025279, 0.317930861136062, 0.488047220029700, 0.317930861136062, 0.012403323025279, -0.104688258464392, -0.014233383714318, 0.058545300496815] assert_allclose(taps, known_taps) # With linear changes: taps = firls(7, (0, 1, 2, 3, 4, 5), [1, 0, 0, 1, 1, 0], nyq=10) # >> taps = firls(6, [0, 0.1, 0.2, 0.3, 0.4, 0.5], [1, 0, 0, 1, 1, 0]) known_taps = [ 1.156090832768218, -4.1385894727395849, 7.5288619164321826, -8.5530572592947856, 7.5288619164321826, -4.1385894727395849, 1.156090832768218] assert_allclose(taps, known_taps) class TestMinimumPhase(TestCase): def test_bad_args(self): # not enough taps assert_raises(ValueError, minimum_phase, [1.]) assert_raises(ValueError, minimum_phase, [1., 1.]) assert_raises(ValueError, minimum_phase, np.ones(10) * 1j) assert_raises(ValueError, minimum_phase, 'foo') assert_raises(ValueError, minimum_phase, np.ones(10), n_fft=8) assert_raises(ValueError, minimum_phase, np.ones(10), method='foo') with warnings.catch_warnings(): warnings.simplefilter("ignore") assert_warns(RuntimeWarning, minimum_phase, np.arange(3)) def test_homomorphic(self): # check that it can recover frequency responses of arbitrary # linear-phase filters # for some cases we can get the actual filter back h = [1, -1] h_new = minimum_phase(np.convolve(h, h[::-1])) assert_allclose(h_new, h, rtol=0.05) # but in general we only guarantee we get the magnitude back rng = np.random.RandomState(0) for n in (2, 3, 10, 11, 15, 16, 17, 20, 21, 100, 101): h = rng.randn(n) h_new = minimum_phase(np.convolve(h, h[::-1])) assert_allclose(np.abs(np.fft.fft(h_new)), np.abs(np.fft.fft(h)), rtol=1e-4) def test_hilbert(self): # compare to MATLAB output of reference implementation # f=[0 0.3 0.5 1]; # a=[1 1 0 0]; # h=remez(11,f,a); h = remez(12, [0, 0.3, 0.5, 1], [1, 0], Hz=2.) k = [0.349585548646686, 0.373552164395447, 0.326082685363438, 0.077152207480935, -0.129943946349364, -0.059355880509749] m = minimum_phase(h, 'hilbert') assert_allclose(m, k, rtol=1e-3) # f=[0 0.8 0.9 1]; # a=[0 0 1 1]; # h=remez(20,f,a); h = remez(21, [0, 0.8, 0.9, 1], [0, 1], Hz=2.) k = [0.232486803906329, -0.133551833687071, 0.151871456867244, -0.157957283165866, 0.151739294892963, -0.129293146705090, 0.100787844523204, -0.065832656741252, 0.035361328741024, -0.014977068692269, -0.158416139047557] m = minimum_phase(h, 'hilbert', n_fft=2**19) assert_allclose(m, k, rtol=1e-3) if __name__ == "__main__": run_module_suite()
bsd-3-clause
vashzsun/fund_analysis
fund_data/dataProcess.py
1
2664
__author__ = 'Seven1' import json import os,sys sys.path.insert(0,os.path.dirname(sys.path[0]))#外部设置项目目录为搜索路径, 确保正确的包引用 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "fund_analysis.settings") #导入django设置, 才能正常运行 from fund_data.models import FundInfo from datetime import datetime class FundProcess: fund_count = 0 def getFundDataFromJsonFile(self,filePath): if os.path.exists(filePath): try: jsonFile = open(filePath,encoding='utf-8') json = jsonFile.read() finally: jsonFile.close() #print('close file') return json else: return 'false' def saveFundsData(self,jsonData): fundsDict = json.loads(jsonData) x = 0 for fundData in fundsDict['result'][0]: print(fundsDict['result'][0][fundData]['code']) returnDate = fundsDict['result'][0][fundData]['time'] formatDate = datetime.strptime(returnDate,'%Y年%m月%d日 ') #格式化处理中文时间 returnNewnet = self.convent_fundata_to_float(fundsDict,fundData,'newnet') returnTotalnet = self.convent_fundata_to_float(fundsDict,fundData,'totalnet') returnDayincrease = self.convent_fundata_to_float(fundsDict,fundData,'dayincrease') returnDaygrowrate = self.convent_fundata_to_float(fundsDict,fundData,'daygrowrate') returnWeekgrowrate = self.convent_fundata_to_float(fundsDict,fundData,'weekgrowrate') returnMonthgrowrate = self.convent_fundata_to_float(fundsDict,fundData,'monthgrowrate') returnAnnualincome = self.convent_fundata_to_float(fundsDict,fundData,'annualincome') newData = FundInfo( code=fundsDict['result'][0][fundData]['code'], name=fundsDict['result'][0][fundData]['name'], newnet=returnNewnet, totalnet=returnTotalnet, dayincrease=returnDayincrease, daygrowrate=returnDaygrowrate, weekgrowrate=returnWeekgrowrate, monthgrowrate=returnMonthgrowrate, annualincome=returnAnnualincome, time=formatDate ) x += 1 print(x) newData.save() def convent_fundata_to_float(self,fundsDict,fundData,valueName): if fundsDict['result'][0][fundData][valueName] == 'null' or fundsDict['result'][0][fundData][valueName] == '': return 0 else: return float(fundsDict['result'][0][fundData][valueName])
apache-2.0
crosick/zhishu
ENV/lib/python2.7/encodings/ptcp154.py
647
8950
""" Python Character Mapping Codec generated from 'PTCP154.txt' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_map) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_map)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_map)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='ptcp154', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x0496, # CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER 0x0081: 0x0492, # CYRILLIC CAPITAL LETTER GHE WITH STROKE 0x0082: 0x04ee, # CYRILLIC CAPITAL LETTER U WITH MACRON 0x0083: 0x0493, # CYRILLIC SMALL LETTER GHE WITH STROKE 0x0084: 0x201e, # DOUBLE LOW-9 QUOTATION MARK 0x0085: 0x2026, # HORIZONTAL ELLIPSIS 0x0086: 0x04b6, # CYRILLIC CAPITAL LETTER CHE WITH DESCENDER 0x0087: 0x04ae, # CYRILLIC CAPITAL LETTER STRAIGHT U 0x0088: 0x04b2, # CYRILLIC CAPITAL LETTER HA WITH DESCENDER 0x0089: 0x04af, # CYRILLIC SMALL LETTER STRAIGHT U 0x008a: 0x04a0, # CYRILLIC CAPITAL LETTER BASHKIR KA 0x008b: 0x04e2, # CYRILLIC CAPITAL LETTER I WITH MACRON 0x008c: 0x04a2, # CYRILLIC CAPITAL LETTER EN WITH DESCENDER 0x008d: 0x049a, # CYRILLIC CAPITAL LETTER KA WITH DESCENDER 0x008e: 0x04ba, # CYRILLIC CAPITAL LETTER SHHA 0x008f: 0x04b8, # CYRILLIC CAPITAL LETTER CHE WITH VERTICAL STROKE 0x0090: 0x0497, # CYRILLIC SMALL LETTER ZHE WITH DESCENDER 0x0091: 0x2018, # LEFT SINGLE QUOTATION MARK 0x0092: 0x2019, # RIGHT SINGLE QUOTATION MARK 0x0093: 0x201c, # LEFT DOUBLE QUOTATION MARK 0x0094: 0x201d, # RIGHT DOUBLE QUOTATION MARK 0x0095: 0x2022, # BULLET 0x0096: 0x2013, # EN DASH 0x0097: 0x2014, # EM DASH 0x0098: 0x04b3, # CYRILLIC SMALL LETTER HA WITH DESCENDER 0x0099: 0x04b7, # CYRILLIC SMALL LETTER CHE WITH DESCENDER 0x009a: 0x04a1, # CYRILLIC SMALL LETTER BASHKIR KA 0x009b: 0x04e3, # CYRILLIC SMALL LETTER I WITH MACRON 0x009c: 0x04a3, # CYRILLIC SMALL LETTER EN WITH DESCENDER 0x009d: 0x049b, # CYRILLIC SMALL LETTER KA WITH DESCENDER 0x009e: 0x04bb, # CYRILLIC SMALL LETTER SHHA 0x009f: 0x04b9, # CYRILLIC SMALL LETTER CHE WITH VERTICAL STROKE 0x00a1: 0x040e, # CYRILLIC CAPITAL LETTER SHORT U (Byelorussian) 0x00a2: 0x045e, # CYRILLIC SMALL LETTER SHORT U (Byelorussian) 0x00a3: 0x0408, # CYRILLIC CAPITAL LETTER JE 0x00a4: 0x04e8, # CYRILLIC CAPITAL LETTER BARRED O 0x00a5: 0x0498, # CYRILLIC CAPITAL LETTER ZE WITH DESCENDER 0x00a6: 0x04b0, # CYRILLIC CAPITAL LETTER STRAIGHT U WITH STROKE 0x00a8: 0x0401, # CYRILLIC CAPITAL LETTER IO 0x00aa: 0x04d8, # CYRILLIC CAPITAL LETTER SCHWA 0x00ad: 0x04ef, # CYRILLIC SMALL LETTER U WITH MACRON 0x00af: 0x049c, # CYRILLIC CAPITAL LETTER KA WITH VERTICAL STROKE 0x00b1: 0x04b1, # CYRILLIC SMALL LETTER STRAIGHT U WITH STROKE 0x00b2: 0x0406, # CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I 0x00b3: 0x0456, # CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I 0x00b4: 0x0499, # CYRILLIC SMALL LETTER ZE WITH DESCENDER 0x00b5: 0x04e9, # CYRILLIC SMALL LETTER BARRED O 0x00b8: 0x0451, # CYRILLIC SMALL LETTER IO 0x00b9: 0x2116, # NUMERO SIGN 0x00ba: 0x04d9, # CYRILLIC SMALL LETTER SCHWA 0x00bc: 0x0458, # CYRILLIC SMALL LETTER JE 0x00bd: 0x04aa, # CYRILLIC CAPITAL LETTER ES WITH DESCENDER 0x00be: 0x04ab, # CYRILLIC SMALL LETTER ES WITH DESCENDER 0x00bf: 0x049d, # CYRILLIC SMALL LETTER KA WITH VERTICAL STROKE 0x00c0: 0x0410, # CYRILLIC CAPITAL LETTER A 0x00c1: 0x0411, # CYRILLIC CAPITAL LETTER BE 0x00c2: 0x0412, # CYRILLIC CAPITAL LETTER VE 0x00c3: 0x0413, # CYRILLIC CAPITAL LETTER GHE 0x00c4: 0x0414, # CYRILLIC CAPITAL LETTER DE 0x00c5: 0x0415, # CYRILLIC CAPITAL LETTER IE 0x00c6: 0x0416, # CYRILLIC CAPITAL LETTER ZHE 0x00c7: 0x0417, # CYRILLIC CAPITAL LETTER ZE 0x00c8: 0x0418, # CYRILLIC CAPITAL LETTER I 0x00c9: 0x0419, # CYRILLIC CAPITAL LETTER SHORT I 0x00ca: 0x041a, # CYRILLIC CAPITAL LETTER KA 0x00cb: 0x041b, # CYRILLIC CAPITAL LETTER EL 0x00cc: 0x041c, # CYRILLIC CAPITAL LETTER EM 0x00cd: 0x041d, # CYRILLIC CAPITAL LETTER EN 0x00ce: 0x041e, # CYRILLIC CAPITAL LETTER O 0x00cf: 0x041f, # CYRILLIC CAPITAL LETTER PE 0x00d0: 0x0420, # CYRILLIC CAPITAL LETTER ER 0x00d1: 0x0421, # CYRILLIC CAPITAL LETTER ES 0x00d2: 0x0422, # CYRILLIC CAPITAL LETTER TE 0x00d3: 0x0423, # CYRILLIC CAPITAL LETTER U 0x00d4: 0x0424, # CYRILLIC CAPITAL LETTER EF 0x00d5: 0x0425, # CYRILLIC CAPITAL LETTER HA 0x00d6: 0x0426, # CYRILLIC CAPITAL LETTER TSE 0x00d7: 0x0427, # CYRILLIC CAPITAL LETTER CHE 0x00d8: 0x0428, # CYRILLIC CAPITAL LETTER SHA 0x00d9: 0x0429, # CYRILLIC CAPITAL LETTER SHCHA 0x00da: 0x042a, # CYRILLIC CAPITAL LETTER HARD SIGN 0x00db: 0x042b, # CYRILLIC CAPITAL LETTER YERU 0x00dc: 0x042c, # CYRILLIC CAPITAL LETTER SOFT SIGN 0x00dd: 0x042d, # CYRILLIC CAPITAL LETTER E 0x00de: 0x042e, # CYRILLIC CAPITAL LETTER YU 0x00df: 0x042f, # CYRILLIC CAPITAL LETTER YA 0x00e0: 0x0430, # CYRILLIC SMALL LETTER A 0x00e1: 0x0431, # CYRILLIC SMALL LETTER BE 0x00e2: 0x0432, # CYRILLIC SMALL LETTER VE 0x00e3: 0x0433, # CYRILLIC SMALL LETTER GHE 0x00e4: 0x0434, # CYRILLIC SMALL LETTER DE 0x00e5: 0x0435, # CYRILLIC SMALL LETTER IE 0x00e6: 0x0436, # CYRILLIC SMALL LETTER ZHE 0x00e7: 0x0437, # CYRILLIC SMALL LETTER ZE 0x00e8: 0x0438, # CYRILLIC SMALL LETTER I 0x00e9: 0x0439, # CYRILLIC SMALL LETTER SHORT I 0x00ea: 0x043a, # CYRILLIC SMALL LETTER KA 0x00eb: 0x043b, # CYRILLIC SMALL LETTER EL 0x00ec: 0x043c, # CYRILLIC SMALL LETTER EM 0x00ed: 0x043d, # CYRILLIC SMALL LETTER EN 0x00ee: 0x043e, # CYRILLIC SMALL LETTER O 0x00ef: 0x043f, # CYRILLIC SMALL LETTER PE 0x00f0: 0x0440, # CYRILLIC SMALL LETTER ER 0x00f1: 0x0441, # CYRILLIC SMALL LETTER ES 0x00f2: 0x0442, # CYRILLIC SMALL LETTER TE 0x00f3: 0x0443, # CYRILLIC SMALL LETTER U 0x00f4: 0x0444, # CYRILLIC SMALL LETTER EF 0x00f5: 0x0445, # CYRILLIC SMALL LETTER HA 0x00f6: 0x0446, # CYRILLIC SMALL LETTER TSE 0x00f7: 0x0447, # CYRILLIC SMALL LETTER CHE 0x00f8: 0x0448, # CYRILLIC SMALL LETTER SHA 0x00f9: 0x0449, # CYRILLIC SMALL LETTER SHCHA 0x00fa: 0x044a, # CYRILLIC SMALL LETTER HARD SIGN 0x00fb: 0x044b, # CYRILLIC SMALL LETTER YERU 0x00fc: 0x044c, # CYRILLIC SMALL LETTER SOFT SIGN 0x00fd: 0x044d, # CYRILLIC SMALL LETTER E 0x00fe: 0x044e, # CYRILLIC SMALL LETTER YU 0x00ff: 0x044f, # CYRILLIC SMALL LETTER YA }) ### Encoding Map encoding_map = codecs.make_encoding_map(decoding_map)
mit
lxieyang/simple-amt
simpleamt.py
1
2914
import argparse, json from boto.mturk.connection import MTurkConnection from boto.mturk.qualification import * from jinja2 import Environment, FileSystemLoader """ A bunch of free functions that we use in all scripts. """ def get_jinja_env(config): """ Get a jinja2 Environment object that we can use to find templates. """ return Environment(loader=FileSystemLoader(config['template_directories'])) def json_file(filename): with open(filename, 'r') as f: return json.load(f) def get_parent_parser(): """ Get an argparse parser with arguments that are always needed """ parser = argparse.ArgumentParser(add_help=False) parser.add_argument('--prod', action='store_false', dest='sandbox', default=True, help="Whether to run on the production AMT site.") parser.add_argument('--hit_ids_file') parser.add_argument('--reject_file') parser.add_argument('--reject_only', default=False) parser.add_argument('--auto_mode', default=False) parser.add_argument('--config', default='config.json', type=json_file) return parser def get_mturk_connection_from_args(args): """ Utility method to get an MTurkConnection from argparse args. """ aws_access_key = args.config.get('aws_access_key') aws_secret_key = args.config.get('aws_secret_key') return get_mturk_connection(sandbox=args.sandbox, aws_access_key=aws_access_key, aws_secret_key=aws_secret_key) def get_mturk_connection(sandbox=True, aws_access_key=None, aws_secret_key=None): """ Get a boto mturk connection. This is a thin wrapper over the MTurkConnection constructor; the only difference is a boolean flag to indicate sandbox or not. """ kwargs = {} if aws_access_key is not None: kwargs['aws_access_key_id'] = aws_access_key if aws_secret_key is not None: kwargs['aws_secret_access_key'] = aws_secret_key if sandbox: host = 'mechanicalturk.sandbox.amazonaws.com' else: host='mechanicalturk.amazonaws.com' return MTurkConnection(host=host, **kwargs) def setup_qualifications(hit_properties): """ Replace some of the human-readable keys from the raw HIT properties JSON data structure with boto-specific objects. """ qual = Qualifications() if 'country' in hit_properties: qual.add(LocaleRequirement('EqualTo', hit_properties['country'])) del hit_properties['country'] if 'hits_approved' in hit_properties: qual.add(NumberHitsApprovedRequirement('GreaterThan', hit_properties['hits_approved'])) del hit_properties['hits_approved'] if 'percent_approved' in hit_properties: qual.add(PercentAssignmentsApprovedRequirement('GreaterThan', hit_properties['percent_approved'])) del hit_properties['percent_approved'] hit_properties['qualifications'] = qual
mit
mitodl/bootcamp-ecommerce
main/context_processors_test.py
1
3354
"""Context processors tests""" import json import pytest from django.contrib.auth.models import AnonymousUser from django.test import RequestFactory from main.context_processors import configuration_context, js_settings from profiles.factories import UserFactory # pylint: disable=redefined-outer-name @pytest.fixture def patched_get_resource_page_urls(mocker): """ Return a mock of main.context_processors.get_resource_page_urls """ yield mocker.patch( "main.context_processors.get_resource_page_urls", return_value={"terms_of_service": "/terms-of-service"}, ) @pytest.mark.django_db @pytest.mark.parametrize("is_authed", [True, False]) def test_configuration_context( settings, mocker, is_authed, patched_get_resource_page_urls ): """Verify the context that is provided to all Django templates""" settings.ZENDESK_CONFIG = { "HELP_WIDGET_ENABLED": False, "HELP_WIDGET_KEY": "fake_key", } settings.HUBSPOT_CONFIG = { "HUBSPOT_PORTAL_ID": "fake-portal-id", "HUBSPOT_FOOTER_FORM_GUID": "fake-form-guid", } user = UserFactory.create() if is_authed else AnonymousUser() request = RequestFactory().get("/") request.user = user request.site = mocker.Mock() context = configuration_context(request) assert context == { "resource_page_urls": {"terms_of_service": "/terms-of-service"}, "zendesk_config": { "help_widget_enabled": settings.ZENDESK_CONFIG["HELP_WIDGET_ENABLED"], "help_widget_key": settings.ZENDESK_CONFIG["HELP_WIDGET_KEY"], }, "hubspot_portal_id": settings.HUBSPOT_CONFIG.get("HUBSPOT_PORTAL_ID"), "hubspot_footer_form_guid": settings.HUBSPOT_CONFIG.get( "HUBSPOT_FOOTER_FORM_GUID" ), "support_url": settings.SUPPORT_URL, } patched_get_resource_page_urls.assert_called_once_with(request.site) def test_get_context_js_settings(mocker, settings, patched_get_resource_page_urls): """Verify the specific JS settings in the base context dictionary""" settings.USE_WEBPACK_DEV_SERVER = False settings.ENVIRONMENT = "TEST" settings.VERSION = "9.9.9" settings.RECAPTCHA_SITE_KEY = "SITE_KEY" settings.SUPPORT_URL = "http://example.com/support" settings.SENTRY_DSN = "http://example.com/sentry" settings.MAX_FILE_UPLOAD_MB = 123 settings.ZENDESK_CONFIG = { "HELP_WIDGET_ENABLED": False, "HELP_WIDGET_KEY": "fake_key", } request = RequestFactory().get("/") request.user = AnonymousUser() request.site = mocker.Mock() context = js_settings(request) assert json.loads(context["js_settings_json"]) == { "environment": settings.ENVIRONMENT, "release_version": settings.VERSION, "sentry_dsn": settings.SENTRY_DSN, "public_path": "/static/bundles/", "zendesk_config": { "help_widget_enabled": settings.ZENDESK_CONFIG["HELP_WIDGET_ENABLED"], "help_widget_key": settings.ZENDESK_CONFIG["HELP_WIDGET_KEY"], }, "recaptchaKey": settings.RECAPTCHA_SITE_KEY, "upload_max_size": 123_000_000, "support_url": settings.SUPPORT_URL, "terms_url": patched_get_resource_page_urls.return_value["terms_of_service"], "novoed_login_url": settings.NOVOED_SAML_LOGIN_URL, }
bsd-3-clause
tanglei528/horizon
openstack_dashboard/dashboards/project/containers/forms.py
7
10136
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.core.urlresolvers import reverse from django.core import validators from django.utils.encoding import force_unicode from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from openstack_dashboard import api from openstack_dashboard.dashboards.project.containers import tables no_slash_validator = validators.RegexValidator(r'^(?u)[^/]+$', _("Slash is not an allowed " "character."), code="noslash") class CreateContainer(forms.SelfHandlingForm): ACCESS_CHOICES = ( ("private", _("Private")), ("public", _("Public")), ) parent = forms.CharField(max_length=255, required=False, widget=forms.HiddenInput) name = forms.CharField(max_length=255, label=_("Container Name"), validators=[no_slash_validator]) access = forms.ChoiceField(label=_("Container Access"), required=True, choices=ACCESS_CHOICES) def handle(self, request, data): try: if not data['parent']: is_public = data["access"] == "public" metadata = ({'is_public': is_public}) # Create a container api.swift.swift_create_container(request, data["name"], metadata=metadata) messages.success(request, _("Container created successfully.")) else: # Create a pseudo-folder container, slash, remainder = data['parent'].partition("/") remainder = remainder.rstrip("/") subfolder_name = "/".join([bit for bit in (remainder, data['name']) if bit]) api.swift.swift_create_subfolder(request, container, subfolder_name) messages.success(request, _("Folder created successfully.")) return True except Exception: exceptions.handle(request, _('Unable to create container.')) class UploadObject(forms.SelfHandlingForm): path = forms.CharField(max_length=255, required=False, widget=forms.HiddenInput) name = forms.CharField(max_length=255, label=_("Object Name"), help_text=_("Slashes are allowed, and are treated " "as pseudo-folders by the Object " "Store."), widget=forms.TextInput( attrs={"ng-model": "name", "not-blank": ""} )) object_file = forms.FileField(label=_("File"), required=False, allow_empty_file=True) container_name = forms.CharField(widget=forms.HiddenInput()) def _set_object_path(self, data): if data['path']: object_path = "/".join([data['path'].rstrip("/"), data['name']]) else: object_path = data['name'] return object_path def clean(self): data = super(UploadObject, self).clean() if 'object_file' not in self.files: self.files['object_file'] = None return data def handle(self, request, data): object_file = self.files['object_file'] object_path = self._set_object_path(data) try: obj = api.swift.swift_upload_object(request, data['container_name'], object_path, object_file) msg = force_unicode(_("Object was successfully uploaded.")) messages.success(request, msg) return obj except Exception: exceptions.handle(request, _("Unable to upload object.")) class UpdateObject(UploadObject): def __init__(self, *args, **kwargs): super(UpdateObject, self).__init__(*args, **kwargs) self.fields['name'].widget = forms.TextInput( attrs={"readonly": "readonly"}) self.fields['name'].help_text = None def handle(self, request, data): object_file = self.files.get('object_file') if object_file: object_path = self._set_object_path(data) try: obj = api.swift.swift_upload_object(request, data['container_name'], object_path, object_file) messages.success( request, _("Object was successfully updated.")) return obj except Exception: exceptions.handle(request, _("Unable to update object.")) return False else: # If object file is not provided, then a POST method is needed # to update ONLY metadata. This must be implemented when # object metadata can be updated from this panel. return True class CreatePseudoFolder(forms.SelfHandlingForm): path = forms.CharField(max_length=255, required=False, widget=forms.HiddenInput) name = forms.CharField(max_length=255, label=_("Pseudo-folder Name")) container_name = forms.CharField(widget=forms.HiddenInput()) def _set_pseudo_folder_path(self, data): if data['path']: pseudo_folder_path = "/".join([data['path'].rstrip("/"), data['name']]) + "/" else: pseudo_folder_path = data['name'] + "/" return pseudo_folder_path def handle(self, request, data): pseudo_folder_path = self._set_pseudo_folder_path(data) try: obj = api.swift.swift_create_pseudo_folder(request, data['container_name'], pseudo_folder_path) messages.success(request, _("Pseudo-folder was successfully created.")) return obj except Exception: exceptions.handle(request, _("Unable to create pseudo-folder.")) class CopyObject(forms.SelfHandlingForm): new_container_name = forms.ChoiceField(label=_("Destination container"), validators=[no_slash_validator]) path = forms.CharField(max_length=255, required=False) new_object_name = forms.CharField(max_length=255, label=_("Destination object name"), validators=[no_slash_validator]) orig_container_name = forms.CharField(widget=forms.HiddenInput()) orig_object_name = forms.CharField(widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): containers = kwargs.pop('containers') super(CopyObject, self).__init__(*args, **kwargs) self.fields['new_container_name'].choices = containers def handle(self, request, data): index = "horizon:project:containers:index" orig_container = data['orig_container_name'] orig_object = data['orig_object_name'] new_container = data['new_container_name'] new_object = data['new_object_name'] path = data['path'] if path and not path.endswith("/"): path = path + "/" new_path = "%s%s" % (path, new_object) # Now copy the object itself. try: api.swift.swift_copy_object(request, orig_container, orig_object, new_container, new_path) dest = "%s/%s" % (new_container, path) vals = {"dest": dest.rstrip("/"), "orig": orig_object.split("/")[-1], "new": new_object} messages.success(request, _('Copied "%(orig)s" to "%(dest)s" as "%(new)s".') % vals) return True except exceptions.HorizonException as exc: messages.error(request, exc) raise exceptions.Http302(reverse(index, args=[tables.wrap_delimiter(orig_container)])) except Exception: redirect = reverse(index, args=[tables.wrap_delimiter(orig_container)]) exceptions.handle(request, _("Unable to copy object."), redirect=redirect)
apache-2.0
TenchiMasaki/android-tegra-nv-3.1.10-rel-15r7
tools/perf/scripts/python/netdev-times.py
11271
15048
# Display a process of packets and processed time. # It helps us to investigate networking or network device. # # options # tx: show only tx chart # rx: show only rx chart # dev=: show only thing related to specified device # debug: work with debug mode. It shows buffer status. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * all_event_list = []; # insert all tracepoint event related with this script irq_dic = {}; # key is cpu and value is a list which stacks irqs # which raise NET_RX softirq net_rx_dic = {}; # key is cpu and value include time of NET_RX softirq-entry # and a list which stacks receive receive_hunk_list = []; # a list which include a sequence of receive events rx_skb_list = []; # received packet list for matching # skb_copy_datagram_iovec buffer_budget = 65536; # the budget of rx_skb_list, tx_queue_list and # tx_xmit_list of_count_rx_skb_list = 0; # overflow count tx_queue_list = []; # list of packets which pass through dev_queue_xmit of_count_tx_queue_list = 0; # overflow count tx_xmit_list = []; # list of packets which pass through dev_hard_start_xmit of_count_tx_xmit_list = 0; # overflow count tx_free_list = []; # list of packets which is freed # options show_tx = 0; show_rx = 0; dev = 0; # store a name of device specified by option "dev=" debug = 0; # indices of event_info tuple EINFO_IDX_NAME= 0 EINFO_IDX_CONTEXT=1 EINFO_IDX_CPU= 2 EINFO_IDX_TIME= 3 EINFO_IDX_PID= 4 EINFO_IDX_COMM= 5 # Calculate a time interval(msec) from src(nsec) to dst(nsec) def diff_msec(src, dst): return (dst - src) / 1000000.0 # Display a process of transmitting a packet def print_transmit(hunk): if dev != 0 and hunk['dev'].find(dev) < 0: return print "%7s %5d %6d.%06dsec %12.3fmsec %12.3fmsec" % \ (hunk['dev'], hunk['len'], nsecs_secs(hunk['queue_t']), nsecs_nsecs(hunk['queue_t'])/1000, diff_msec(hunk['queue_t'], hunk['xmit_t']), diff_msec(hunk['xmit_t'], hunk['free_t'])) # Format for displaying rx packet processing PF_IRQ_ENTRY= " irq_entry(+%.3fmsec irq=%d:%s)" PF_SOFT_ENTRY=" softirq_entry(+%.3fmsec)" PF_NAPI_POLL= " napi_poll_exit(+%.3fmsec %s)" PF_JOINT= " |" PF_WJOINT= " | |" PF_NET_RECV= " |---netif_receive_skb(+%.3fmsec skb=%x len=%d)" PF_NET_RX= " |---netif_rx(+%.3fmsec skb=%x)" PF_CPY_DGRAM= " | skb_copy_datagram_iovec(+%.3fmsec %d:%s)" PF_KFREE_SKB= " | kfree_skb(+%.3fmsec location=%x)" PF_CONS_SKB= " | consume_skb(+%.3fmsec)" # Display a process of received packets and interrputs associated with # a NET_RX softirq def print_receive(hunk): show_hunk = 0 irq_list = hunk['irq_list'] cpu = irq_list[0]['cpu'] base_t = irq_list[0]['irq_ent_t'] # check if this hunk should be showed if dev != 0: for i in range(len(irq_list)): if irq_list[i]['name'].find(dev) >= 0: show_hunk = 1 break else: show_hunk = 1 if show_hunk == 0: return print "%d.%06dsec cpu=%d" % \ (nsecs_secs(base_t), nsecs_nsecs(base_t)/1000, cpu) for i in range(len(irq_list)): print PF_IRQ_ENTRY % \ (diff_msec(base_t, irq_list[i]['irq_ent_t']), irq_list[i]['irq'], irq_list[i]['name']) print PF_JOINT irq_event_list = irq_list[i]['event_list'] for j in range(len(irq_event_list)): irq_event = irq_event_list[j] if irq_event['event'] == 'netif_rx': print PF_NET_RX % \ (diff_msec(base_t, irq_event['time']), irq_event['skbaddr']) print PF_JOINT print PF_SOFT_ENTRY % \ diff_msec(base_t, hunk['sirq_ent_t']) print PF_JOINT event_list = hunk['event_list'] for i in range(len(event_list)): event = event_list[i] if event['event_name'] == 'napi_poll': print PF_NAPI_POLL % \ (diff_msec(base_t, event['event_t']), event['dev']) if i == len(event_list) - 1: print "" else: print PF_JOINT else: print PF_NET_RECV % \ (diff_msec(base_t, event['event_t']), event['skbaddr'], event['len']) if 'comm' in event.keys(): print PF_WJOINT print PF_CPY_DGRAM % \ (diff_msec(base_t, event['comm_t']), event['pid'], event['comm']) elif 'handle' in event.keys(): print PF_WJOINT if event['handle'] == "kfree_skb": print PF_KFREE_SKB % \ (diff_msec(base_t, event['comm_t']), event['location']) elif event['handle'] == "consume_skb": print PF_CONS_SKB % \ diff_msec(base_t, event['comm_t']) print PF_JOINT def trace_begin(): global show_tx global show_rx global dev global debug for i in range(len(sys.argv)): if i == 0: continue arg = sys.argv[i] if arg == 'tx': show_tx = 1 elif arg =='rx': show_rx = 1 elif arg.find('dev=',0, 4) >= 0: dev = arg[4:] elif arg == 'debug': debug = 1 if show_tx == 0 and show_rx == 0: show_tx = 1 show_rx = 1 def trace_end(): # order all events in time all_event_list.sort(lambda a,b :cmp(a[EINFO_IDX_TIME], b[EINFO_IDX_TIME])) # process all events for i in range(len(all_event_list)): event_info = all_event_list[i] name = event_info[EINFO_IDX_NAME] if name == 'irq__softirq_exit': handle_irq_softirq_exit(event_info) elif name == 'irq__softirq_entry': handle_irq_softirq_entry(event_info) elif name == 'irq__softirq_raise': handle_irq_softirq_raise(event_info) elif name == 'irq__irq_handler_entry': handle_irq_handler_entry(event_info) elif name == 'irq__irq_handler_exit': handle_irq_handler_exit(event_info) elif name == 'napi__napi_poll': handle_napi_poll(event_info) elif name == 'net__netif_receive_skb': handle_netif_receive_skb(event_info) elif name == 'net__netif_rx': handle_netif_rx(event_info) elif name == 'skb__skb_copy_datagram_iovec': handle_skb_copy_datagram_iovec(event_info) elif name == 'net__net_dev_queue': handle_net_dev_queue(event_info) elif name == 'net__net_dev_xmit': handle_net_dev_xmit(event_info) elif name == 'skb__kfree_skb': handle_kfree_skb(event_info) elif name == 'skb__consume_skb': handle_consume_skb(event_info) # display receive hunks if show_rx: for i in range(len(receive_hunk_list)): print_receive(receive_hunk_list[i]) # display transmit hunks if show_tx: print " dev len Qdisc " \ " netdevice free" for i in range(len(tx_free_list)): print_transmit(tx_free_list[i]) if debug: print "debug buffer status" print "----------------------------" print "xmit Qdisc:remain:%d overflow:%d" % \ (len(tx_queue_list), of_count_tx_queue_list) print "xmit netdevice:remain:%d overflow:%d" % \ (len(tx_xmit_list), of_count_tx_xmit_list) print "receive:remain:%d overflow:%d" % \ (len(rx_skb_list), of_count_rx_skb_list) # called from perf, when it finds a correspoinding event def irq__softirq_entry(name, context, cpu, sec, nsec, pid, comm, vec): if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX": return event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec) all_event_list.append(event_info) def irq__softirq_exit(name, context, cpu, sec, nsec, pid, comm, vec): if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX": return event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec) all_event_list.append(event_info) def irq__softirq_raise(name, context, cpu, sec, nsec, pid, comm, vec): if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX": return event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec) all_event_list.append(event_info) def irq__irq_handler_entry(name, context, cpu, sec, nsec, pid, comm, irq, irq_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, irq, irq_name) all_event_list.append(event_info) def irq__irq_handler_exit(name, context, cpu, sec, nsec, pid, comm, irq, ret): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, irq, ret) all_event_list.append(event_info) def napi__napi_poll(name, context, cpu, sec, nsec, pid, comm, napi, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, napi, dev_name) all_event_list.append(event_info) def net__netif_receive_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, dev_name) all_event_list.append(event_info) def net__netif_rx(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, dev_name) all_event_list.append(event_info) def net__net_dev_queue(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, dev_name) all_event_list.append(event_info) def net__net_dev_xmit(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen, rc, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, rc ,dev_name) all_event_list.append(event_info) def skb__kfree_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr, protocol, location): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, protocol, location) all_event_list.append(event_info) def skb__consume_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr) all_event_list.append(event_info) def skb__skb_copy_datagram_iovec(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen) all_event_list.append(event_info) def handle_irq_handler_entry(event_info): (name, context, cpu, time, pid, comm, irq, irq_name) = event_info if cpu not in irq_dic.keys(): irq_dic[cpu] = [] irq_record = {'irq':irq, 'name':irq_name, 'cpu':cpu, 'irq_ent_t':time} irq_dic[cpu].append(irq_record) def handle_irq_handler_exit(event_info): (name, context, cpu, time, pid, comm, irq, ret) = event_info if cpu not in irq_dic.keys(): return irq_record = irq_dic[cpu].pop() if irq != irq_record['irq']: return irq_record.update({'irq_ext_t':time}) # if an irq doesn't include NET_RX softirq, drop. if 'event_list' in irq_record.keys(): irq_dic[cpu].append(irq_record) def handle_irq_softirq_raise(event_info): (name, context, cpu, time, pid, comm, vec) = event_info if cpu not in irq_dic.keys() \ or len(irq_dic[cpu]) == 0: return irq_record = irq_dic[cpu].pop() if 'event_list' in irq_record.keys(): irq_event_list = irq_record['event_list'] else: irq_event_list = [] irq_event_list.append({'time':time, 'event':'sirq_raise'}) irq_record.update({'event_list':irq_event_list}) irq_dic[cpu].append(irq_record) def handle_irq_softirq_entry(event_info): (name, context, cpu, time, pid, comm, vec) = event_info net_rx_dic[cpu] = {'sirq_ent_t':time, 'event_list':[]} def handle_irq_softirq_exit(event_info): (name, context, cpu, time, pid, comm, vec) = event_info irq_list = [] event_list = 0 if cpu in irq_dic.keys(): irq_list = irq_dic[cpu] del irq_dic[cpu] if cpu in net_rx_dic.keys(): sirq_ent_t = net_rx_dic[cpu]['sirq_ent_t'] event_list = net_rx_dic[cpu]['event_list'] del net_rx_dic[cpu] if irq_list == [] or event_list == 0: return rec_data = {'sirq_ent_t':sirq_ent_t, 'sirq_ext_t':time, 'irq_list':irq_list, 'event_list':event_list} # merge information realted to a NET_RX softirq receive_hunk_list.append(rec_data) def handle_napi_poll(event_info): (name, context, cpu, time, pid, comm, napi, dev_name) = event_info if cpu in net_rx_dic.keys(): event_list = net_rx_dic[cpu]['event_list'] rec_data = {'event_name':'napi_poll', 'dev':dev_name, 'event_t':time} event_list.append(rec_data) def handle_netif_rx(event_info): (name, context, cpu, time, pid, comm, skbaddr, skblen, dev_name) = event_info if cpu not in irq_dic.keys() \ or len(irq_dic[cpu]) == 0: return irq_record = irq_dic[cpu].pop() if 'event_list' in irq_record.keys(): irq_event_list = irq_record['event_list'] else: irq_event_list = [] irq_event_list.append({'time':time, 'event':'netif_rx', 'skbaddr':skbaddr, 'skblen':skblen, 'dev_name':dev_name}) irq_record.update({'event_list':irq_event_list}) irq_dic[cpu].append(irq_record) def handle_netif_receive_skb(event_info): global of_count_rx_skb_list (name, context, cpu, time, pid, comm, skbaddr, skblen, dev_name) = event_info if cpu in net_rx_dic.keys(): rec_data = {'event_name':'netif_receive_skb', 'event_t':time, 'skbaddr':skbaddr, 'len':skblen} event_list = net_rx_dic[cpu]['event_list'] event_list.append(rec_data) rx_skb_list.insert(0, rec_data) if len(rx_skb_list) > buffer_budget: rx_skb_list.pop() of_count_rx_skb_list += 1 def handle_net_dev_queue(event_info): global of_count_tx_queue_list (name, context, cpu, time, pid, comm, skbaddr, skblen, dev_name) = event_info skb = {'dev':dev_name, 'skbaddr':skbaddr, 'len':skblen, 'queue_t':time} tx_queue_list.insert(0, skb) if len(tx_queue_list) > buffer_budget: tx_queue_list.pop() of_count_tx_queue_list += 1 def handle_net_dev_xmit(event_info): global of_count_tx_xmit_list (name, context, cpu, time, pid, comm, skbaddr, skblen, rc, dev_name) = event_info if rc == 0: # NETDEV_TX_OK for i in range(len(tx_queue_list)): skb = tx_queue_list[i] if skb['skbaddr'] == skbaddr: skb['xmit_t'] = time tx_xmit_list.insert(0, skb) del tx_queue_list[i] if len(tx_xmit_list) > buffer_budget: tx_xmit_list.pop() of_count_tx_xmit_list += 1 return def handle_kfree_skb(event_info): (name, context, cpu, time, pid, comm, skbaddr, protocol, location) = event_info for i in range(len(tx_queue_list)): skb = tx_queue_list[i] if skb['skbaddr'] == skbaddr: del tx_queue_list[i] return for i in range(len(tx_xmit_list)): skb = tx_xmit_list[i] if skb['skbaddr'] == skbaddr: skb['free_t'] = time tx_free_list.append(skb) del tx_xmit_list[i] return for i in range(len(rx_skb_list)): rec_data = rx_skb_list[i] if rec_data['skbaddr'] == skbaddr: rec_data.update({'handle':"kfree_skb", 'comm':comm, 'pid':pid, 'comm_t':time}) del rx_skb_list[i] return def handle_consume_skb(event_info): (name, context, cpu, time, pid, comm, skbaddr) = event_info for i in range(len(tx_xmit_list)): skb = tx_xmit_list[i] if skb['skbaddr'] == skbaddr: skb['free_t'] = time tx_free_list.append(skb) del tx_xmit_list[i] return def handle_skb_copy_datagram_iovec(event_info): (name, context, cpu, time, pid, comm, skbaddr, skblen) = event_info for i in range(len(rx_skb_list)): rec_data = rx_skb_list[i] if skbaddr == rec_data['skbaddr']: rec_data.update({'handle':"skb_copy_datagram_iovec", 'comm':comm, 'pid':pid, 'comm_t':time}) del rx_skb_list[i] return
gpl-2.0
837468220/python-for-android
python3-alpha/python3-src/Lib/test/test_isinstance.py
59
10173
# Tests some corner cases with isinstance() and issubclass(). While these # tests use new style classes and properties, they actually do whitebox # testing of error conditions uncovered when using extension types. import unittest from test import support import sys class TestIsInstanceExceptions(unittest.TestCase): # Test to make sure that an AttributeError when accessing the instance's # class's bases is masked. This was actually a bug in Python 2.2 and # 2.2.1 where the exception wasn't caught but it also wasn't being cleared # (leading to an "undetected error" in the debug build). Set up is, # isinstance(inst, cls) where: # # - cls isn't a a type, or a tuple # - cls has a __bases__ attribute # - inst has a __class__ attribute # - inst.__class__ as no __bases__ attribute # # Sounds complicated, I know, but this mimics a situation where an # extension type raises an AttributeError when its __bases__ attribute is # gotten. In that case, isinstance() should return False. def test_class_has_no_bases(self): class I(object): def getclass(self): # This must return an object that has no __bases__ attribute return None __class__ = property(getclass) class C(object): def getbases(self): return () __bases__ = property(getbases) self.assertEqual(False, isinstance(I(), C())) # Like above except that inst.__class__.__bases__ raises an exception # other than AttributeError def test_bases_raises_other_than_attribute_error(self): class E(object): def getbases(self): raise RuntimeError __bases__ = property(getbases) class I(object): def getclass(self): return E() __class__ = property(getclass) class C(object): def getbases(self): return () __bases__ = property(getbases) self.assertRaises(RuntimeError, isinstance, I(), C()) # Here's a situation where getattr(cls, '__bases__') raises an exception. # If that exception is not AttributeError, it should not get masked def test_dont_mask_non_attribute_error(self): class I: pass class C(object): def getbases(self): raise RuntimeError __bases__ = property(getbases) self.assertRaises(RuntimeError, isinstance, I(), C()) # Like above, except that getattr(cls, '__bases__') raises an # AttributeError, which /should/ get masked as a TypeError def test_mask_attribute_error(self): class I: pass class C(object): def getbases(self): raise AttributeError __bases__ = property(getbases) self.assertRaises(TypeError, isinstance, I(), C()) # check that we don't mask non AttributeErrors # see: http://bugs.python.org/issue1574217 def test_isinstance_dont_mask_non_attribute_error(self): class C(object): def getclass(self): raise RuntimeError __class__ = property(getclass) c = C() self.assertRaises(RuntimeError, isinstance, c, bool) # test another code path class D: pass self.assertRaises(RuntimeError, isinstance, c, D) # These tests are similar to above, but tickle certain code paths in # issubclass() instead of isinstance() -- really PyObject_IsSubclass() # vs. PyObject_IsInstance(). class TestIsSubclassExceptions(unittest.TestCase): def test_dont_mask_non_attribute_error(self): class C(object): def getbases(self): raise RuntimeError __bases__ = property(getbases) class S(C): pass self.assertRaises(RuntimeError, issubclass, C(), S()) def test_mask_attribute_error(self): class C(object): def getbases(self): raise AttributeError __bases__ = property(getbases) class S(C): pass self.assertRaises(TypeError, issubclass, C(), S()) # Like above, but test the second branch, where the __bases__ of the # second arg (the cls arg) is tested. This means the first arg must # return a valid __bases__, and it's okay for it to be a normal -- # unrelated by inheritance -- class. def test_dont_mask_non_attribute_error_in_cls_arg(self): class B: pass class C(object): def getbases(self): raise RuntimeError __bases__ = property(getbases) self.assertRaises(RuntimeError, issubclass, B, C()) def test_mask_attribute_error_in_cls_arg(self): class B: pass class C(object): def getbases(self): raise AttributeError __bases__ = property(getbases) self.assertRaises(TypeError, issubclass, B, C()) # meta classes for creating abstract classes and instances class AbstractClass(object): def __init__(self, bases): self.bases = bases def getbases(self): return self.bases __bases__ = property(getbases) def __call__(self): return AbstractInstance(self) class AbstractInstance(object): def __init__(self, klass): self.klass = klass def getclass(self): return self.klass __class__ = property(getclass) # abstract classes AbstractSuper = AbstractClass(bases=()) AbstractChild = AbstractClass(bases=(AbstractSuper,)) # normal classes class Super: pass class Child(Super): pass # new-style classes class NewSuper(object): pass class NewChild(NewSuper): pass class TestIsInstanceIsSubclass(unittest.TestCase): # Tests to ensure that isinstance and issubclass work on abstract # classes and instances. Before the 2.2 release, TypeErrors were # raised when boolean values should have been returned. The bug was # triggered by mixing 'normal' classes and instances were with # 'abstract' classes and instances. This case tries to test all # combinations. def test_isinstance_normal(self): # normal instances self.assertEqual(True, isinstance(Super(), Super)) self.assertEqual(False, isinstance(Super(), Child)) self.assertEqual(False, isinstance(Super(), AbstractSuper)) self.assertEqual(False, isinstance(Super(), AbstractChild)) self.assertEqual(True, isinstance(Child(), Super)) self.assertEqual(False, isinstance(Child(), AbstractSuper)) def test_isinstance_abstract(self): # abstract instances self.assertEqual(True, isinstance(AbstractSuper(), AbstractSuper)) self.assertEqual(False, isinstance(AbstractSuper(), AbstractChild)) self.assertEqual(False, isinstance(AbstractSuper(), Super)) self.assertEqual(False, isinstance(AbstractSuper(), Child)) self.assertEqual(True, isinstance(AbstractChild(), AbstractChild)) self.assertEqual(True, isinstance(AbstractChild(), AbstractSuper)) self.assertEqual(False, isinstance(AbstractChild(), Super)) self.assertEqual(False, isinstance(AbstractChild(), Child)) def test_subclass_normal(self): # normal classes self.assertEqual(True, issubclass(Super, Super)) self.assertEqual(False, issubclass(Super, AbstractSuper)) self.assertEqual(False, issubclass(Super, Child)) self.assertEqual(True, issubclass(Child, Child)) self.assertEqual(True, issubclass(Child, Super)) self.assertEqual(False, issubclass(Child, AbstractSuper)) def test_subclass_abstract(self): # abstract classes self.assertEqual(True, issubclass(AbstractSuper, AbstractSuper)) self.assertEqual(False, issubclass(AbstractSuper, AbstractChild)) self.assertEqual(False, issubclass(AbstractSuper, Child)) self.assertEqual(True, issubclass(AbstractChild, AbstractChild)) self.assertEqual(True, issubclass(AbstractChild, AbstractSuper)) self.assertEqual(False, issubclass(AbstractChild, Super)) self.assertEqual(False, issubclass(AbstractChild, Child)) def test_subclass_tuple(self): # test with a tuple as the second argument classes self.assertEqual(True, issubclass(Child, (Child,))) self.assertEqual(True, issubclass(Child, (Super,))) self.assertEqual(False, issubclass(Super, (Child,))) self.assertEqual(True, issubclass(Super, (Child, Super))) self.assertEqual(False, issubclass(Child, ())) self.assertEqual(True, issubclass(Super, (Child, (Super,)))) self.assertEqual(True, issubclass(NewChild, (NewChild,))) self.assertEqual(True, issubclass(NewChild, (NewSuper,))) self.assertEqual(False, issubclass(NewSuper, (NewChild,))) self.assertEqual(True, issubclass(NewSuper, (NewChild, NewSuper))) self.assertEqual(False, issubclass(NewChild, ())) self.assertEqual(True, issubclass(NewSuper, (NewChild, (NewSuper,)))) self.assertEqual(True, issubclass(int, (int, (float, int)))) self.assertEqual(True, issubclass(str, (str, (Child, NewChild, str)))) def test_subclass_recursion_limit(self): # make sure that issubclass raises RuntimeError before the C stack is # blown self.assertRaises(RuntimeError, blowstack, issubclass, str, str) def test_isinstance_recursion_limit(self): # make sure that issubclass raises RuntimeError before the C stack is # blown self.assertRaises(RuntimeError, blowstack, isinstance, '', str) def blowstack(fxn, arg, compare_to): # Make sure that calling isinstance with a deeply nested tuple for its # argument will raise RuntimeError eventually. tuple_arg = (compare_to,) for cnt in range(sys.getrecursionlimit()+5): tuple_arg = (tuple_arg,) fxn(arg, tuple_arg) def test_main(): support.run_unittest( TestIsInstanceExceptions, TestIsSubclassExceptions, TestIsInstanceIsSubclass ) if __name__ == '__main__': test_main()
apache-2.0
xuewei4d/scikit-learn
sklearn/preprocessing/_discretization.py
5
13176
# -*- coding: utf-8 -*- # Author: Henry Lin <hlin117@gmail.com> # Tom Dupré la Tour # License: BSD import numbers import numpy as np import warnings from . import OneHotEncoder from ..base import BaseEstimator, TransformerMixin from ..utils.validation import check_array from ..utils.validation import check_is_fitted from ..utils.validation import _deprecate_positional_args class KBinsDiscretizer(TransformerMixin, BaseEstimator): """ Bin continuous data into intervals. Read more in the :ref:`User Guide <preprocessing_discretization>`. .. versionadded:: 0.20 Parameters ---------- n_bins : int or array-like of shape (n_features,), default=5 The number of bins to produce. Raises ValueError if ``n_bins < 2``. encode : {'onehot', 'onehot-dense', 'ordinal'}, default='onehot' Method used to encode the transformed result. onehot Encode the transformed result with one-hot encoding and return a sparse matrix. Ignored features are always stacked to the right. onehot-dense Encode the transformed result with one-hot encoding and return a dense array. Ignored features are always stacked to the right. ordinal Return the bin identifier encoded as an integer value. strategy : {'uniform', 'quantile', 'kmeans'}, default='quantile' Strategy used to define the widths of the bins. uniform All bins in each feature have identical widths. quantile All bins in each feature have the same number of points. kmeans Values in each bin have the same nearest center of a 1D k-means cluster. dtype : {np.float32, np.float64}, default=None The desired data-type for the output. If None, output dtype is consistent with input dtype. Only np.float32 and np.float64 are supported. .. versionadded:: 0.24 Attributes ---------- n_bins_ : ndarray of shape (n_features,), dtype=np.int_ Number of bins per feature. Bins whose width are too small (i.e., <= 1e-8) are removed with a warning. bin_edges_ : ndarray of ndarray of shape (n_features,) The edges of each bin. Contain arrays of varying shapes ``(n_bins_, )`` Ignored features will have empty arrays. See Also -------- Binarizer : Class used to bin values as ``0`` or ``1`` based on a parameter ``threshold``. Notes ----- In bin edges for feature ``i``, the first and last values are used only for ``inverse_transform``. During transform, bin edges are extended to:: np.concatenate([-np.inf, bin_edges_[i][1:-1], np.inf]) You can combine ``KBinsDiscretizer`` with :class:`~sklearn.compose.ColumnTransformer` if you only want to preprocess part of the features. ``KBinsDiscretizer`` might produce constant features (e.g., when ``encode = 'onehot'`` and certain bins do not contain any data). These features can be removed with feature selection algorithms (e.g., :class:`~sklearn.feature_selection.VarianceThreshold`). Examples -------- >>> X = [[-2, 1, -4, -1], ... [-1, 2, -3, -0.5], ... [ 0, 3, -2, 0.5], ... [ 1, 4, -1, 2]] >>> est = KBinsDiscretizer(n_bins=3, encode='ordinal', strategy='uniform') >>> est.fit(X) KBinsDiscretizer(...) >>> Xt = est.transform(X) >>> Xt # doctest: +SKIP array([[ 0., 0., 0., 0.], [ 1., 1., 1., 0.], [ 2., 2., 2., 1.], [ 2., 2., 2., 2.]]) Sometimes it may be useful to convert the data back into the original feature space. The ``inverse_transform`` function converts the binned data into the original feature space. Each value will be equal to the mean of the two bin edges. >>> est.bin_edges_[0] array([-2., -1., 0., 1.]) >>> est.inverse_transform(Xt) array([[-1.5, 1.5, -3.5, -0.5], [-0.5, 2.5, -2.5, -0.5], [ 0.5, 3.5, -1.5, 0.5], [ 0.5, 3.5, -1.5, 1.5]]) """ @_deprecate_positional_args def __init__(self, n_bins=5, *, encode='onehot', strategy='quantile', dtype=None): self.n_bins = n_bins self.encode = encode self.strategy = strategy self.dtype = dtype def fit(self, X, y=None): """ Fit the estimator. Parameters ---------- X : array-like of shape (n_samples, n_features), dtype={int, float} Data to be discretized. y : None Ignored. This parameter exists only for compatibility with :class:`~sklearn.pipeline.Pipeline`. Returns ------- self """ X = self._validate_data(X, dtype='numeric') supported_dtype = (np.float64, np.float32) if self.dtype in supported_dtype: output_dtype = self.dtype elif self.dtype is None: output_dtype = X.dtype else: raise ValueError( f"Valid options for 'dtype' are " f"{supported_dtype + (None,)}. Got dtype={self.dtype} " f" instead." ) valid_encode = ('onehot', 'onehot-dense', 'ordinal') if self.encode not in valid_encode: raise ValueError("Valid options for 'encode' are {}. " "Got encode={!r} instead." .format(valid_encode, self.encode)) valid_strategy = ('uniform', 'quantile', 'kmeans') if self.strategy not in valid_strategy: raise ValueError("Valid options for 'strategy' are {}. " "Got strategy={!r} instead." .format(valid_strategy, self.strategy)) n_features = X.shape[1] n_bins = self._validate_n_bins(n_features) bin_edges = np.zeros(n_features, dtype=object) for jj in range(n_features): column = X[:, jj] col_min, col_max = column.min(), column.max() if col_min == col_max: warnings.warn("Feature %d is constant and will be " "replaced with 0." % jj) n_bins[jj] = 1 bin_edges[jj] = np.array([-np.inf, np.inf]) continue if self.strategy == 'uniform': bin_edges[jj] = np.linspace(col_min, col_max, n_bins[jj] + 1) elif self.strategy == 'quantile': quantiles = np.linspace(0, 100, n_bins[jj] + 1) bin_edges[jj] = np.asarray(np.percentile(column, quantiles)) elif self.strategy == 'kmeans': from ..cluster import KMeans # fixes import loops # Deterministic initialization with uniform spacing uniform_edges = np.linspace(col_min, col_max, n_bins[jj] + 1) init = (uniform_edges[1:] + uniform_edges[:-1])[:, None] * 0.5 # 1D k-means procedure km = KMeans(n_clusters=n_bins[jj], init=init, n_init=1) centers = km.fit(column[:, None]).cluster_centers_[:, 0] # Must sort, centers may be unsorted even with sorted init centers.sort() bin_edges[jj] = (centers[1:] + centers[:-1]) * 0.5 bin_edges[jj] = np.r_[col_min, bin_edges[jj], col_max] # Remove bins whose width are too small (i.e., <= 1e-8) if self.strategy in ('quantile', 'kmeans'): mask = np.ediff1d(bin_edges[jj], to_begin=np.inf) > 1e-8 bin_edges[jj] = bin_edges[jj][mask] if len(bin_edges[jj]) - 1 != n_bins[jj]: warnings.warn('Bins whose width are too small (i.e., <= ' '1e-8) in feature %d are removed. Consider ' 'decreasing the number of bins.' % jj) n_bins[jj] = len(bin_edges[jj]) - 1 self.bin_edges_ = bin_edges self.n_bins_ = n_bins if 'onehot' in self.encode: self._encoder = OneHotEncoder( categories=[np.arange(i) for i in self.n_bins_], sparse=self.encode == 'onehot', dtype=output_dtype) # Fit the OneHotEncoder with toy datasets # so that it's ready for use after the KBinsDiscretizer is fitted self._encoder.fit(np.zeros((1, len(self.n_bins_)))) return self def _validate_n_bins(self, n_features): """Returns n_bins_, the number of bins per feature. """ orig_bins = self.n_bins if isinstance(orig_bins, numbers.Number): if not isinstance(orig_bins, numbers.Integral): raise ValueError("{} received an invalid n_bins type. " "Received {}, expected int." .format(KBinsDiscretizer.__name__, type(orig_bins).__name__)) if orig_bins < 2: raise ValueError("{} received an invalid number " "of bins. Received {}, expected at least 2." .format(KBinsDiscretizer.__name__, orig_bins)) return np.full(n_features, orig_bins, dtype=int) n_bins = check_array(orig_bins, dtype=int, copy=True, ensure_2d=False) if n_bins.ndim > 1 or n_bins.shape[0] != n_features: raise ValueError("n_bins must be a scalar or array " "of shape (n_features,).") bad_nbins_value = (n_bins < 2) | (n_bins != orig_bins) violating_indices = np.where(bad_nbins_value)[0] if violating_indices.shape[0] > 0: indices = ", ".join(str(i) for i in violating_indices) raise ValueError("{} received an invalid number " "of bins at indices {}. Number of bins " "must be at least 2, and must be an int." .format(KBinsDiscretizer.__name__, indices)) return n_bins def transform(self, X): """ Discretize the data. Parameters ---------- X : array-like of shape (n_samples, n_features), dtype={int, float} Data to be discretized. Returns ------- Xt : {ndarray, sparse matrix}, dtype={np.float32, np.float64} Data in the binned space. Will be a sparse matrix if `self.encode='onehot'` and ndarray otherwise. """ check_is_fitted(self) # check input and attribute dtypes dtype = (np.float64, np.float32) if self.dtype is None else self.dtype Xt = self._validate_data(X, copy=True, dtype=dtype, reset=False) bin_edges = self.bin_edges_ for jj in range(Xt.shape[1]): # Values which are close to a bin edge are susceptible to numeric # instability. Add eps to X so these values are binned correctly # with respect to their decimal truncation. See documentation of # numpy.isclose for an explanation of ``rtol`` and ``atol``. rtol = 1.e-5 atol = 1.e-8 eps = atol + rtol * np.abs(Xt[:, jj]) Xt[:, jj] = np.digitize(Xt[:, jj] + eps, bin_edges[jj][1:]) np.clip(Xt, 0, self.n_bins_ - 1, out=Xt) if self.encode == 'ordinal': return Xt dtype_init = None if 'onehot' in self.encode: dtype_init = self._encoder.dtype self._encoder.dtype = Xt.dtype try: Xt_enc = self._encoder.transform(Xt) finally: # revert the initial dtype to avoid modifying self. self._encoder.dtype = dtype_init return Xt_enc def inverse_transform(self, Xt): """ Transform discretized data back to original feature space. Note that this function does not regenerate the original data due to discretization rounding. Parameters ---------- Xt : array-like of shape (n_samples, n_features), dtype={int, float} Transformed data in the binned space. Returns ------- Xinv : ndarray, dtype={np.float32, np.float64} Data in the original feature space. """ check_is_fitted(self) if 'onehot' in self.encode: Xt = self._encoder.inverse_transform(Xt) Xinv = check_array(Xt, copy=True, dtype=(np.float64, np.float32)) n_features = self.n_bins_.shape[0] if Xinv.shape[1] != n_features: raise ValueError("Incorrect number of features. Expecting {}, " "received {}.".format(n_features, Xinv.shape[1])) for jj in range(n_features): bin_edges = self.bin_edges_[jj] bin_centers = (bin_edges[1:] + bin_edges[:-1]) * 0.5 Xinv[:, jj] = bin_centers[np.int_(Xinv[:, jj])] return Xinv
bsd-3-clause
emijrp/youtube-dl
youtube_dl/extractor/arte.py
77
9526
# encoding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( find_xpath_attr, unified_strdate, get_element_by_attribute, int_or_none, qualities, ) # There are different sources of video in arte.tv, the extraction process # is different for each one. The videos usually expire in 7 days, so we can't # add tests. class ArteTvIE(InfoExtractor): _VALID_URL = r'http://videos\.arte\.tv/(?P<lang>fr|de)/.*-(?P<id>.*?)\.html' IE_NAME = 'arte.tv' def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) lang = mobj.group('lang') video_id = mobj.group('id') ref_xml_url = url.replace('/videos/', '/do_delegate/videos/') ref_xml_url = ref_xml_url.replace('.html', ',view,asPlayerXml.xml') ref_xml_doc = self._download_xml( ref_xml_url, video_id, note='Downloading metadata') config_node = find_xpath_attr(ref_xml_doc, './/video', 'lang', lang) config_xml_url = config_node.attrib['ref'] config = self._download_xml( config_xml_url, video_id, note='Downloading configuration') formats = [{ 'format_id': q.attrib['quality'], # The playpath starts at 'mp4:', if we don't manually # split the url, rtmpdump will incorrectly parse them 'url': q.text.split('mp4:', 1)[0], 'play_path': 'mp4:' + q.text.split('mp4:', 1)[1], 'ext': 'flv', 'quality': 2 if q.attrib['quality'] == 'hd' else 1, } for q in config.findall('./urls/url')] self._sort_formats(formats) title = config.find('.//name').text thumbnail = config.find('.//firstThumbnailUrl').text return { 'id': video_id, 'title': title, 'thumbnail': thumbnail, 'formats': formats, } class ArteTVPlus7IE(InfoExtractor): IE_NAME = 'arte.tv:+7' _VALID_URL = r'https?://(?:www\.)?arte\.tv/guide/(?P<lang>fr|de)/(?:(?:sendungen|emissions)/)?(?P<id>.*?)/(?P<name>.*?)(\?.*)?' @classmethod def _extract_url_info(cls, url): mobj = re.match(cls._VALID_URL, url) lang = mobj.group('lang') # This is not a real id, it can be for example AJT for the news # http://www.arte.tv/guide/fr/emissions/AJT/arte-journal video_id = mobj.group('id') return video_id, lang def _real_extract(self, url): video_id, lang = self._extract_url_info(url) webpage = self._download_webpage(url, video_id) return self._extract_from_webpage(webpage, video_id, lang) def _extract_from_webpage(self, webpage, video_id, lang): json_url = self._html_search_regex( [r'arte_vp_url=["\'](.*?)["\']', r'data-url=["\']([^"]+)["\']'], webpage, 'json vp url') return self._extract_from_json_url(json_url, video_id, lang) def _extract_from_json_url(self, json_url, video_id, lang): info = self._download_json(json_url, video_id) player_info = info['videoJsonPlayer'] upload_date_str = player_info.get('shootingDate') if not upload_date_str: upload_date_str = player_info.get('VDA', '').split(' ')[0] title = player_info['VTI'].strip() subtitle = player_info.get('VSU', '').strip() if subtitle: title += ' - %s' % subtitle info_dict = { 'id': player_info['VID'], 'title': title, 'description': player_info.get('VDE'), 'upload_date': unified_strdate(upload_date_str), 'thumbnail': player_info.get('programImage') or player_info.get('VTU', {}).get('IUR'), } qfunc = qualities(['HQ', 'MQ', 'EQ', 'SQ']) formats = [] for format_id, format_dict in player_info['VSR'].items(): f = dict(format_dict) versionCode = f.get('versionCode') langcode = { 'fr': 'F', 'de': 'A', }.get(lang, lang) lang_rexs = [r'VO?%s' % langcode, r'VO?.-ST%s' % langcode] lang_pref = ( None if versionCode is None else ( 10 if any(re.match(r, versionCode) for r in lang_rexs) else -10)) source_pref = 0 if versionCode is not None: # The original version with subtitles has lower relevance if re.match(r'VO-ST(F|A)', versionCode): source_pref -= 10 # The version with sourds/mal subtitles has also lower relevance elif re.match(r'VO?(F|A)-STM\1', versionCode): source_pref -= 9 format = { 'format_id': format_id, 'preference': -10 if f.get('videoFormat') == 'M3U8' else None, 'language_preference': lang_pref, 'format_note': '%s, %s' % (f.get('versionCode'), f.get('versionLibelle')), 'width': int_or_none(f.get('width')), 'height': int_or_none(f.get('height')), 'tbr': int_or_none(f.get('bitrate')), 'quality': qfunc(f.get('quality')), 'source_preference': source_pref, } if f.get('mediaType') == 'rtmp': format['url'] = f['streamer'] format['play_path'] = 'mp4:' + f['url'] format['ext'] = 'flv' else: format['url'] = f['url'] formats.append(format) self._check_formats(formats, video_id) self._sort_formats(formats) info_dict['formats'] = formats return info_dict # It also uses the arte_vp_url url from the webpage to extract the information class ArteTVCreativeIE(ArteTVPlus7IE): IE_NAME = 'arte.tv:creative' _VALID_URL = r'https?://creative\.arte\.tv/(?P<lang>fr|de)/(?:magazine?/)?(?P<id>[^?#]+)' _TESTS = [{ 'url': 'http://creative.arte.tv/de/magazin/agentur-amateur-corporate-design', 'info_dict': { 'id': '72176', 'ext': 'mp4', 'title': 'Folge 2 - Corporate Design', 'upload_date': '20131004', }, }, { 'url': 'http://creative.arte.tv/fr/Monty-Python-Reunion', 'info_dict': { 'id': '160676', 'ext': 'mp4', 'title': 'Monty Python live (mostly)', 'description': 'Événement ! Quarante-cinq ans après leurs premiers succès, les légendaires Monty Python remontent sur scène.\n', 'upload_date': '20140805', } }] class ArteTVFutureIE(ArteTVPlus7IE): IE_NAME = 'arte.tv:future' _VALID_URL = r'https?://future\.arte\.tv/(?P<lang>fr|de)/(thema|sujet)/.*?#article-anchor-(?P<id>\d+)' _TEST = { 'url': 'http://future.arte.tv/fr/sujet/info-sciences#article-anchor-7081', 'info_dict': { 'id': '5201', 'ext': 'mp4', 'title': 'Les champignons au secours de la planète', 'upload_date': '20131101', }, } def _real_extract(self, url): anchor_id, lang = self._extract_url_info(url) webpage = self._download_webpage(url, anchor_id) row = self._search_regex( r'(?s)id="%s"[^>]*>.+?(<div[^>]*arte_vp_url[^>]*>)' % anchor_id, webpage, 'row') return self._extract_from_webpage(row, anchor_id, lang) class ArteTVDDCIE(ArteTVPlus7IE): IE_NAME = 'arte.tv:ddc' _VALID_URL = r'https?://ddc\.arte\.tv/(?P<lang>emission|folge)/(?P<id>.+)' def _real_extract(self, url): video_id, lang = self._extract_url_info(url) if lang == 'folge': lang = 'de' elif lang == 'emission': lang = 'fr' webpage = self._download_webpage(url, video_id) scriptElement = get_element_by_attribute('class', 'visu_video_block', webpage) script_url = self._html_search_regex(r'src="(.*?)"', scriptElement, 'script url') javascriptPlayerGenerator = self._download_webpage(script_url, video_id, 'Download javascript player generator') json_url = self._search_regex(r"json_url=(.*)&rendering_place.*", javascriptPlayerGenerator, 'json url') return self._extract_from_json_url(json_url, video_id, lang) class ArteTVConcertIE(ArteTVPlus7IE): IE_NAME = 'arte.tv:concert' _VALID_URL = r'https?://concert\.arte\.tv/(?P<lang>de|fr)/(?P<id>.+)' _TEST = { 'url': 'http://concert.arte.tv/de/notwist-im-pariser-konzertclub-divan-du-monde', 'md5': '9ea035b7bd69696b67aa2ccaaa218161', 'info_dict': { 'id': '186', 'ext': 'mp4', 'title': 'The Notwist im Pariser Konzertclub "Divan du Monde"', 'upload_date': '20140128', 'description': 'md5:486eb08f991552ade77439fe6d82c305', }, } class ArteTVEmbedIE(ArteTVPlus7IE): IE_NAME = 'arte.tv:embed' _VALID_URL = r'''(?x) http://www\.arte\.tv /playerv2/embed\.php\?json_url= (?P<json_url> http://arte\.tv/papi/tvguide/videos/stream/player/ (?P<lang>[^/]+)/(?P<id>[^/]+)[^&]* ) ''' def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') lang = mobj.group('lang') json_url = mobj.group('json_url') return self._extract_from_json_url(json_url, video_id, lang)
unlicense
jaruba/chromium.src
components/policy/tools/make_policy_zip.py
159
2874
#!/usr/bin/env python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Creates a zip archive with policy template files. The list of input files is extracted from a grd file with grit. This is to keep the length of input arguments below the limit on Windows. """ import optparse import os import sys import zipfile def add_files_to_zip(zip_file, base_dir, file_list): """Pack a list of files into a zip archive, that is already opened for writing. Args: zip_file: An object representing the zip archive. base_dir: Base path of all the files in the real file system. files: List of file paths to add, all relative to base_dir. The zip entries will only contain this componenet of the path. """ for file_path in file_list: zip_file.write(base_dir + file_path, file_path) return 0 def get_grd_outputs(grit_cmd, grit_defines, grd_file, grd_strip_path_prefix): grit_path = os.path.join(os.getcwd(), os.path.dirname(grit_cmd)) sys.path.append(grit_path) import grit_info outputs = grit_info.Outputs(grd_file, grit_defines, 'GRIT_DIR/../gritsettings/resource_ids') result = [] for item in outputs: assert item.startswith(grd_strip_path_prefix) result.append(item[len(grd_strip_path_prefix):]) return result def main(argv): """Pack a list of files into a zip archive. Args: zip_path: The file name of the zip archive. base_dir: Base path of input files. locales: The list of locales that are used to generate the list of file names using INPUT_FILES. """ parser = optparse.OptionParser() parser.add_option("--output", dest="output") parser.add_option("--basedir", dest="basedir") parser.add_option("--grit_info", dest="grit_info") parser.add_option("--grd_input", dest="grd_input") parser.add_option("--grd_strip_path_prefix", dest="grd_strip_path_prefix") parser.add_option("--extra_input", action="append", dest="extra_input", default=[]) parser.add_option("-D", action="append", dest="grit_defines", default=[]) parser.add_option("-E", action="append", dest="grit_build_env", default=[]) options, args = parser.parse_args(argv[1:]) if (options.basedir[-1] != '/'): options.basedir += '/' grit_defines = {} for define in options.grit_defines: grit_defines[define] = 1 file_list = options.extra_input file_list += get_grd_outputs(options.grit_info, grit_defines, options.grd_input, options.grd_strip_path_prefix) zip_file = zipfile.ZipFile(options.output, 'w', zipfile.ZIP_DEFLATED) try: return add_files_to_zip(zip_file, options.basedir, file_list) finally: zip_file.close() if '__main__' == __name__: sys.exit(main(sys.argv))
bsd-3-clause
repotvsupertuga/repo
plugin.video.specto/resources/lib/sources/directdl_tv.py
20
4246
# -*- coding: utf-8 -*- ''' Specto Add-on Copyright (C) 2015 lambda This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re,urllib,urlparse,json,base64 from resources.lib.libraries import control from resources.lib.libraries import cleantitle from resources.lib.libraries import client from resources.lib import resolvers class source: def __init__(self): self.base_link = 'http://directdownload.tv' self.search_link = 'L2FwaT9rZXk9NEIwQkI4NjJGMjRDOEEyOSZxdWFsaXR5W109SERUViZxdWFsaXR5W109RFZEUklQJnF1YWxpdHlbXT03MjBQJnF1YWxpdHlbXT1XRUJETCZxdWFsaXR5W109V0VCREwxMDgwUCZsaW1pdD0yMCZrZXl3b3JkPQ==' def get_show(self, imdb, tvdb, tvshowtitle, year): try: url = tvshowtitle url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url except: return def get_episode(self, url, imdb, tvdb, title, date, season, episode): try: if url == None: return url = '%s S%02dE%02d' % (url, int(season), int(episode)) url = client.replaceHTMLCodes(url) url = url.encode('utf-8') return url except: return def get_sources(self, url, hosthdDict, hostDict, locDict): try: sources = [] if url == None: return sources if (control.setting('realdedrid_user') == '' and control.setting('premiumize_user') == ''): raise Exception() query = base64.urlsafe_b64decode(self.search_link) + urllib.quote_plus(url) query = urlparse.urljoin(self.base_link, query) result = client.source(query) result = json.loads(result) title, hdlr = re.compile('(.+?) (S\d*E\d*)$').findall(url)[0] title = cleantitle.tv(title) hdlr = [hdlr] links = [] for i in result: try: t = i['showName'] t = client.replaceHTMLCodes(t) t = cleantitle.tv(t) if not t == title: raise Exception() y = i['release'] y = re.compile('[\.|\(|\[|\s](\d{4}|S\d*E\d*)[\.|\)|\]|\s]').findall(y)[-1] y = y.upper() if not any(x == y for x in hdlr): raise Exception() quality = i['quality'] if quality == 'WEBDL1080P': quality = '1080p' elif quality in ['720P', 'WEBDL']: quality = 'HD' else: quality = 'SD' size = i['size'] size = float(size)/1024 info = '%.2f GB' % size url = i['links'] for x in url.keys(): links.append({'url': url[x], 'quality': quality, 'info': info}) except: pass for i in links: try: url = i['url'] if len(url) > 1: raise Exception() url = url[0] host = (urlparse.urlparse(url).netloc).replace('www.', '').rsplit('.', 1)[0].lower() if not host in hosthdDict: raise Exception() sources.append({'source': host, 'quality': i['quality'], 'provider': 'DirectDL', 'url': url, 'info': i['info']}) except: pass return sources except: return sources def resolve(self, url): try: url = resolvers.request(url) return url except: return
gpl-2.0
Dik1s/volatility
contrib/plugins/pagecheck.py
55
1739
# Volatility # # This file is part of Volatility. # # Volatility is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Volatility is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Volatility. If not, see <http://www.gnu.org/licenses/>. # import volatility.commands as commands import volatility.utils as utils class PageCheck(commands.Command): """Reads the available pages and reports if any are inaccessible""" def render_text(self, outfd, data): """Displays any page errors""" found = False for page, vtop, size, pde, pte in data: found = True outfd.write("(V): 0x{0:08x} [PDE] 0x{3:08x} [PTE] 0x{4:08x} (P): 0x{1:08x} Size: 0x{2:08x}\n".format(page, vtop, size, pde, pte)) if not found: outfd.write("No page failures found!") def calculate(self): """Calculate returns the results of the available pages validity""" addr_space = utils.load_as(self._config) for page, size in addr_space.get_available_pages(): output = addr_space.read(page, size) if output == None: pde_value = addr_space.get_pde(page) pte_value = addr_space.get_pte(page, pde_value) yield page, addr_space.vtop(page), size, pde_value, pte_value
gpl-2.0
jonathonwalz/ansible
lib/ansible/modules/cloud/google/gcpubsub_facts.py
70
4771
#!/usr/bin/python # Copyright 2016 Google Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcpubsub_facts version_added: "2.3" short_description: List Topics/Subscriptions and Messages from Google PubSub. description: - List Topics/Subscriptions from Google PubSub. Use the gcpubsub module for topic/subscription management. See U(https://cloud.google.com/pubsub/docs) for an overview. requirements: - "python >= 2.6" - "google-auth >= 0.5.0" - "google-cloud-pubsub >= 0.22.0" notes: - list state enables user to list topics or subscriptions in the project. See examples for details. author: - "Tom Melendez (@supertom) <tom@supertom.com>" options: topic: description: - GCP pubsub topic name. Only the name, not the full path, is required. required: False view: description: - Choices are 'topics' or 'subscriptions' required: True state: description: - list is the only valid option. required: False ''' EXAMPLES = ''' ## List all Topics in a project gcpubsub_facts: view: topics state: list ## List all Subscriptions in a project gcpubsub_facts: view: subscriptions state: list ## List all Subscriptions for a Topic in a project gcpubsub_facts: view: subscriptions topic: my-topic state: list ''' RETURN = ''' subscriptions: description: List of subscriptions. returned: When view is set to subscriptions. type: list sample: ["mysubscription", "mysubscription2"] topic: description: Name of topic. Used to filter subscriptions. returned: Always type: str sample: "mytopic" topics: description: List of topics. returned: When view is set to topics. type: list sample: ["mytopic", "mytopic2"] ''' try: from ast import literal_eval HAS_PYTHON26 = True except ImportError: HAS_PYTHON26 = False try: from google.cloud import pubsub HAS_GOOGLE_CLOUD_PUBSUB = True except ImportError as e: HAS_GOOGLE_CLOUD_PUBSUB = False def list_func(data, member='name'): """Used for state=list.""" return [getattr(x, member) for x in data] def main(): module = AnsibleModule(argument_spec=dict( view=dict(choices=['topics', 'subscriptions'], default='topics'), topic=dict(required=False), state=dict(choices=['list'], default='list'), service_account_email=dict(), credentials_file=dict(), project_id=dict(), ),) if not HAS_PYTHON26: module.fail_json( msg="GCE module requires python's 'ast' module, python v2.6+") if not HAS_GOOGLE_CLOUD_PUBSUB: module.fail_json(msg="Please install google-cloud-pubsub library.") CLIENT_MINIMUM_VERSION = '0.22.0' if not check_min_pkg_version('google-cloud-pubsub', CLIENT_MINIMUM_VERSION): module.fail_json(msg="Please install google-cloud-pubsub library version %s" % CLIENT_MINIMUM_VERSION) mod_params = {} mod_params['state'] = module.params.get('state') mod_params['topic'] = module.params.get('topic') mod_params['view'] = module.params.get('view') creds, params = get_google_cloud_credentials(module) pubsub_client = pubsub.Client(project=params['project_id'], credentials=creds, use_gax=False) pubsub_client.user_agent = 'ansible-pubsub-0.1' json_output = {} if mod_params['view'] == 'topics': json_output['topics'] = list_func(pubsub_client.list_topics()) elif mod_params['view'] == 'subscriptions': if mod_params['topic']: t = pubsub_client.topic(mod_params['topic']) json_output['subscriptions'] = list_func(t.list_subscriptions()) else: json_output['subscriptions'] = list_func(pubsub_client.list_subscriptions()) json_output['changed'] = False json_output.update(mod_params) module.exit_json(**json_output) # import module snippets from ansible.module_utils.basic import * from ansible.module_utils.gcp import * if __name__ == '__main__': main()
gpl-3.0
dtaht/Gnugol
src/prototypes/wikipedia.py
1
1543
"""ajaxgoogle.py - Simple bindings to the AJAX Google Search API (Just the JSON-over-HTTP bit of it, nothing to do with AJAX per se) http://code.google.com/apis/ajaxsearch/documentation/reference.html#_intro_fonje brendan o'connor - gist.github.com/28405 - anyall.org""" try: import json except ImportError: import simplejson as json import urllib, urllib2 import os.path TEMPLATE = "http://en.wikipedia.org/w/api.php?action=query&prop=info&format=json" #if os.path.exists(os.environ['HOME'] + '/.googlekey'): # KEY = open(os.environ['HOME']+'/.googlekey').read().strip() #else: # KEY = None #if KEY: # TEMPLATE += "&key=" + KEY def search_url(q, **kwds): url = TEMPLATE url += "titles=" + urllib.quote(q) if kwds: url += "&" + urllib.urlencode(kwds) return url def search(q, **kwds): """See options at http://code.google.com/apis/ajaxsearch/documentation/reference.html#_intro_fonje including: rsz= large | small (8 vs 4) start= <0-indexed offset> hl= <language of searcher> lr= <language of results> safe= active | moderate | off """ f = urllib2.urlopen(search_url(q, **kwds)) ret = json.load(f) if ret['responseStatus']==200 and ret['responseData']: return ret['responseData'] raise Exception("Google API error %s: %s\n (%s)" % (ret['responseStatus'],ret['responseDetails'],repr(ret))) if __name__=='__main__': import sys from pprint import pprint if len(sys.argv) > 1: q = " ".join(sys.argv[1:]) else: q = "query a question to whom in what sense" pprint(search(q))
agpl-3.0
dvliman/jaikuengine
.google_appengine/lib/django-0.96/django/conf/__init__.py
33
5865
""" Settings and configuration for Django. Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment variable, and then from django.conf.global_settings; see the global settings file for a list of all possible variables. """ import os import time # Needed for Windows from django.conf import global_settings ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE" class LazySettings(object): """ A lazy proxy for either global Django settings or a custom settings object. The user can manually configure settings prior to using them. Otherwise, Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE. """ def __init__(self): # _target must be either None or something that supports attribute # access (getattr, hasattr, etc). self._target = None def __getattr__(self, name): if self._target is None: self._import_settings() if name == '__members__': # Used to implement dir(obj), for example. return self._target.get_all_members() return getattr(self._target, name) def __setattr__(self, name, value): if name == '_target': # Assign directly to self.__dict__, because otherwise we'd call # __setattr__(), which would be an infinite loop. self.__dict__['_target'] = value else: setattr(self._target, name, value) def _import_settings(self): """ Load the settings module pointed to by the environment variable. This is used the first time we need any settings at all, if the user has not previously configured the settings manually. """ try: settings_module = os.environ[ENVIRONMENT_VARIABLE] if not settings_module: # If it's set but is an empty string. raise KeyError except KeyError: raise EnvironmentError, "Environment variable %s is undefined." % ENVIRONMENT_VARIABLE self._target = Settings(settings_module) def configure(self, default_settings=global_settings, **options): """ Called to manually configure the settings. The 'default_settings' parameter sets where to retrieve any unspecified values from (its argument must support attribute access (__getattr__)). """ if self._target != None: raise EnvironmentError, 'Settings already configured.' holder = UserSettingsHolder(default_settings) for name, value in options.items(): setattr(holder, name, value) self._target = holder class Settings(object): def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) for setting in dir(global_settings): if setting == setting.upper(): setattr(self, setting, getattr(global_settings, setting)) # store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module try: mod = __import__(self.SETTINGS_MODULE, {}, {}, ['']) except ImportError, e: raise EnvironmentError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e) # Settings that should be converted into tuples if they're mistakenly entered # as strings. tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS") for setting in dir(mod): if setting == setting.upper(): setting_value = getattr(mod, setting) if setting in tuple_settings and type(setting_value) == str: setting_value = (setting_value,) # In case the user forgot the comma. setattr(self, setting, setting_value) # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list # of all those apps. new_installed_apps = [] for app in self.INSTALLED_APPS: if app.endswith('.*'): appdir = os.path.dirname(__import__(app[:-2], {}, {}, ['']).__file__) for d in os.listdir(appdir): if d.isalpha() and os.path.isdir(os.path.join(appdir, d)): new_installed_apps.append('%s.%s' % (app[:-2], d)) else: new_installed_apps.append(app) self.INSTALLED_APPS = new_installed_apps if hasattr(time, 'tzset'): # Move the time zone info into os.environ. See ticket #2315 for why # we don't do this unconditionally (breaks Windows). os.environ['TZ'] = self.TIME_ZONE def get_all_members(self): return dir(self) class UserSettingsHolder(object): """ Holder for user configured settings. """ # SETTINGS_MODULE doesn't make much sense in the manually configured # (standalone) case. SETTINGS_MODULE = None def __init__(self, default_settings): """ Requests for configuration variables not in this class are satisfied from the module specified in default_settings (if possible). """ self.default_settings = default_settings def __getattr__(self, name): return getattr(self.default_settings, name) def get_all_members(self): return dir(self) + dir(self.default_settings) settings = LazySettings() # This function replaces itself with django.utils.translation.gettext() the # first time it's run. This is necessary because the import of # django.utils.translation requires a working settings module, and loading it # from within this file would cause a circular import. def first_time_gettext(*args): from django.utils.translation import gettext __builtins__['_'] = gettext return gettext(*args) __builtins__['_'] = first_time_gettext
apache-2.0
ludmilamarian/invenio
invenio/modules/upgrader/operations.py
20
2662
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2012, 2013 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ Objects for inspect and manipulating the database structure. Based on Alembic. """ from __future__ import absolute_import from werkzeug.local import LocalProxy from alembic.environment import EnvironmentContext from alembic.operations import Operations from alembic.autogenerate.api import _produce_migration_diffs from alembic.config import Config from invenio.ext.sqlalchemy import db op = LocalProxy(lambda: create_operations()) """ Alembic operations object used to modify the database structure. """ def has_table(table_name): """Return True if table exists, False otherwise.""" return db.engine.dialect.has_table( db.engine.connect(), table_name ) def create_migration_ctx(**kwargs): """Create an alembic migration context.""" env = EnvironmentContext(Config(), None) env.configure( connection=db.engine.connect(), sqlalchemy_module_prefix='db.', **kwargs ) return env.get_context() def create_operations(ctx=None, **kwargs): """Create an alembic operations object.""" if ctx is None: ctx = create_migration_ctx(**kwargs) operations = Operations(ctx) operations.has_table = has_table return operations def produce_upgrade_operations( ctx=None, metadata=None, include_symbol=None, include_object=None, **kwargs): """Produce a list of upgrade statements.""" if metadata is None: # Note, all SQLAlchemy models must have been loaded to produce # accurate results. metadata = db.metadata if ctx is None: ctx = create_migration_ctx(target_metadata=metadata, **kwargs) template_args = {} imports = set() _produce_migration_diffs( ctx, template_args, imports, include_object=include_object, include_symbol=include_symbol, **kwargs ) return template_args
gpl-2.0
rruebner/odoo
addons/website_certification/__openerp__.py
64
1502
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-TODAY OpenERP S.A. <http://www.openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Certified People', 'category': 'Website', 'summary': 'Display your network of certified people on your website', 'version': '1.0', 'author': 'OpenERP S.A.', 'depends': ['marketing', 'website'], 'description': """ Display your network of certified people on your website """, 'data': [ 'security/ir.model.access.csv', 'views/website_certification_views.xml', 'views/website_certification_templates.xml', ], 'installable': True, }
agpl-3.0
krafczyk/spack
var/spack/repos/builtin/packages/r-topgo/package.py
2
2371
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class RTopgo(RPackage): """topGO package provides tools for testing GO terms while accounting for the topology of the GO graph. Different test statistics and different methods for eliminating local similarities and dependencies between GO terms can be implemented and applied.""" homepage = "https://www.bioconductor.org/packages/topGO/" git = "https://git.bioconductor.org/packages/topGO.git" version('2.30.1', commit='b1469ce1d198ccb73ef79ca22cab81659e16dbaa') version('2.28.0', commit='066a975d460046cce33fb27e74e6a0ebc33fd716') depends_on('r@3.4.0:3.4.9') depends_on('r-dbi', type=('build', 'run')) depends_on('r-matrixstats', type=('build', 'run')) depends_on('r-lattice', type=('build', 'run')) depends_on('r-sparsem@0.73:', type=('build', 'run')) depends_on('r-annotationdbi@1.7.19:', type=('build', 'run')) depends_on('r-go-db@2.3.0:', type=('build', 'run')) depends_on('r-biobase@2.0.0:', type=('build', 'run')) depends_on('r-graph@1.14.0:', type=('build', 'run')) depends_on('r-biocgenerics@0.13.6:', type=('build', 'run'))
lgpl-2.1
xsm110/Apache-Beam
sdks/python/apache_beam/io/filesystems_util.py
3
1283
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Utility functions for getting the correct file systems for a file name""" from apache_beam.io.localfilesystem import LocalFileSystem # TODO(BEAM-1585): Add a mechanism to add user implemented file systems def get_filesystem(path): """Function that returns the FileSystem class to use based on the path provided in the input. """ if path.startswith('gs://'): from apache_beam.io.gcp.gcsfilesystem import GCSFileSystem return GCSFileSystem() else: return LocalFileSystem()
apache-2.0
ryancoleman/autodock-vina
boost_1_54_0/libs/python/test/test_pointer_adoption.py
46
1708
# Copyright David Abrahams 2004. Distributed under the Boost # Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) """ >>> from test_pointer_adoption_ext import * >>> num_a_instances() 0 >>> a = create('dynamically allocated') >>> num_a_instances() 1 >>> a.content() 'dynamically allocated' >>> innards = a.get_inner() >>> innards.change('with an exposed reference') >>> a.content() 'with an exposed reference' # The a instance should be kept alive... >>> a = None >>> num_a_instances() 1 # ...until we're done with its innards >>> innards = None >>> num_a_instances() 0 >>> b = B() >>> a = create('another') >>> b.a_content() 'empty' >>> innards = b.adopt(a); >>> b.a_content() 'another' >>> num_a_instances() 1 >>> del a # innards and b are both holding a reference >>> num_a_instances() 1 >>> innards.change('yet another') >>> b.a_content() 'yet another' >>> del innards >>> num_a_instances() # b still owns a reference to a 1 >>> del b >>> num_a_instances() 0 Test call policies for constructors here >>> a = create('second a') >>> num_a_instances() 1 >>> b = B(a) >>> num_a_instances() 1 >>> a.content() 'second a' >>> del a >>> num_a_instances() 1 >>> b.a_content() 'second a' >>> del b >>> num_a_instances() 0 >>> assert as_A(create('dynalloc')) is not None >>> base = Base() >>> assert as_A(base) is None """ def run(args = None): import sys import doctest if args is not None: sys.argv = args return doctest.testmod(sys.modules.get(__name__)) if __name__ == '__main__': print "running..." import sys status = run()[0] if (status == 0): print "Done." sys.exit(status)
apache-2.0
abgworrall/kubernetes
vendor/github.com/ugorji/go/codec/test.py
1516
4019
#!/usr/bin/env python # This will create golden files in a directory passed to it. # A Test calls this internally to create the golden files # So it can process them (so we don't have to checkin the files). # Ensure msgpack-python and cbor are installed first, using: # sudo apt-get install python-dev # sudo apt-get install python-pip # pip install --user msgpack-python msgpack-rpc-python cbor # Ensure all "string" keys are utf strings (else encoded as bytes) import cbor, msgpack, msgpackrpc, sys, os, threading def get_test_data_list(): # get list with all primitive types, and a combo type l0 = [ -8, -1616, -32323232, -6464646464646464, 192, 1616, 32323232, 6464646464646464, 192, -3232.0, -6464646464.0, 3232.0, 6464.0, 6464646464.0, False, True, u"null", None, u"someday", 1328176922000002000, u"", -2206187877999998000, u"bytestring", 270, u"none", -2013855847999995777, #-6795364578871345152, ] l1 = [ { "true": True, "false": False }, { "true": u"True", "false": False, "uint16(1616)": 1616 }, { "list": [1616, 32323232, True, -3232.0, {"TRUE":True, "FALSE":False}, [True, False] ], "int32":32323232, "bool": True, "LONG STRING": u"123456789012345678901234567890123456789012345678901234567890", "SHORT STRING": u"1234567890" }, { True: "true", 138: False, "false": 200 } ] l = [] l.extend(l0) l.append(l0) l.append(1) l.extend(l1) return l def build_test_data(destdir): l = get_test_data_list() for i in range(len(l)): # packer = msgpack.Packer() serialized = msgpack.dumps(l[i]) f = open(os.path.join(destdir, str(i) + '.msgpack.golden'), 'wb') f.write(serialized) f.close() serialized = cbor.dumps(l[i]) f = open(os.path.join(destdir, str(i) + '.cbor.golden'), 'wb') f.write(serialized) f.close() def doRpcServer(port, stopTimeSec): class EchoHandler(object): def Echo123(self, msg1, msg2, msg3): return ("1:%s 2:%s 3:%s" % (msg1, msg2, msg3)) def EchoStruct(self, msg): return ("%s" % msg) addr = msgpackrpc.Address('localhost', port) server = msgpackrpc.Server(EchoHandler()) server.listen(addr) # run thread to stop it after stopTimeSec seconds if > 0 if stopTimeSec > 0: def myStopRpcServer(): server.stop() t = threading.Timer(stopTimeSec, myStopRpcServer) t.start() server.start() def doRpcClientToPythonSvc(port): address = msgpackrpc.Address('localhost', port) client = msgpackrpc.Client(address, unpack_encoding='utf-8') print client.call("Echo123", "A1", "B2", "C3") print client.call("EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"}) def doRpcClientToGoSvc(port): # print ">>>> port: ", port, " <<<<<" address = msgpackrpc.Address('localhost', port) client = msgpackrpc.Client(address, unpack_encoding='utf-8') print client.call("TestRpcInt.Echo123", ["A1", "B2", "C3"]) print client.call("TestRpcInt.EchoStruct", {"A" :"Aa", "B":"Bb", "C":"Cc"}) def doMain(args): if len(args) == 2 and args[0] == "testdata": build_test_data(args[1]) elif len(args) == 3 and args[0] == "rpc-server": doRpcServer(int(args[1]), int(args[2])) elif len(args) == 2 and args[0] == "rpc-client-python-service": doRpcClientToPythonSvc(int(args[1])) elif len(args) == 2 and args[0] == "rpc-client-go-service": doRpcClientToGoSvc(int(args[1])) else: print("Usage: test.py " + "[testdata|rpc-server|rpc-client-python-service|rpc-client-go-service] ...") if __name__ == "__main__": doMain(sys.argv[1:])
apache-2.0
ninjin/nerv
src/nerv/dag.py
2
3353
# vim:set ft=python ts=4 sw=4 sts=4 autoindent: ''' A Directed Multigraph with some caching of attributes for better run-time performance. Author: Pontus Stenetorp <pontus stenetorp se> Version: 2014-03-12 ''' # TODO: Implement remove_edge? # TODO: Could use more clever caching rather than full invalidation. # TODO: The above cache would also allow us to avoid a method call. # TODO: Consider an incremental topological sort? # TODO: Sanity checking? from collections import defaultdict from lib.structs import OrderedSet from lib.structs import enum VertexType = enum('SOURCE', 'SINK', 'INTERNAL') class DAG(object): def __init__(self): self.parents = defaultdict(OrderedSet) self.children = defaultdict(OrderedSet) self.vertices = set() # Cache(s). self._topo_sort = None def __iter__(self): return iter(self.vertices) def add_edge(self, parent, child): self.vertices.add(parent) self.vertices.add(child) self.parents[child].add(parent) self.children[parent].add(child) # Invalidate cache(s). self._topo_sort = None def typed_it(self): for vertex in self: if not self.parents[vertex]: yield (VertexType.SOURCE, vertex) elif not self.children[vertex]: yield (VertexType.SINK, vertex) else: yield (VertexType.INTERNAL, vertex) def sources(self): return (v for t, v in self.typed_it() if t == VertexType.SOURCE) def sinks(self): return (v for t, v in self.typed_it() if t == VertexType.SINK) def internals(self): return (v for t, v in self.typed_it() if t == VertexType.INTERNAL) # http://en.wikipedia.org/wiki/Topological_sorting def _topological_sort(self): tsort = [] processed = set() # Start a Depth-First Search (DFS) from each vertex and add each # vertex after the search has added their children to the order. # Lastly, reverse the order to gain the topological sort. for start in self: # No need to process a vertex twice. if start in processed: continue # Start the DFS from this vertex. queue = [start] while queue: current = queue[-1] # If we have already processed this vertex it means that all # of its descendants have been processed and we can safely # add it to the topological sort. if current in processed: tsort.append(current) queue.pop() continue # Process the vertex by adding each of its unprocessed # children to the queue. for child in self.children[current]: if child not in processed: queue.append(child) processed.add(current) return reversed(tsort) def topological_sort(self, reverse=False): if self._topo_sort is not None: topo_sort = self._topo_sort else: topo_sort = tuple(self._topological_sort()) self._topo_sort = topo_sort return topo_sort if not reverse else reversed(topo_sort)
isc
six8/polydatum
tests/test_deferred_attr_requests.py
1
3758
from polydatum.middleware import DalCommand, PathSegment def test_deferred_attribute_access(path_segment_factory): """ Verify that we can access non-existent attributes on this class and that we can access arbitrarily deep non-existent attributes. """ dc = DalCommand(lambda: None, path_segment_factory()) assert isinstance(dc.foo, DalCommand) assert isinstance(dc.foo.bar, DalCommand) assert isinstance(dc.foo.bar.baz, DalCommand) # Use a different non-existent service, to help make it clear that there # is nothing special about the `foo` service above. assert isinstance(dc.anything, DalCommand) assert isinstance(dc.example, DalCommand) def test_dal_deferred_attr_access_handler_chain(path_segment_factory): """ Verify that the handler for a DalCommand instance is preserved regardless of how deep a deferred attribute lookup chain is. Ultimately this class is responsible for deferring attribute access and calling the handler with a built up chain of PathSegments. We want to make sure that the handler is the same regardless of where in the deferred attribute access it is finally called. """ # The impl here doesn't matter, we are only checking # for identity with this callable. # Even the signature of this callable doesn't matter right here. def specific_handler(): pass dc = DalCommand(specific_handler, path_segment_factory()) assert dc.foo._handler is specific_handler assert dc.foo.bar._handler is specific_handler assert dc.foo.bar.baz._handler is specific_handler def test_dal_deferred_attr_access_handler_called(path_segment_factory): """ Verify that the handler for a DalCommand gets called when the DalCommand is called. """ def handler(path_chain, *args, **kwargs): return path_chain, args, kwargs test_path_segment = path_segment_factory() dc = DalCommand(handler, test_path_segment) test_args = ("foo", "bar") test_kwargs = dict(example="test", other="monkey") for requester in [dc, dc.foo.bar, dc.monkey.gorilla.orangutan]: called_path_segment, called_args, called_kwargs = requester( *test_args, **test_kwargs ) assert isinstance(called_path_segment[0], PathSegment) assert called_path_segment[0].name == test_path_segment[0].name assert called_args == test_args assert called_kwargs == test_kwargs def test_dal_deferred_attr_access_path_chaining(path_segment_factory): """ Verify that deeper attribute access on a DalCommand will nest path segments when building up the path call chain. Maintaining order is important. dc = DalCommand() deep_dc = dc.foo.bar.baz.method assert deep_dc.path = (PathSegment(name=foo), PathSegment(name=bar), ...) assert deep_dc.non_existent.path == (deep_dc.path + PathSegment(name=non_existent)) """ dc = DalCommand(lambda: None, path_segment_factory("animals")) nested_dc = dc.foo.bar.baz.monkey.gorilla expected_path_chain = ( PathSegment(name="animals"), PathSegment(name="foo"), PathSegment(name="bar"), PathSegment(name="baz"), PathSegment(name="monkey"), PathSegment(name="gorilla"), ) assert nested_dc.path == expected_path_chain def test_dal_deferred_attr_access_reusability(path_segment_factory): """ Verify the same dal attributes can be re-used """ req = DalCommand(lambda: None, path_segment_factory("req")) bar = req.foo.bar bar2 = req.foo.bar assert bar != bar2 assert bar.path == bar2.path zap = bar.zap zap2 = bar2.zap assert zap != zap2 assert zap.path == zap2.path
mit
flwh/shadowsocks
shadowsocks/daemon.py
694
5602
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2014-2015 clowwindy # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import, division, print_function, \ with_statement import os import sys import logging import signal import time from shadowsocks import common, shell # this module is ported from ShadowVPN daemon.c def daemon_exec(config): if 'daemon' in config: if os.name != 'posix': raise Exception('daemon mode is only supported on Unix') command = config['daemon'] if not command: command = 'start' pid_file = config['pid-file'] log_file = config['log-file'] if command == 'start': daemon_start(pid_file, log_file) elif command == 'stop': daemon_stop(pid_file) # always exit after daemon_stop sys.exit(0) elif command == 'restart': daemon_stop(pid_file) daemon_start(pid_file, log_file) else: raise Exception('unsupported daemon command %s' % command) def write_pid_file(pid_file, pid): import fcntl import stat try: fd = os.open(pid_file, os.O_RDWR | os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR) except OSError as e: shell.print_exception(e) return -1 flags = fcntl.fcntl(fd, fcntl.F_GETFD) assert flags != -1 flags |= fcntl.FD_CLOEXEC r = fcntl.fcntl(fd, fcntl.F_SETFD, flags) assert r != -1 # There is no platform independent way to implement fcntl(fd, F_SETLK, &fl) # via fcntl.fcntl. So use lockf instead try: fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 0, 0, os.SEEK_SET) except IOError: r = os.read(fd, 32) if r: logging.error('already started at pid %s' % common.to_str(r)) else: logging.error('already started') os.close(fd) return -1 os.ftruncate(fd, 0) os.write(fd, common.to_bytes(str(pid))) return 0 def freopen(f, mode, stream): oldf = open(f, mode) oldfd = oldf.fileno() newfd = stream.fileno() os.close(newfd) os.dup2(oldfd, newfd) def daemon_start(pid_file, log_file): def handle_exit(signum, _): if signum == signal.SIGTERM: sys.exit(0) sys.exit(1) signal.signal(signal.SIGINT, handle_exit) signal.signal(signal.SIGTERM, handle_exit) # fork only once because we are sure parent will exit pid = os.fork() assert pid != -1 if pid > 0: # parent waits for its child time.sleep(5) sys.exit(0) # child signals its parent to exit ppid = os.getppid() pid = os.getpid() if write_pid_file(pid_file, pid) != 0: os.kill(ppid, signal.SIGINT) sys.exit(1) os.setsid() signal.signal(signal.SIGHUP, signal.SIG_IGN) print('started') os.kill(ppid, signal.SIGTERM) sys.stdin.close() try: freopen(log_file, 'a', sys.stdout) freopen(log_file, 'a', sys.stderr) except IOError as e: shell.print_exception(e) sys.exit(1) def daemon_stop(pid_file): import errno try: with open(pid_file) as f: buf = f.read() pid = common.to_str(buf) if not buf: logging.error('not running') except IOError as e: shell.print_exception(e) if e.errno == errno.ENOENT: # always exit 0 if we are sure daemon is not running logging.error('not running') return sys.exit(1) pid = int(pid) if pid > 0: try: os.kill(pid, signal.SIGTERM) except OSError as e: if e.errno == errno.ESRCH: logging.error('not running') # always exit 0 if we are sure daemon is not running return shell.print_exception(e) sys.exit(1) else: logging.error('pid is not positive: %d', pid) # sleep for maximum 10s for i in range(0, 200): try: # query for the pid os.kill(pid, 0) except OSError as e: if e.errno == errno.ESRCH: break time.sleep(0.05) else: logging.error('timed out when stopping pid %d', pid) sys.exit(1) print('stopped') os.unlink(pid_file) def set_user(username): if username is None: return import pwd import grp try: pwrec = pwd.getpwnam(username) except KeyError: logging.error('user not found: %s' % username) raise user = pwrec[0] uid = pwrec[2] gid = pwrec[3] cur_uid = os.getuid() if uid == cur_uid: return if cur_uid != 0: logging.error('can not set user as nonroot user') # will raise later # inspired by supervisor if hasattr(os, 'setgroups'): groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]] groups.insert(0, gid) os.setgroups(groups) os.setgid(gid) os.setuid(uid)
apache-2.0
johnardavies/scrapy
scrapy/downloadermiddlewares/cookies.py
128
3330
import os import six import logging from collections import defaultdict from scrapy.exceptions import NotConfigured from scrapy.http import Response from scrapy.http.cookies import CookieJar from scrapy.utils.python import to_native_str logger = logging.getLogger(__name__) class CookiesMiddleware(object): """This middleware enables working with sites that need cookies""" def __init__(self, debug=False): self.jars = defaultdict(CookieJar) self.debug = debug @classmethod def from_crawler(cls, crawler): if not crawler.settings.getbool('COOKIES_ENABLED'): raise NotConfigured return cls(crawler.settings.getbool('COOKIES_DEBUG')) def process_request(self, request, spider): if request.meta.get('dont_merge_cookies', False): return cookiejarkey = request.meta.get("cookiejar") jar = self.jars[cookiejarkey] cookies = self._get_request_cookies(jar, request) for cookie in cookies: jar.set_cookie_if_ok(cookie, request) # set Cookie header request.headers.pop('Cookie', None) jar.add_cookie_header(request) self._debug_cookie(request, spider) def process_response(self, request, response, spider): if request.meta.get('dont_merge_cookies', False): return response # extract cookies from Set-Cookie and drop invalid/expired cookies cookiejarkey = request.meta.get("cookiejar") jar = self.jars[cookiejarkey] jar.extract_cookies(response, request) self._debug_set_cookie(response, spider) return response def _debug_cookie(self, request, spider): if self.debug: cl = [to_native_str(c, errors='replace') for c in request.headers.getlist('Cookie')] if cl: cookies = "\n".join("Cookie: {}\n".format(c) for c in cl) msg = "Sending cookies to: {}\n{}".format(request, cookies) logger.debug(msg, extra={'spider': spider}) def _debug_set_cookie(self, response, spider): if self.debug: cl = [to_native_str(c, errors='replace') for c in response.headers.getlist('Set-Cookie')] if cl: cookies = "\n".join("Set-Cookie: {}\n".format(c) for c in cl) msg = "Received cookies from: {}\n{}".format(response, cookies) logger.debug(msg, extra={'spider': spider}) def _format_cookie(self, cookie): # build cookie string cookie_str = '%s=%s' % (cookie['name'], cookie['value']) if cookie.get('path', None): cookie_str += '; Path=%s' % cookie['path'] if cookie.get('domain', None): cookie_str += '; Domain=%s' % cookie['domain'] return cookie_str def _get_request_cookies(self, jar, request): if isinstance(request.cookies, dict): cookie_list = [{'name': k, 'value': v} for k, v in \ six.iteritems(request.cookies)] else: cookie_list = request.cookies cookies = [self._format_cookie(x) for x in cookie_list] headers = {'Set-Cookie': cookies} response = Response(request.url, headers=headers) return jar.make_cookies(response, request)
bsd-3-clause
40323144/2015cdb_g7
static/Brython3.1.1-20150328-091302/Lib/fractions.py
722
23203
# Originally contributed by Sjoerd Mullender. # Significantly modified by Jeffrey Yasskin <jyasskin at gmail.com>. """Fraction, infinite-precision, real numbers.""" from decimal import Decimal import math import numbers import operator import re import sys __all__ = ['Fraction', 'gcd'] def gcd(a, b): """Calculate the Greatest Common Divisor of a and b. Unless b==0, the result will have the same sign as b (so that when b is divided by it, the result comes out positive). """ while b: a, b = b, a%b return a # Constants related to the hash implementation; hash(x) is based # on the reduction of x modulo the prime _PyHASH_MODULUS. _PyHASH_MODULUS = sys.hash_info.modulus # Value to be used for rationals that reduce to infinity modulo # _PyHASH_MODULUS. _PyHASH_INF = sys.hash_info.inf _RATIONAL_FORMAT = re.compile(r""" \A\s* # optional whitespace at the start, then (?P<sign>[-+]?) # an optional sign, then (?=\d|\.\d) # lookahead for digit or .digit (?P<num>\d*) # numerator (possibly empty) (?: # followed by (?:/(?P<denom>\d+))? # an optional denominator | # or (?:\.(?P<decimal>\d*))? # an optional fractional part (?:E(?P<exp>[-+]?\d+))? # and optional exponent ) \s*\Z # and optional whitespace to finish """, re.VERBOSE | re.IGNORECASE) class Fraction(numbers.Rational): """This class implements rational numbers. In the two-argument form of the constructor, Fraction(8, 6) will produce a rational number equivalent to 4/3. Both arguments must be Rational. The numerator defaults to 0 and the denominator defaults to 1 so that Fraction(3) == 3 and Fraction() == 0. Fractions can also be constructed from: - numeric strings similar to those accepted by the float constructor (for example, '-2.3' or '1e10') - strings of the form '123/456' - float and Decimal instances - other Rational instances (including integers) """ __slots__ = ('_numerator', '_denominator') # We're immutable, so use __new__ not __init__ def __new__(cls, numerator=0, denominator=None): """Constructs a Rational. Takes a string like '3/2' or '1.5', another Rational instance, a numerator/denominator pair, or a float. Examples -------- >>> Fraction(10, -8) Fraction(-5, 4) >>> Fraction(Fraction(1, 7), 5) Fraction(1, 35) >>> Fraction(Fraction(1, 7), Fraction(2, 3)) Fraction(3, 14) >>> Fraction('314') Fraction(314, 1) >>> Fraction('-35/4') Fraction(-35, 4) >>> Fraction('3.1415') # conversion from numeric string Fraction(6283, 2000) >>> Fraction('-47e-2') # string may include a decimal exponent Fraction(-47, 100) >>> Fraction(1.47) # direct construction from float (exact conversion) Fraction(6620291452234629, 4503599627370496) >>> Fraction(2.25) Fraction(9, 4) >>> Fraction(Decimal('1.47')) Fraction(147, 100) """ self = super(Fraction, cls).__new__(cls) if denominator is None: if isinstance(numerator, numbers.Rational): self._numerator = numerator.numerator self._denominator = numerator.denominator return self elif isinstance(numerator, float): # Exact conversion from float value = Fraction.from_float(numerator) self._numerator = value._numerator self._denominator = value._denominator return self elif isinstance(numerator, Decimal): value = Fraction.from_decimal(numerator) self._numerator = value._numerator self._denominator = value._denominator return self elif isinstance(numerator, str): # Handle construction from strings. m = _RATIONAL_FORMAT.match(numerator) if m is None: raise ValueError('Invalid literal for Fraction: %r' % numerator) numerator = int(m.group('num') or '0') denom = m.group('denom') if denom: denominator = int(denom) else: denominator = 1 decimal = m.group('decimal') if decimal: scale = 10**len(decimal) numerator = numerator * scale + int(decimal) denominator *= scale exp = m.group('exp') if exp: exp = int(exp) if exp >= 0: numerator *= 10**exp else: denominator *= 10**-exp if m.group('sign') == '-': numerator = -numerator else: raise TypeError("argument should be a string " "or a Rational instance") elif (isinstance(numerator, numbers.Rational) and isinstance(denominator, numbers.Rational)): numerator, denominator = ( numerator.numerator * denominator.denominator, denominator.numerator * numerator.denominator ) else: raise TypeError("both arguments should be " "Rational instances") if denominator == 0: raise ZeroDivisionError('Fraction(%s, 0)' % numerator) g = gcd(numerator, denominator) self._numerator = numerator // g self._denominator = denominator // g return self @classmethod def from_float(cls, f): """Converts a finite float to a rational number, exactly. Beware that Fraction.from_float(0.3) != Fraction(3, 10). """ if isinstance(f, numbers.Integral): return cls(f) elif not isinstance(f, float): raise TypeError("%s.from_float() only takes floats, not %r (%s)" % (cls.__name__, f, type(f).__name__)) if math.isnan(f): raise ValueError("Cannot convert %r to %s." % (f, cls.__name__)) if math.isinf(f): raise OverflowError("Cannot convert %r to %s." % (f, cls.__name__)) return cls(*f.as_integer_ratio()) @classmethod def from_decimal(cls, dec): """Converts a finite Decimal instance to a rational number, exactly.""" from decimal import Decimal if isinstance(dec, numbers.Integral): dec = Decimal(int(dec)) elif not isinstance(dec, Decimal): raise TypeError( "%s.from_decimal() only takes Decimals, not %r (%s)" % (cls.__name__, dec, type(dec).__name__)) if dec.is_infinite(): raise OverflowError( "Cannot convert %s to %s." % (dec, cls.__name__)) if dec.is_nan(): raise ValueError("Cannot convert %s to %s." % (dec, cls.__name__)) sign, digits, exp = dec.as_tuple() digits = int(''.join(map(str, digits))) if sign: digits = -digits if exp >= 0: return cls(digits * 10 ** exp) else: return cls(digits, 10 ** -exp) def limit_denominator(self, max_denominator=1000000): """Closest Fraction to self with denominator at most max_denominator. >>> Fraction('3.141592653589793').limit_denominator(10) Fraction(22, 7) >>> Fraction('3.141592653589793').limit_denominator(100) Fraction(311, 99) >>> Fraction(4321, 8765).limit_denominator(10000) Fraction(4321, 8765) """ # Algorithm notes: For any real number x, define a *best upper # approximation* to x to be a rational number p/q such that: # # (1) p/q >= x, and # (2) if p/q > r/s >= x then s > q, for any rational r/s. # # Define *best lower approximation* similarly. Then it can be # proved that a rational number is a best upper or lower # approximation to x if, and only if, it is a convergent or # semiconvergent of the (unique shortest) continued fraction # associated to x. # # To find a best rational approximation with denominator <= M, # we find the best upper and lower approximations with # denominator <= M and take whichever of these is closer to x. # In the event of a tie, the bound with smaller denominator is # chosen. If both denominators are equal (which can happen # only when max_denominator == 1 and self is midway between # two integers) the lower bound---i.e., the floor of self, is # taken. if max_denominator < 1: raise ValueError("max_denominator should be at least 1") if self._denominator <= max_denominator: return Fraction(self) p0, q0, p1, q1 = 0, 1, 1, 0 n, d = self._numerator, self._denominator while True: a = n//d q2 = q0+a*q1 if q2 > max_denominator: break p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 n, d = d, n-a*d k = (max_denominator-q0)//q1 bound1 = Fraction(p0+k*p1, q0+k*q1) bound2 = Fraction(p1, q1) if abs(bound2 - self) <= abs(bound1-self): return bound2 else: return bound1 @property def numerator(a): return a._numerator @property def denominator(a): return a._denominator def __repr__(self): """repr(self)""" return ('Fraction(%s, %s)' % (self._numerator, self._denominator)) def __str__(self): """str(self)""" if self._denominator == 1: return str(self._numerator) else: return '%s/%s' % (self._numerator, self._denominator) def _operator_fallbacks(monomorphic_operator, fallback_operator): """Generates forward and reverse operators given a purely-rational operator and a function from the operator module. Use this like: __op__, __rop__ = _operator_fallbacks(just_rational_op, operator.op) In general, we want to implement the arithmetic operations so that mixed-mode operations either call an implementation whose author knew about the types of both arguments, or convert both to the nearest built in type and do the operation there. In Fraction, that means that we define __add__ and __radd__ as: def __add__(self, other): # Both types have numerators/denominator attributes, # so do the operation directly if isinstance(other, (int, Fraction)): return Fraction(self.numerator * other.denominator + other.numerator * self.denominator, self.denominator * other.denominator) # float and complex don't have those operations, but we # know about those types, so special case them. elif isinstance(other, float): return float(self) + other elif isinstance(other, complex): return complex(self) + other # Let the other type take over. return NotImplemented def __radd__(self, other): # radd handles more types than add because there's # nothing left to fall back to. if isinstance(other, numbers.Rational): return Fraction(self.numerator * other.denominator + other.numerator * self.denominator, self.denominator * other.denominator) elif isinstance(other, Real): return float(other) + float(self) elif isinstance(other, Complex): return complex(other) + complex(self) return NotImplemented There are 5 different cases for a mixed-type addition on Fraction. I'll refer to all of the above code that doesn't refer to Fraction, float, or complex as "boilerplate". 'r' will be an instance of Fraction, which is a subtype of Rational (r : Fraction <: Rational), and b : B <: Complex. The first three involve 'r + b': 1. If B <: Fraction, int, float, or complex, we handle that specially, and all is well. 2. If Fraction falls back to the boilerplate code, and it were to return a value from __add__, we'd miss the possibility that B defines a more intelligent __radd__, so the boilerplate should return NotImplemented from __add__. In particular, we don't handle Rational here, even though we could get an exact answer, in case the other type wants to do something special. 3. If B <: Fraction, Python tries B.__radd__ before Fraction.__add__. This is ok, because it was implemented with knowledge of Fraction, so it can handle those instances before delegating to Real or Complex. The next two situations describe 'b + r'. We assume that b didn't know about Fraction in its implementation, and that it uses similar boilerplate code: 4. If B <: Rational, then __radd_ converts both to the builtin rational type (hey look, that's us) and proceeds. 5. Otherwise, __radd__ tries to find the nearest common base ABC, and fall back to its builtin type. Since this class doesn't subclass a concrete type, there's no implementation to fall back to, so we need to try as hard as possible to return an actual value, or the user will get a TypeError. """ def forward(a, b): if isinstance(b, (int, Fraction)): return monomorphic_operator(a, b) elif isinstance(b, float): return fallback_operator(float(a), b) elif isinstance(b, complex): return fallback_operator(complex(a), b) else: return NotImplemented forward.__name__ = '__' + fallback_operator.__name__ + '__' forward.__doc__ = monomorphic_operator.__doc__ def reverse(b, a): if isinstance(a, numbers.Rational): # Includes ints. return monomorphic_operator(a, b) elif isinstance(a, numbers.Real): return fallback_operator(float(a), float(b)) elif isinstance(a, numbers.Complex): return fallback_operator(complex(a), complex(b)) else: return NotImplemented reverse.__name__ = '__r' + fallback_operator.__name__ + '__' reverse.__doc__ = monomorphic_operator.__doc__ return forward, reverse def _add(a, b): """a + b""" return Fraction(a.numerator * b.denominator + b.numerator * a.denominator, a.denominator * b.denominator) __add__, __radd__ = _operator_fallbacks(_add, operator.add) def _sub(a, b): """a - b""" return Fraction(a.numerator * b.denominator - b.numerator * a.denominator, a.denominator * b.denominator) __sub__, __rsub__ = _operator_fallbacks(_sub, operator.sub) def _mul(a, b): """a * b""" return Fraction(a.numerator * b.numerator, a.denominator * b.denominator) __mul__, __rmul__ = _operator_fallbacks(_mul, operator.mul) def _div(a, b): """a / b""" return Fraction(a.numerator * b.denominator, a.denominator * b.numerator) __truediv__, __rtruediv__ = _operator_fallbacks(_div, operator.truediv) def __floordiv__(a, b): """a // b""" return math.floor(a / b) def __rfloordiv__(b, a): """a // b""" return math.floor(a / b) def __mod__(a, b): """a % b""" div = a // b return a - b * div def __rmod__(b, a): """a % b""" div = a // b return a - b * div def __pow__(a, b): """a ** b If b is not an integer, the result will be a float or complex since roots are generally irrational. If b is an integer, the result will be rational. """ if isinstance(b, numbers.Rational): if b.denominator == 1: power = b.numerator if power >= 0: return Fraction(a._numerator ** power, a._denominator ** power) else: return Fraction(a._denominator ** -power, a._numerator ** -power) else: # A fractional power will generally produce an # irrational number. return float(a) ** float(b) else: return float(a) ** b def __rpow__(b, a): """a ** b""" if b._denominator == 1 and b._numerator >= 0: # If a is an int, keep it that way if possible. return a ** b._numerator if isinstance(a, numbers.Rational): return Fraction(a.numerator, a.denominator) ** b if b._denominator == 1: return a ** b._numerator return a ** float(b) def __pos__(a): """+a: Coerces a subclass instance to Fraction""" return Fraction(a._numerator, a._denominator) def __neg__(a): """-a""" return Fraction(-a._numerator, a._denominator) def __abs__(a): """abs(a)""" return Fraction(abs(a._numerator), a._denominator) def __trunc__(a): """trunc(a)""" if a._numerator < 0: return -(-a._numerator // a._denominator) else: return a._numerator // a._denominator def __floor__(a): """Will be math.floor(a) in 3.0.""" return a.numerator // a.denominator def __ceil__(a): """Will be math.ceil(a) in 3.0.""" # The negations cleverly convince floordiv to return the ceiling. return -(-a.numerator // a.denominator) def __round__(self, ndigits=None): """Will be round(self, ndigits) in 3.0. Rounds half toward even. """ if ndigits is None: floor, remainder = divmod(self.numerator, self.denominator) if remainder * 2 < self.denominator: return floor elif remainder * 2 > self.denominator: return floor + 1 # Deal with the half case: elif floor % 2 == 0: return floor else: return floor + 1 shift = 10**abs(ndigits) # See _operator_fallbacks.forward to check that the results of # these operations will always be Fraction and therefore have # round(). if ndigits > 0: return Fraction(round(self * shift), shift) else: return Fraction(round(self / shift) * shift) def __hash__(self): """hash(self)""" # XXX since this method is expensive, consider caching the result # In order to make sure that the hash of a Fraction agrees # with the hash of a numerically equal integer, float or # Decimal instance, we follow the rules for numeric hashes # outlined in the documentation. (See library docs, 'Built-in # Types'). # dinv is the inverse of self._denominator modulo the prime # _PyHASH_MODULUS, or 0 if self._denominator is divisible by # _PyHASH_MODULUS. dinv = pow(self._denominator, _PyHASH_MODULUS - 2, _PyHASH_MODULUS) if not dinv: hash_ = _PyHASH_INF else: hash_ = abs(self._numerator) * dinv % _PyHASH_MODULUS result = hash_ if self >= 0 else -hash_ return -2 if result == -1 else result def __eq__(a, b): """a == b""" if isinstance(b, numbers.Rational): return (a._numerator == b.numerator and a._denominator == b.denominator) if isinstance(b, numbers.Complex) and b.imag == 0: b = b.real if isinstance(b, float): if math.isnan(b) or math.isinf(b): # comparisons with an infinity or nan should behave in # the same way for any finite a, so treat a as zero. return 0.0 == b else: return a == a.from_float(b) else: # Since a doesn't know how to compare with b, let's give b # a chance to compare itself with a. return NotImplemented def _richcmp(self, other, op): """Helper for comparison operators, for internal use only. Implement comparison between a Rational instance `self`, and either another Rational instance or a float `other`. If `other` is not a Rational instance or a float, return NotImplemented. `op` should be one of the six standard comparison operators. """ # convert other to a Rational instance where reasonable. if isinstance(other, numbers.Rational): return op(self._numerator * other.denominator, self._denominator * other.numerator) if isinstance(other, float): if math.isnan(other) or math.isinf(other): return op(0.0, other) else: return op(self, self.from_float(other)) else: return NotImplemented def __lt__(a, b): """a < b""" return a._richcmp(b, operator.lt) def __gt__(a, b): """a > b""" return a._richcmp(b, operator.gt) def __le__(a, b): """a <= b""" return a._richcmp(b, operator.le) def __ge__(a, b): """a >= b""" return a._richcmp(b, operator.ge) def __bool__(a): """a != 0""" return a._numerator != 0 # support for pickling, copy, and deepcopy def __reduce__(self): return (self.__class__, (str(self),)) def __copy__(self): if type(self) == Fraction: return self # I'm immutable; therefore I am my own clone return self.__class__(self._numerator, self._denominator) def __deepcopy__(self, memo): if type(self) == Fraction: return self # My components are also immutable return self.__class__(self._numerator, self._denominator)
gpl-3.0
ngcurrier/ProteusCFD
GUI/dakotaHistogram.py
1
1543
#!/usr/bin/python import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt #reads a space delimited file with a header and returns a dictionary #attempts to cast dictionary entries into floats, if it fails, leaves as is def readSpaceDelimitedFile(filename): f = open(filename, 'r') headers = f.readline().split() dict = {} for header in headers: dict[header] = [] for line in f: items = line.split() i = 0 for header in headers: try: dict[header].append(float(items[i])) except: dict[header].append(items[i]) i = i + 1 f.close() return dict #plots a histogram of data, computes basic stats, and labels chart def plotHistogram(data, seriesName): # the histogram of the data n, bins, patches = plt.hist(data, 50, normed=1, facecolor='green', alpha=0.75) mu = np.mean(data) sigma = np.std(data) # add a 'best fit' line y = mlab.normpdf(bins, mu, sigma) l = plt.plot(bins, y, 'r--', linewidth=1) plt.xlabel(seriesName) plt.ylabel('Probability') plt.title(r'$\mathrm{Histogram\ of\ ' + seriesName + ':}\ \mu=' + str(mu) +',\ \sigma=' + str(sigma) +'$') plt.grid(True) plt.show() if __name__ == '__main__': data = readSpaceDelimitedFile('dakota_tabular.dat') print data for idata in data: if idata != 'interface' and idata != '%eval_id': plotHistogram(data[idata], idata)
gpl-3.0
yawnosnorous/python-for-android
python-modules/twisted/twisted/python/test/test_inotify.py
56
3188
# Copyright (c) 2010 Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.python._inotify}. """ from twisted.trial.unittest import TestCase from twisted.python.runtime import platform if platform.supportsINotify(): from ctypes import c_int, c_char_p from twisted.python import _inotify from twisted.python._inotify import ( INotifyError, initializeModule, init, add) else: _inotify = None class INotifyTests(TestCase): """ Tests for L{twisted.python._inotify}. """ if _inotify is None: skip = "This platform doesn't support INotify." def test_missingInit(self): """ If the I{libc} object passed to L{initializeModule} has no C{inotify_init} attribute, L{ImportError} is raised. """ class libc: def inotify_add_watch(self): pass def inotify_rm_watch(self): pass self.assertRaises(ImportError, initializeModule, libc()) def test_missingAdd(self): """ If the I{libc} object passed to L{initializeModule} has no C{inotify_add_watch} attribute, L{ImportError} is raised. """ class libc: def inotify_init(self): pass def inotify_rm_watch(self): pass self.assertRaises(ImportError, initializeModule, libc()) def test_missingRemove(self): """ If the I{libc} object passed to L{initializeModule} has no C{inotify_rm_watch} attribute, L{ImportError} is raised. """ class libc: def inotify_init(self): pass def inotify_add_watch(self): pass self.assertRaises(ImportError, initializeModule, libc()) def test_setAddArgtypes(self): """ If the I{libc} object passed to L{initializeModule} has all of the necessary attributes, it sets the C{argtypes} attribute of the C{inotify_add_watch} attribute to a list describing the argument types. """ class libc: def inotify_init(self): pass def inotify_rm_watch(self): pass def inotify_add_watch(self): pass inotify_add_watch = staticmethod(inotify_add_watch) c = libc() initializeModule(c) self.assertEquals( c.inotify_add_watch.argtypes, [c_int, c_char_p, c_int]) def test_failedInit(self): """ If C{inotify_init} returns a negative number, L{init} raises L{INotifyError}. """ class libc: def inotify_init(self): return -1 self.patch(_inotify, 'libc', libc()) self.assertRaises(INotifyError, init) def test_failedAddWatch(self): """ If C{inotify_add_watch} returns a negative number, L{add} raises L{INotifyError}. """ class libc: def inotify_add_watch(self, fd, path, mask): return -1 self.patch(_inotify, 'libc', libc()) self.assertRaises(INotifyError, add, 3, '/foo', 0)
apache-2.0
FireWRT/OpenWrt-Firefly-Libraries
staging_dir/host/lib/python2.7/encodings/zlib_codec.py
533
3015
""" Python 'zlib_codec' Codec - zlib compression encoding Unlike most of the other codecs which target Unicode, this codec will return Python string objects for both encode and decode. Written by Marc-Andre Lemburg (mal@lemburg.com). """ import codecs import zlib # this codec needs the optional zlib module ! ### Codec APIs def zlib_encode(input,errors='strict'): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = zlib.compress(input) return (output, len(input)) def zlib_decode(input,errors='strict'): """ Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = zlib.decompress(input) return (output, len(input)) class Codec(codecs.Codec): def encode(self, input, errors='strict'): return zlib_encode(input, errors) def decode(self, input, errors='strict'): return zlib_decode(input, errors) class IncrementalEncoder(codecs.IncrementalEncoder): def __init__(self, errors='strict'): assert errors == 'strict' self.errors = errors self.compressobj = zlib.compressobj() def encode(self, input, final=False): if final: c = self.compressobj.compress(input) return c + self.compressobj.flush() else: return self.compressobj.compress(input) def reset(self): self.compressobj = zlib.compressobj() class IncrementalDecoder(codecs.IncrementalDecoder): def __init__(self, errors='strict'): assert errors == 'strict' self.errors = errors self.decompressobj = zlib.decompressobj() def decode(self, input, final=False): if final: c = self.decompressobj.decompress(input) return c + self.decompressobj.flush() else: return self.decompressobj.decompress(input) def reset(self): self.decompressobj = zlib.decompressobj() class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='zlib', encode=zlib_encode, decode=zlib_decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
gpl-2.0
telefonicaid/iotqatools
iotqatools/tests/test_cb_utils.py
2
10950
# -*- coding: utf-8 -*- """ Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U This file is part of telefonica-iotqatools iotqatools is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. iotqatools is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with iotqatools. If not, seehttp://www.gnu.org/licenses/. For those usages not covered by the GNU Affero General Public License please contact with::[iot_support@tid.es] """ __author__ = 'jmab20' import json from nose.tools import eq_, ok_, assert_in from iotqatools.cb_utils import CBUtils import unittest import mock last_updateContext ="" class MockResponse: def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code self.headers = {} self.content = str(json_data) def json(self): return self.json_data # This method will be used by the mock to replace requests.get def mocked_requests_get(*args, **kwargs): version = """ <orion> <version>0.24.0</version> <uptime>0 d, 3 h, 53 m, 28 s</uptime> <git_hash>ed11a3307c7050857ef398ee3e4cd04042a0cc01</git_hash> <compile_time>Mon Sep 14 17:52:44 CEST 2015</compile_time> <compiled_by>fermin</compiled_by> <compiled_in>centollo</compiled_in> </orion>""" statistics = """<orion> <xmlRequests>10</xmlRequests> <jsonRequests>25</jsonRequests> <queries>6</queries> <updates>4</updates> <subscriptions>11</subscriptions> <versionRequests>9</versionRequests> <statisticsRequests>3</statisticsRequests> <invalidRequests>2</invalidRequests> <subCacheEntries>10</subCacheEntries> <subCacheLookups>3</subCacheLookups> <uptime_in_secs>15396</uptime_in_secs> <measuring_interval_in_secs>15396</measuring_interval_in_secs> </orion>""" subscribe = """ { "subscribeResponse" : { "subscriptionId" : "5673c7fd9ddf69cafcf23000", "duration" : "PT5M" } }""" global last_updateContext if kwargs["url"] == 'http://mock.cb.com:1026/v1/updateContext': jsobj_1 = json.loads(kwargs["data"]) last_updateContext = jsobj_1['contextElements'][0] return MockResponse("", 201) elif kwargs["url"] == 'http://mock.cb.com:1026/v1/queryContext': res1 = { } res1["contextElement"] = last_updateContext response = {"contextResponses" : [] } response["contextResponses"].append(res1) return MockResponse(json.dumps(response), 200) elif kwargs["url"] == 'http://mock.cb.com:1026/v1/contextEntities/Sala01': response = { } response["contextElement"] = last_updateContext return MockResponse(json.dumps(response), 200) elif kwargs["url"] == 'http://mock.cb.com:1026/version': return MockResponse(version, 200) elif kwargs["url"] == 'http://mock.cb.com:1026/statistics': return MockResponse(statistics, 200) elif kwargs["url"] == 'http://mock.cb.com:1026/v1/subscribeContext': return MockResponse(subscribe, 200) elif kwargs["method"] == "get": response = { } response["contextElement"] = last_updateContext return MockResponse(json.dumps(response), 200) return MockResponse("not found " + kwargs["url"], 404) def mocked_requests_404(*args, **kwargs): notfound = """{"errorCode" : { "code" : "404", "reasonPhrase" : "No context element found" } }""" return MockResponse(notfound, 200) class CBUtilsTest(unittest.TestCase): def setUp(self): self.cb = CBUtils(instance='mock.cb.com', port="1026", verbosity=0) # self.cb = CBUtils(instance='195.235.93.78', port="10026", path_context="/cb/v1/contextEntities", path_query="/cb/v1/queryContext", # path_statistics="/cb/statistics", # path_subscription="/cb/v1/subscribeContext", # path_update="/cb/v1/updateContext", # path_version="/cb/version", # verbosity=0) @mock.patch('requests.request', side_effect=mocked_requests_get) def test_version(self, mock_requests): version = self.cb.version() print "### Test ---> Version: " + version.content eq_(200, version.status_code, msg="version to CB does not return 200") assert_in("orion", version.content, msg="bad data returned to query version to CB") assert_in("version", version.content, msg="bad data returned to query version to CB") @mock.patch('requests.request', side_effect=mocked_requests_get) def test_statistics(self, mock_requests): print "### Test ---> Statistics: " print self.cb.statistics().content @mock.patch('requests.request', side_effect=mocked_requests_get) def test_create_entity(self, mock_requests): print "### Test ---> Create a entity: " data0 = {'ent_type': 'Sala', 'ent_pattern': 'false', 'ent_id': 'Sala01', 'attributes': [{'name': 'temperature', 'type': 'centigrade', 'value': '99'}]} self.cb.entity_append('x222', data0) print "### Test ---> Recover the entity1 (method1): " entity1 = self.cb.entity_get('x222', 'Sala01') eq_(200, entity1.status_code, msg="Error Code") print "### Test ---> Recover the entity2 (method2):" entity2 = self.cb.entities_get('x222', 'Sala', 'Sala01', 'false') eq_(200, entity2.status_code, msg="Error Code") print "### Test ---> Recover the entities wiht pattern (method3):" entity3 = self.cb.entities_get('x222', 'Sala', 'Sala.*', 'true') eq_(200, entity2.status_code, msg="Error Code") print "### Test ---> Compare all the entities recovered: " jsobj_1 = json.loads(entity1.content) jsobj_2 = json.loads(entity2.content) jsobj_3 = json.loads(entity3.content) # Validations eq_('Sala', jsobj_1['contextElement']['type'], msg="DATA ERROR 1 {}".format(jsobj_1['contextElement']['type'])) eq_('Sala01', jsobj_1['contextElement']['id'], msg="DATA ERROR 2 {}".format(jsobj_1['contextElement']['id'])) eq_('99', jsobj_1['contextElement']['attributes'][0]['value'], msg="DATA ERROR 3 {}".format(jsobj_1['contextElement']['attributes'][0]['value'])) eq_('temperature', jsobj_1['contextElement']['attributes'][0]['name'], msg="DATA ERROR 4 {}".format(jsobj_1['contextElement']['attributes'][0]['name'])) eq_(jsobj_1['contextElement'], jsobj_2['contextResponses'][0]['contextElement'], msg='## Not equals!\n Received1: {} \n Received2: {}'.format( jsobj_1['contextElement'], jsobj_2['contextResponses'][0]['contextElement'])) eq_(jsobj_3['contextResponses'][0]['contextElement'], jsobj_2['contextResponses'][0]['contextElement'], msg='## Not equals!\n Received5: {} \n Received2: {}'.format( jsobj_3['contextResponses'][0]['contextElement'], jsobj_2['contextResponses'][0]['contextElement'])) @mock.patch('requests.request', side_effect=mocked_requests_404) def test_missing_entities(self, mock_requests): print "### Test ---> Recover missing entities: " entityb1 = self.cb.entities_get('x222', 'Sala', 'S', 'false') eq_(200, entityb1.status_code, msg="Error Code") entityb2 = self.cb.entities_get('x222', 'Sal', 'Sala01', 'false') eq_(200, entityb2.status_code, msg="Error Code") # checking it further jsobj_b1 = json.loads(entityb1.content) jsobj_b2 = json.loads(entityb2.content) eq_('404', jsobj_b1['errorCode']['code'], msg="Error Code") eq_('No context element found', jsobj_b1['errorCode']['reasonPhrase'], msg="Error Body") eq_('404', jsobj_b2['errorCode']['code'], msg="Error Code") eq_('No context element found', jsobj_b2['errorCode']['reasonPhrase'], msg="Error Body") @mock.patch('requests.request', side_effect=mocked_requests_get) def test_update_entity(self, mock_requests): print "### Test ---> Update the entity: " data0 = {'ent_type': 'Salass', 'ent_pattern': 'false', 'ent_id': 'Sala01', 'attributes': [{'name': 'temperature', 'type': 'centigrade', 'value': '99'}]} self.cb.entity_append('x222', data0) print "### Test ---> Recover the entity1 (method1): " entity1 = self.cb.entity_get('x222', 'Sala01') data1 = {'ent_type': 'Salass', 'ent_pattern': 'false', 'ent_id': 'Sala01', 'attributes': [{'name': 'temperature', 'type': 'centigrade', 'value': '101'}]} self.cb.entity_update('x222', data1) print "### Test ---> Recover the updated entity: " entity2 = self.cb.entity_get('x222', 'Sala01') eq_(200, entity1.status_code, msg="Error Code") assert_in('101', entity2.content) @mock.patch('requests.request', side_effect=mocked_requests_get) def test_subscription(self, mock_requests): print "### Test ---> Add Subscription: " data0 = {'ent_type': 'Salass', 'ent_pattern': 'false', 'ent_id': 'Sala01', 'attributes': [{'name': 'temperature', 'type': 'centigrade', 'value': '99'}]} self.cb.entity_append('x222', data0) subs0 = dict( {'ent_type': 'Sala', 'ent_pattern': 'false', 'ent_id': 'Sala99', 'notify_url': 'http://localhost:5050/notify'}) sub = self.cb.subscription_add('x222', template_data=subs0) eq_(200, sub.status_code, msg="Error Code") jssub = json.loads(sub.content) ok_(jssub['subscribeResponse']['subscriptionId'], msg="No subscription") eq_(jssub['subscribeResponse']['duration'], 'PT5M', msg="No Duration") print "### Test ---> subscription added:" print "Subscription id: {}".format(jssub['subscribeResponse']['subscriptionId']) print "Subscription duration: {}".format(jssub['subscribeResponse']['duration']) if __name__ == '__main__': unittest.main()
agpl-3.0
peter-jang/ansible
lib/ansible/compat/tests/unittest.py
375
1147
# (c) 2014, Toshio Kuratomi <tkuratomi@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type ''' Compat module for Python2.7's unittest module ''' import sys # Python 2.6 if sys.version_info < (2, 7): try: # Need unittest2 on python2.6 from unittest2 import * except ImportError: print('You need unittest2 installed on python2.6.x to run tests') else: from unittest import *
gpl-3.0
karan1276/servo
tests/wpt/css-tests/tools/py/setup.py
161
1425
import os, sys from setuptools import setup def main(): setup( name='py', description='library with cross-python path, ini-parsing, io, code, log facilities', long_description = open('README.txt').read(), version='1.4.31', url='http://pylib.readthedocs.org/', license='MIT license', platforms=['unix', 'linux', 'osx', 'cygwin', 'win32'], author='holger krekel, Ronny Pfannschmidt, Benjamin Peterson and others', author_email='pytest-dev@python.org', classifiers=['Development Status :: 6 - Mature', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities', 'Programming Language :: Python', 'Programming Language :: Python :: 3'], packages=['py', 'py._code', 'py._io', 'py._log', 'py._path', 'py._process', ], zip_safe=False, ) if __name__ == '__main__': main()
mpl-2.0
jmschrei/scikit-learn
examples/gaussian_process/plot_gpr_co2.py
9
5718
""" ======================================================== Gaussian process regression (GPR) on Mauna Loa CO2 data. ======================================================== This example is based on Section 5.4.3 of "Gaussian Processes for Machine Learning" [RW2006]. It illustrates an example of complex kernel engineering and hyperparameter optimization using gradient ascent on the log-marginal-likelihood. The data consists of the monthly average atmospheric CO2 concentrations (in parts per million by volume (ppmv)) collected at the Mauna Loa Observatory in Hawaii, between 1958 and 1997. The objective is to model the CO2 concentration as a function of the time t. The kernel is composed of several terms that are responsible for explaining different properties of the signal: - a long term, smooth rising trend is to be explained by an RBF kernel. The RBF kernel with a large length-scale enforces this component to be smooth; it is not enforced that the trend is rising which leaves this choice to the GP. The specific length-scale and the amplitude are free hyperparameters. - a seasonal component, which is to be explained by the periodic ExpSineSquared kernel with a fixed periodicity of 1 year. The length-scale of this periodic component, controlling its smoothness, is a free parameter. In order to allow decaying away from exact periodicity, the product with an RBF kernel is taken. The length-scale of this RBF component controls the decay time and is a further free parameter. - smaller, medium term irregularities are to be explained by a RationalQuadratic kernel component, whose length-scale and alpha parameter, which determines the diffuseness of the length-scales, are to be determined. According to [RW2006], these irregularities can better be explained by a RationalQuadratic than an RBF kernel component, probably because it can accommodate several length-scales. - a "noise" term, consisting of an RBF kernel contribution, which shall explain the correlated noise components such as local weather phenomena, and a WhiteKernel contribution for the white noise. The relative amplitudes and the RBF's length scale are further free parameters. Maximizing the log-marginal-likelihood after subtracting the target's mean yields the following kernel with an LML of -83.214: 34.4**2 * RBF(length_scale=41.8) + 3.27**2 * RBF(length_scale=180) * ExpSineSquared(length_scale=1.44, periodicity=1) + 0.446**2 * RationalQuadratic(alpha=17.7, length_scale=0.957) + 0.197**2 * RBF(length_scale=0.138) + WhiteKernel(noise_level=0.0336) Thus, most of the target signal (34.4ppm) is explained by a long-term rising trend (length-scale 41.8 years). The periodic component has an amplitude of 3.27ppm, a decay time of 180 years and a length-scale of 1.44. The long decay time indicates that we have a locally very close to periodic seasonal component. The correlated noise has an amplitude of 0.197ppm with a length scale of 0.138 years and a white-noise contribution of 0.197ppm. Thus, the overall noise level is very small, indicating that the data can be very well explained by the model. The figure shows also that the model makes very confident predictions until around 2015. """ print(__doc__) # Authors: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> # # License: BSD 3 clause import numpy as np from matplotlib import pyplot as plt from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels \ import RBF, WhiteKernel, RationalQuadratic, ExpSineSquared from sklearn.datasets import fetch_mldata data = fetch_mldata('mauna-loa-atmospheric-co2').data X = data[:, [1]] y = data[:, 0] # Kernel with parameters given in GPML book k1 = 66.0**2 * RBF(length_scale=67.0) # long term smooth rising trend k2 = 2.4**2 * RBF(length_scale=90.0) \ * ExpSineSquared(length_scale=1.3, periodicity=1.0) # seasonal component # medium term irregularity k3 = 0.66**2 \ * RationalQuadratic(length_scale=1.2, alpha=0.78) k4 = 0.18**2 * RBF(length_scale=0.134) \ + WhiteKernel(noise_level=0.19**2) # noise terms kernel_gpml = k1 + k2 + k3 + k4 gp = GaussianProcessRegressor(kernel=kernel_gpml, alpha=0, optimizer=None, normalize_y=True) gp.fit(X, y) print("GPML kernel: %s" % gp.kernel_) print("Log-marginal-likelihood: %.3f" % gp.log_marginal_likelihood(gp.kernel_.theta)) # Kernel with optimized parameters k1 = 50.0**2 * RBF(length_scale=50.0) # long term smooth rising trend k2 = 2.0**2 * RBF(length_scale=100.0) \ * ExpSineSquared(length_scale=1.0, periodicity=1.0, periodicity_bounds="fixed") # seasonal component # medium term irregularities k3 = 0.5**2 * RationalQuadratic(length_scale=1.0, alpha=1.0) k4 = 0.1**2 * RBF(length_scale=0.1) \ + WhiteKernel(noise_level=0.1**2, noise_level_bounds=(1e-3, np.inf)) # noise terms kernel = k1 + k2 + k3 + k4 gp = GaussianProcessRegressor(kernel=kernel, alpha=0, normalize_y=True) gp.fit(X, y) print("\nLearned kernel: %s" % gp.kernel_) print("Log-marginal-likelihood: %.3f" % gp.log_marginal_likelihood(gp.kernel_.theta)) X_ = np.linspace(X.min(), X.max() + 30, 1000)[:, np.newaxis] y_pred, y_std = gp.predict(X_, return_std=True) # Illustration plt.scatter(X, y, c='k') plt.plot(X_, y_pred) plt.fill_between(X_[:, 0], y_pred - y_std, y_pred + y_std, alpha=0.5, color='k') plt.xlim(X_.min(), X_.max()) plt.xlabel("Year") plt.ylabel(r"CO$_2$ in ppm") plt.title(r"Atmospheric CO$_2$ concentration at Mauna Loa") plt.tight_layout() plt.show()
bsd-3-clause
auduny/home-assistant
homeassistant/components/uk_transport/sensor.py
15
9530
"""Support for UK public transport data provided by transportapi.com. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.uk_transport/ """ import logging import re from datetime import datetime, timedelta import requests import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_MODE from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) ATTR_ATCOCODE = 'atcocode' ATTR_LOCALITY = 'locality' ATTR_STOP_NAME = 'stop_name' ATTR_REQUEST_TIME = 'request_time' ATTR_NEXT_BUSES = 'next_buses' ATTR_STATION_CODE = 'station_code' ATTR_CALLING_AT = 'calling_at' ATTR_NEXT_TRAINS = 'next_trains' CONF_API_APP_KEY = 'app_key' CONF_API_APP_ID = 'app_id' CONF_QUERIES = 'queries' CONF_ORIGIN = 'origin' CONF_DESTINATION = 'destination' _QUERY_SCHEME = vol.Schema({ vol.Required(CONF_MODE): vol.All(cv.ensure_list, [vol.In(list(['bus', 'train']))]), vol.Required(CONF_ORIGIN): cv.string, vol.Required(CONF_DESTINATION): cv.string, }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_API_APP_ID): cv.string, vol.Required(CONF_API_APP_KEY): cv.string, vol.Required(CONF_QUERIES): [_QUERY_SCHEME], }) def setup_platform(hass, config, add_entities, discovery_info=None): """Get the uk_transport sensor.""" sensors = [] number_sensors = len(config.get(CONF_QUERIES)) interval = timedelta(seconds=87*number_sensors) for query in config.get(CONF_QUERIES): if 'bus' in query.get(CONF_MODE): stop_atcocode = query.get(CONF_ORIGIN) bus_direction = query.get(CONF_DESTINATION) sensors.append( UkTransportLiveBusTimeSensor( config.get(CONF_API_APP_ID), config.get(CONF_API_APP_KEY), stop_atcocode, bus_direction, interval)) elif 'train' in query.get(CONF_MODE): station_code = query.get(CONF_ORIGIN) calling_at = query.get(CONF_DESTINATION) sensors.append( UkTransportLiveTrainTimeSensor( config.get(CONF_API_APP_ID), config.get(CONF_API_APP_KEY), station_code, calling_at, interval)) add_entities(sensors, True) class UkTransportSensor(Entity): """ Sensor that reads the UK transport web API. transportapi.com provides comprehensive transport data for UK train, tube and bus travel across the UK via simple JSON API. Subclasses of this base class can be used to access specific types of information. """ TRANSPORT_API_URL_BASE = "https://transportapi.com/v3/uk/" ICON = 'mdi:train' def __init__(self, name, api_app_id, api_app_key, url): """Initialize the sensor.""" self._data = {} self._api_app_id = api_app_id self._api_app_key = api_app_key self._url = self.TRANSPORT_API_URL_BASE + url self._name = name self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" return "min" @property def icon(self): """Icon to use in the frontend, if any.""" return self.ICON def _do_api_request(self, params): """Perform an API request.""" request_params = dict({ 'app_id': self._api_app_id, 'app_key': self._api_app_key, }, **params) response = requests.get(self._url, params=request_params) if response.status_code != 200: _LOGGER.warning('Invalid response from API') elif 'error' in response.json(): if 'exceeded' in response.json()['error']: self._state = 'Usage limits exceeded' if 'invalid' in response.json()['error']: self._state = 'Credentials invalid' else: self._data = response.json() class UkTransportLiveBusTimeSensor(UkTransportSensor): """Live bus time sensor from UK transportapi.com.""" ICON = 'mdi:bus' def __init__(self, api_app_id, api_app_key, stop_atcocode, bus_direction, interval): """Construct a live bus time sensor.""" self._stop_atcocode = stop_atcocode self._bus_direction = bus_direction self._next_buses = [] self._destination_re = re.compile( '{}'.format(bus_direction), re.IGNORECASE ) sensor_name = 'Next bus to {}'.format(bus_direction) stop_url = 'bus/stop/{}/live.json'.format(stop_atcocode) UkTransportSensor.__init__( self, sensor_name, api_app_id, api_app_key, stop_url ) self.update = Throttle(interval)(self._update) def _update(self): """Get the latest live departure data for the specified stop.""" params = {'group': 'route', 'nextbuses': 'no'} self._do_api_request(params) if self._data != {}: self._next_buses = [] for (route, departures) in self._data['departures'].items(): for departure in departures: if self._destination_re.search(departure['direction']): self._next_buses.append({ 'route': route, 'direction': departure['direction'], 'scheduled': departure['aimed_departure_time'], 'estimated': departure['best_departure_estimate'] }) if self._next_buses: self._state = min( _delta_mins(bus['scheduled']) for bus in self._next_buses) else: self._state = None @property def device_state_attributes(self): """Return other details about the sensor state.""" attrs = {} if self._data is not None: for key in [ ATTR_ATCOCODE, ATTR_LOCALITY, ATTR_STOP_NAME, ATTR_REQUEST_TIME ]: attrs[key] = self._data.get(key) attrs[ATTR_NEXT_BUSES] = self._next_buses return attrs class UkTransportLiveTrainTimeSensor(UkTransportSensor): """Live train time sensor from UK transportapi.com.""" ICON = 'mdi:train' def __init__(self, api_app_id, api_app_key, station_code, calling_at, interval): """Construct a live bus time sensor.""" self._station_code = station_code self._calling_at = calling_at self._next_trains = [] sensor_name = 'Next train to {}'.format(calling_at) query_url = 'train/station/{}/live.json'.format(station_code) UkTransportSensor.__init__( self, sensor_name, api_app_id, api_app_key, query_url ) self.update = Throttle(interval)(self._update) def _update(self): """Get the latest live departure data for the specified stop.""" params = {'darwin': 'false', 'calling_at': self._calling_at, 'train_status': 'passenger'} self._do_api_request(params) self._next_trains = [] if self._data != {}: if self._data['departures']['all'] == []: self._state = 'No departures' else: for departure in self._data['departures']['all']: self._next_trains.append({ 'origin_name': departure['origin_name'], 'destination_name': departure['destination_name'], 'status': departure['status'], 'scheduled': departure['aimed_departure_time'], 'estimated': departure['expected_departure_time'], 'platform': departure['platform'], 'operator_name': departure['operator_name'] }) if self._next_trains: self._state = min( _delta_mins(train['scheduled']) for train in self._next_trains) else: self._state = None @property def device_state_attributes(self): """Return other details about the sensor state.""" attrs = {} if self._data is not None: attrs[ATTR_STATION_CODE] = self._station_code attrs[ATTR_CALLING_AT] = self._calling_at if self._next_trains: attrs[ATTR_NEXT_TRAINS] = self._next_trains return attrs def _delta_mins(hhmm_time_str): """Calculate time delta in minutes to a time in hh:mm format.""" now = datetime.now() hhmm_time = datetime.strptime(hhmm_time_str, '%H:%M') hhmm_datetime = datetime( now.year, now.month, now.day, hour=hhmm_time.hour, minute=hhmm_time.minute ) if hhmm_datetime < now: hhmm_datetime += timedelta(days=1) delta_mins = (hhmm_datetime - now).seconds // 60 return delta_mins
apache-2.0
dietrichc/streamline-ppc-reports
examples/dfp/v201408/inventory_service/update_ad_units.py
4
2877
#!/usr/bin/python # # Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This code example updates ad unit sizes by adding a banner ad size. To determine which ad units exist, run get_all_ad_units.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication information" section of our README. Tags: InventoryService.getAdUnit Tags: InventoryService.updateAdUnits """ __author__ = ('Nicholas Chen', 'Joseph DiLallo') # Import appropriate modules from the client library. from googleads import dfp # Set the ID of the ad unit to get. AD_UNIT_ID = 'INSERT_AD_UNIT_ID_HERE' def main(client, ad_unit_id): # Initialize appropriate service. inventory_service = client.GetService('InventoryService', version='v201408') # Create a statement to select a single ad unit by ID. values = [{ 'key': 'id', 'value': { 'xsi_type': 'TextValue', 'value': ad_unit_id } }] query = 'WHERE id = :id' statement = dfp.FilterStatement(query, values) # Get ad units by statement. response = inventory_service.getAdUnitsByStatement( statement.ToStatement()) # Add the size 468x60 to the ad unit. ad_unit_size = { 'size': { 'width': '468', 'height': '60' }, 'environmentType': 'BROWSER' } if 'results' in response: updated_ad_units = [] for ad_unit in response['results']: if 'adUnitSizes' not in ad_unit: ad_unit['adUnitSizes'] = [] ad_unit['adUnitSizes'].append(ad_unit_size) updated_ad_units.append(ad_unit) # Update ad unit on the server. ad_units = inventory_service.updateAdUnits(updated_ad_units) # Display results. for ad_unit in ad_units: ad_unit_sizes = ['{%s x %s}' % (size['size']['width'], size['size']['height']) for size in ad_unit['adUnitSizes']] print ('Ad unit with ID \'%s\', name \'%s\', and sizes [%s] was updated' % (ad_unit['id'], ad_unit['name'], ','.join(ad_unit_sizes))) if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpClient.LoadFromStorage() main(dfp_client, AD_UNIT_ID)
apache-2.0
ngageoint/voxel-globe
voxel_globe/tools/enu.py
2
3907
from numpy import sin, cos, pi, arctan, arctan2 def llh2enu_au(llh_origin, llh): ''' someone else's code''' a = 6378137.0 b = 6356752.3142 e2 = 1 - (b/a)**2 phi = llh_origin[0]*pi/180.0 lam = llh_origin[1]*pi/180.0 h = llh_origin[2] dphi = llh[0]*pi/180.0 - phi dlam = llh[1]*pi/180.0 - lam dh = llh[2] - h tmp1 = (1-e2*sin(phi)**2)**0.5 cl = cos(lam) sl = sin(lam) cp = cos(phi) sp = sin(phi) de = (a/tmp1+h)*cp*dlam - (a*(1-e2)/(tmp1**3)+h)*sp*dphi*dlam +cp*dlam*dh dn = (a*(1-e2)/tmp1**3 + h)*dphi + 1.5*cp*sp*a*e2*dphi**2 + sp**2*dh*dphi + 0.5*sp*cp*(a/tmp1 +h)*dlam**2 du = dh - 0.5*(a-1.5*a*e2*cp**2+0.5*a*e2+h)*dphi**2 - 0.5*cp**2*(a/tmp1 -h)*dlam**2 return [de, dn, du] def llh2enu(lat_origin, lon_origin, h_origin, lat, lon, h): ''' Take a lon lat height (degrees and meters) origin point and lat lon height number or numpy array) and returns the e, n, u, at the origin''' xyz = llh2xyz(lat, lon, h) enu = xyz2enu(lat_origin, lon_origin, h_origin, *xyz) enu_dict = {'east':enu[0], 'north':enu[1], 'up':enu[2]} return enu def enu2llh(lat_origin, lon_origin, h_origin, east, north, up): ''' llh origin can be 1x1 each enu can be a numpy array each''' xyz = enu2xyz(lat_origin, lon_origin, h_origin, east, north, up) llh = xyz2llh(*xyz) llh_dict = {'lat':llh[0], 'lon':llh[1], 'h':llh[2]} return llh_dict def llh2xyz(lat,lon,h): # Convert lat, long, height in WGS84 to ECEF X,Y,Z # lat and long given in decimal degrees. # altitude should be given in meters lat = lat/180.0*pi; #converting to radians lon = lon/180.0*pi; #converting to radians a = 6378137.0; # earth semimajor axis in meters f = 1/298.257223563; # reciprocal flattening e2 = 2*f -f**2; # eccentricity squared chi = (1-e2*(sin(lat))**2)**0.5 X = (a/chi +h)*cos(lat)*cos(lon) Y = (a/chi +h)*cos(lat)*sin(lon) Z = (a*(1-e2)/chi + h)*sin(lat) return (X, Y, Z) def xyz2enu(refLat, refLong, refH, X, Y, Z): # convert ECEF coordinates to local east, north, up # find reference location in ECEF coordinates Xr,Yr,Zr = llh2xyz(refLat,refLong, refH) refLat = refLat/180.0*pi refLong = refLong/180.0*pi e = -sin(refLong)*(X-Xr) + cos(refLong)*(Y-Yr) n = -sin(refLat)*cos(refLong)*(X-Xr) - sin(refLat)*sin(refLong)*(Y-Yr) + cos(refLat)*(Z-Zr) u = cos(refLat)*cos(refLong)*(X-Xr) + cos(refLat)*sin(refLong)*(Y-Yr) + sin(refLat)*(Z-Zr) return (e, n, u) def enu2xyz(refLat, refLong, refH, e, n, u): # Convert east, north, up coordinates (labeled e, n, u) to ECEF # coordinates. The reference point (phi, lambda, h) must be given. All distances are in metres [Xr,Yr,Zr] = llh2xyz(refLat,refLong, refH); # location of reference point refLat = refLat/180.0*pi refLong = refLong/180.0*pi X = -sin(refLong)*e - cos(refLong)*sin(refLat)*n + cos(refLong)*cos(refLat)*u + Xr Y = cos(refLong)*e - sin(refLong)*sin(refLat)*n + cos(refLat)*sin(refLong)*u + Yr Z = cos(refLat)*n + sin(refLat)*u + Zr return (X, Y, Z) def xyz2llh(X,Y,Z): ''' go from x, y, z, (nunpy array in meters) and converts to lon, lat, height ''' a = 6378137.0; # earth semimajor axis in meters f = 1/298.257223563; # reciprocal flattening b = a*(1-f);# semi-minor axis e2 = 2*f-f**2;# first eccentricity squared ep2 = f*(2-f)/((1-f)**2); # second eccentricity squared r2 = X**2+Y**2 r = (r2)**0.5 E2 = a**2 - b**2 F = 54*b**2*Z**2 G = r2 + (1-e2)*Z**2 - e2*E2 c = (e2*e2*F*r2)/(G*G*G) s = ( 1 + c + (c*c + 2*c)**0.5 )**(1/3) P = F/(3*(s+1/s+1)**2*G*G) Q = (1+2*e2*e2*P)**0.5 ro = -(e2*P*r)/(1+Q) + ((a*a/2)*(1+1/Q) - ((1-e2)*P*Z**2)/(Q*(1+Q)) - P*r2/2)**0.5 tmp = (r - e2*ro)**2 U = ( tmp + Z**2 )**0.5 V = ( tmp + (1-e2)*Z**2 )**0.5 zo = (b**2*Z)/(a*V) lat = arctan( (Z + ep2*zo)/r )*180/pi lon = arctan2(Y,X)*180/pi h = U*( 1 - b**2/(a*V)) return (lat, lon, h)
mit
CedarLogic/ansible
lib/ansible/utils/unicode.py
80
11275
# (c) 2012-2014, Toshio Kuraotmi <a.badger@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from six import string_types, text_type, binary_type, PY3 # to_bytes and to_unicode were written by Toshio Kuratomi for the # python-kitchen library https://pypi.python.org/pypi/kitchen # They are licensed in kitchen under the terms of the GPLv2+ # They were copied and modified for use in ansible by Toshio in Jan 2015 # (simply removing the deprecated features) #: Aliases for the utf-8 codec _UTF8_ALIASES = frozenset(('utf-8', 'UTF-8', 'utf8', 'UTF8', 'utf_8', 'UTF_8', 'utf', 'UTF', 'u8', 'U8')) #: Aliases for the latin-1 codec _LATIN1_ALIASES = frozenset(('latin-1', 'LATIN-1', 'latin1', 'LATIN1', 'latin', 'LATIN', 'l1', 'L1', 'cp819', 'CP819', '8859', 'iso8859-1', 'ISO8859-1', 'iso-8859-1', 'ISO-8859-1')) # EXCEPTION_CONVERTERS is defined below due to using to_unicode if PY3: basestring = (str, bytes) def to_unicode(obj, encoding='utf-8', errors='replace', nonstring=None): '''Convert an object into a :class:`unicode` string :arg obj: Object to convert to a :class:`unicode` string. This should normally be a byte :class:`str` :kwarg encoding: What encoding to try converting the byte :class:`str` as. Defaults to :term:`utf-8` :kwarg errors: If errors are found while decoding, perform this action. Defaults to ``replace`` which replaces the invalid bytes with a character that means the bytes were unable to be decoded. Other values are the same as the error handling schemes in the `codec base classes <http://docs.python.org/library/codecs.html#codec-base-classes>`_. For instance ``strict`` which raises an exception and ``ignore`` which simply omits the non-decodable characters. :kwarg nonstring: How to treat nonstring values. Possible values are: :simplerepr: Attempt to call the object's "simple representation" method and return that value. Python-2.3+ has two methods that try to return a simple representation: :meth:`object.__unicode__` and :meth:`object.__str__`. We first try to get a usable value from :meth:`object.__unicode__`. If that fails we try the same with :meth:`object.__str__`. :empty: Return an empty :class:`unicode` string :strict: Raise a :exc:`TypeError` :passthru: Return the object unchanged :repr: Attempt to return a :class:`unicode` string of the repr of the object Default is ``simplerepr`` :raises TypeError: if :attr:`nonstring` is ``strict`` and a non-:class:`basestring` object is passed in or if :attr:`nonstring` is set to an unknown value :raises UnicodeDecodeError: if :attr:`errors` is ``strict`` and :attr:`obj` is not decodable using the given encoding :returns: :class:`unicode` string or the original object depending on the value of :attr:`nonstring`. Usually this should be used on a byte :class:`str` but it can take both byte :class:`str` and :class:`unicode` strings intelligently. Nonstring objects are handled in different ways depending on the setting of the :attr:`nonstring` parameter. The default values of this function are set so as to always return a :class:`unicode` string and never raise an error when converting from a byte :class:`str` to a :class:`unicode` string. However, when you do not pass validly encoded text (or a nonstring object), you may end up with output that you don't expect. Be sure you understand the requirements of your data, not just ignore errors by passing it through this function. ''' # Could use isbasestring/isunicode here but we want this code to be as # fast as possible if isinstance(obj, basestring): if isinstance(obj, text_type): return obj if encoding in _UTF8_ALIASES: return text_type(obj, 'utf-8', errors) if encoding in _LATIN1_ALIASES: return text_type(obj, 'latin-1', errors) return obj.decode(encoding, errors) if not nonstring: nonstring = 'simplerepr' if nonstring == 'empty': return u'' elif nonstring == 'passthru': return obj elif nonstring == 'simplerepr': try: simple = obj.__unicode__() except (AttributeError, UnicodeError): simple = None if not simple: try: simple = text_type(obj) except UnicodeError: try: simple = obj.__str__() except (UnicodeError, AttributeError): simple = u'' if isinstance(simple, binary_type): return text_type(simple, encoding, errors) return simple elif nonstring in ('repr', 'strict'): obj_repr = repr(obj) if isinstance(obj_repr, binary_type): obj_repr = text_type(obj_repr, encoding, errors) if nonstring == 'repr': return obj_repr raise TypeError('to_unicode was given "%(obj)s" which is neither' ' a byte string (str) or a unicode string' % {'obj': obj_repr.encode(encoding, 'replace')}) raise TypeError('nonstring value, %(param)s, is not set to a valid' ' action' % {'param': nonstring}) def to_bytes(obj, encoding='utf-8', errors='replace', nonstring=None): '''Convert an object into a byte :class:`str` :arg obj: Object to convert to a byte :class:`str`. This should normally be a :class:`unicode` string. :kwarg encoding: Encoding to use to convert the :class:`unicode` string into a byte :class:`str`. Defaults to :term:`utf-8`. :kwarg errors: If errors are found while encoding, perform this action. Defaults to ``replace`` which replaces the invalid bytes with a character that means the bytes were unable to be encoded. Other values are the same as the error handling schemes in the `codec base classes <http://docs.python.org/library/codecs.html#codec-base-classes>`_. For instance ``strict`` which raises an exception and ``ignore`` which simply omits the non-encodable characters. :kwarg nonstring: How to treat nonstring values. Possible values are: :simplerepr: Attempt to call the object's "simple representation" method and return that value. Python-2.3+ has two methods that try to return a simple representation: :meth:`object.__unicode__` and :meth:`object.__str__`. We first try to get a usable value from :meth:`object.__str__`. If that fails we try the same with :meth:`object.__unicode__`. :empty: Return an empty byte :class:`str` :strict: Raise a :exc:`TypeError` :passthru: Return the object unchanged :repr: Attempt to return a byte :class:`str` of the :func:`repr` of the object Default is ``simplerepr``. :raises TypeError: if :attr:`nonstring` is ``strict`` and a non-:class:`basestring` object is passed in or if :attr:`nonstring` is set to an unknown value. :raises UnicodeEncodeError: if :attr:`errors` is ``strict`` and all of the bytes of :attr:`obj` are unable to be encoded using :attr:`encoding`. :returns: byte :class:`str` or the original object depending on the value of :attr:`nonstring`. .. warning:: If you pass a byte :class:`str` into this function the byte :class:`str` is returned unmodified. It is **not** re-encoded with the specified :attr:`encoding`. The easiest way to achieve that is:: to_bytes(to_unicode(text), encoding='utf-8') The initial :func:`to_unicode` call will ensure text is a :class:`unicode` string. Then, :func:`to_bytes` will turn that into a byte :class:`str` with the specified encoding. Usually, this should be used on a :class:`unicode` string but it can take either a byte :class:`str` or a :class:`unicode` string intelligently. Nonstring objects are handled in different ways depending on the setting of the :attr:`nonstring` parameter. The default values of this function are set so as to always return a byte :class:`str` and never raise an error when converting from unicode to bytes. However, when you do not pass an encoding that can validly encode the object (or a non-string object), you may end up with output that you don't expect. Be sure you understand the requirements of your data, not just ignore errors by passing it through this function. ''' # Could use isbasestring, isbytestring here but we want this to be as fast # as possible if isinstance(obj, basestring): if isinstance(obj, binary_type): return obj return obj.encode(encoding, errors) if not nonstring: nonstring = 'simplerepr' if nonstring == 'empty': return b'' elif nonstring == 'passthru': return obj elif nonstring == 'simplerepr': try: simple = str(obj) except UnicodeError: try: simple = obj.__str__() except (AttributeError, UnicodeError): simple = None if not simple: try: simple = obj.__unicode__() except (AttributeError, UnicodeError): simple = b'' if isinstance(simple, text_type): simple = simple.encode(encoding, 'replace') return simple elif nonstring in ('repr', 'strict'): try: obj_repr = obj.__repr__() except (AttributeError, UnicodeError): obj_repr = b'' if isinstance(obj_repr, text_type): obj_repr = obj_repr.encode(encoding, errors) else: obj_repr = binary_type(obj_repr) if nonstring == 'repr': return obj_repr raise TypeError('to_bytes was given "%(obj)s" which is neither' ' a unicode string or a byte string (str)' % {'obj': obj_repr}) raise TypeError('nonstring value, %(param)s, is not set to a valid' ' action' % {'param': nonstring}) # force the return value of a function to be unicode. Use with partial to # ensure that a filter will return unicode values. def unicode_wrap(func, *args, **kwargs): return to_unicode(func(*args, **kwargs), nonstring='passthru')
gpl-3.0
Dee-UK/RK3188_tablet_kernel_sources
Documentation/networking/cxacru-cf.py
14668
1626
#!/usr/bin/env python # Copyright 2009 Simon Arlott # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; either version 2 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 59 # Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Usage: cxacru-cf.py < cxacru-cf.bin # Output: values string suitable for the sysfs adsl_config attribute # # Warning: cxacru-cf.bin with MD5 hash cdbac2689969d5ed5d4850f117702110 # contains mis-aligned values which will stop the modem from being able # to make a connection. If the first and last two bytes are removed then # the values become valid, but the modulation will be forced to ANSI # T1.413 only which may not be appropriate. # # The original binary format is a packed list of le32 values. import sys import struct i = 0 while True: buf = sys.stdin.read(4) if len(buf) == 0: break elif len(buf) != 4: sys.stdout.write("\n") sys.stderr.write("Error: read {0} not 4 bytes\n".format(len(buf))) sys.exit(1) if i > 0: sys.stdout.write(" ") sys.stdout.write("{0:x}={1}".format(i, struct.unpack("<I", buf)[0])) i += 1 sys.stdout.write("\n")
gpl-2.0
peterbe/moztrap
tests/model/library/test_importer.py
5
28211
"""Tests for suite/case importer.""" from tests import case from mock import patch from moztrap.model.library.importer import ImportResult, SuiteImporter class ImporterTestBase(object): """Common base class for importer tests.""" def setUp(self): """Setup for importer tests; create a product version.""" self.pv = self.F.ProductVersionFactory.create() def import_data(self, case_data): """Instantiate ``Importer``, call ``import_data`` and return result.""" from moztrap.model.library.importer import Importer return Importer().import_data(self.pv, case_data) class ImporterTest(ImporterTestBase, case.DBTestCase): """Tests for ``Importer``.""" def test_create_caseversion(self): """Successful import creates a caseversion with expected values.""" self.import_data( { "cases": [ { "name": "Foo", "steps": [{"instruction": "do this"}], } ] } ) cv = self.model.CaseVersion.objects.get() self.assertEqual(cv.name, "Foo") self.assertEqual(cv.productversion, self.pv) self.assertEqual(cv.case.product, self.pv.product) def test_create_caseversion_idprefix(self): """Successful import creates a caseversion with an idprefix.""" self.import_data( { "cases": [ { "name": "Foo", "idprefix": "wow", "steps": [{"instruction": "do this"}], } ] } ) cv = self.model.CaseVersion.objects.get() self.assertEqual(cv.name, "Foo") self.assertEqual(cv.case.idprefix, "wow") self.assertEqual(cv.productversion, self.pv) self.assertEqual(cv.case.product, self.pv.product) def test_create_caseversion_description(self): """Test the description field of a new test case""" result = self.import_data( { "cases": [ { "description": "case description", "name": "Foo", "steps": [{"instruction": "do this"}], } ] } ) cv = self.model.CaseVersion.objects.get() self.assertEqual(cv.description, "case description") self.assertEqual(result.num_cases, 1) def test_create_caseversion_tags(self): """Test that case tags get created and assigned""" new_tags = ["tag1", "tag2", "tag3"] result = self.import_data( { "cases": [ { "name": "Foo", "steps": [{"instruction": "do this"}], "tags": new_tags, } ] } ) cv = self.model.CaseVersion.objects.get() case_tags = [tag.name for tag in cv.tags.all()] self.assertEqual(set(case_tags), set(new_tags)) self.assertEqual(result.num_cases, 1) def test_create_caseversion_suites(self): """Test that case suites get created and assigned""" new_suites = ["suite1 name", "suite2 name", "suite3 name"] result = self.import_data( { "cases": [ { "name": "Foo", "steps": [{"instruction": "do this"}], "suites": new_suites, } ] } ) cv = self.model.CaseVersion.objects.get() case_suites = [suite.name for suite in cv.case.suites.all()] self.assertEqual(set(case_suites), set(new_suites)) self.assertEqual(result.num_cases, 1) def test_create_caseversion_existing_user(self): """A case with created_by field filled with existing user""" # need a user to exist, so the import can find it. user = self.F.UserFactory.create(email="sumbudee@mozilla.com") result = self.import_data( { "cases": [ { "created_by": "sumbudee@mozilla.com", "name": "Foo", "steps": [{"instruction": "do this"}] } ] } ) cv = self.model.CaseVersion.objects.get() self.assertEqual(cv.created_by, user) self.assertEqual(result.num_cases, 1) def test_create_two_caseversions_same_user(self): """ Two caseversions that both use the same user. Test that import caches the user and doesn't have to query for it a second time. Expect 19 queries for this import: Query 1: Ensure this caseversion does not already exist for this productversion:: SELECT (1) AS `a` FROM `library_caseversion` WHERE (`library_caseversion`.`deleted_on` IS NULL AND `library_caseversion`.`name` = Foo AND `library_caseversion`.`productversion_id` = 12 ) LIMIT 1 Query 2: Find the user for this email:: SELECT `auth_user`.`id`, `auth_user`.`username`, `auth_user`.`first_name`, `auth_user`.`last_name`, `auth_user`.`email`, `auth_user`.`password`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.`is_superuser`, `auth_user`.`last_login`, `auth_user`.`date_joined` FROM `auth_user` WHERE `auth_user`.`email` = sumbudee@mozilla.com Transaction: SAVEPOINT s140735243669888_x1 Query 3: Create the first new case object:: INSERT INTO `library_case` (`created_on`, `created_by_id`, `modified_on`, `modified_by_id`, `deleted_on`, `deleted_by_id`, `product_id`) VALUES (2012-03-07 19:35:34, None, 2012-03-07 19:35:34, None, None, None, 12) Queries 4-8: Create the first new caseversion object:: INSERT INTO `library_caseversion` (`created_on`, `created_by_id`, `modified_on`, `modified_by_id`, `deleted_on`, `deleted_by_id`, `status`, `productversion_id`, `case_id`, `name`, `description`, `latest`, `envs_narrowed`) VALUES (2012-03-07 19:35:34, 2, 2012-03-07 19:35:34, 2, None, None, draft, 12, 10, Foo, , False, False) SELECT `environments_environment`.`id`, `environments_environment`.`created_on`, `environments_environment`.`created_by_id`, `environments_environment`.`modified_on`, `environments_environment`.`modified_by_id`, `environments_environment`.`deleted_on`, `environments_environment`.`deleted_by_id`, `environments_environment`.`profile_id` FROM `environments_environment` INNER JOIN `core_productversion_environments` ON (`environments_environment`.`id` = `core_productversion_environments`.`environment_id`) WHERE (`environments_environment`.`deleted_on` IS NULL AND `core_productversion_environments`.`productversion_id` = 12 ) SELECT `library_caseversion`.`id`, `library_caseversion`.`created_on`, `library_caseversion`.`created_by_id`, `library_caseversion`.`modified_on`, `library_caseversion`.`modified_by_id`, `library_caseversion`.`deleted_on`, `library_caseversion`.`deleted_by_id`, `library_caseversion`.`status`, `library_caseversion`.`productversion_id`, `library_caseversion`.`case_id`, `library_caseversion`.`name`, `library_caseversion`.`description`, `library_caseversion`.`latest`, `library_caseversion`.`envs_narrowed` FROM `library_caseversion` INNER JOIN `core_productversion` ON (`library_caseversion`.`productversion_id` = `core_productversion`.`id`) WHERE (`library_caseversion`.`deleted_on` IS NULL AND `library_caseversion`.`case_id` = 10 ) ORDER BY `core_productversion`.`order` DESC LIMIT 1 UPDATE `library_caseversion` SET `latest` = False WHERE (`library_caseversion`.`deleted_on` IS NULL AND `library_caseversion`.`case_id` = 10 ) UPDATE `library_caseversion` SET `created_on` = 2012-03-07 19:35:34, `created_by_id` = 2, `modified_on` = 2012-03-07 19:35:34, `modified_by_id` = 2, `deleted_on` = NULL, `deleted_by_id` = NULL, `status` = draft, `productversion_id` = 12, `case_id` = 10, `name` = Foo, `description` = , `latest` = True, `envs_narrowed` = False WHERE `library_caseversion`.`id` = 10 Query 9: During save, check if there are other caseversions for this case to sync names. SELECT `library_caseversion`.`id`, `library_caseversion` .`created_on`, `library_caseversion`.`created_by_id`, `library_caseversion` .`modified_on`, `library_caseversion`.`modified_by_id`, `library_caseversion` .`deleted_on`, `library_caseversion`.`deleted_by_id`, `library_caseversion` .`cc_version`, `library_caseversion`.`status`, `library_caseversion` .`productversion_id`, `library_caseversion`.`case_id`, `library_caseversion`.`name`, `library_caseversion`.`description`, `library_caseversion` .`latest`, `library_caseversion`.`envs_narrowed` FROM `library_caseversion` INNER JOIN `core_productversion` ON (`library_caseversion` .`productversion_id` = `core_productversion`.`id`) WHERE (`library_caseversion` .`deleted_on` IS NULL AND `library_caseversion`.`case_id` = 1 ) ORDER BY `library_caseversion`.`case_id` ASC, `core_productversion`.`order` ASC Query 10: Add the new step to the caseversion:: INSERT INTO `library_casestep` (`created_on`, `created_by_id`, `modified_on`, `modified_by_id`, `deleted_on`, `deleted_by_id`, `caseversion_id`, `number`, `instruction`, `expected`) VALUES (2012-03-07 19:35:34, None, 2012-03-07 19:35:34, None, None, None, 10, 1, do this, ) Transaction: RELEASE SAVEPOINT s140735243669888_x1 Query 11: Ensure the second caseversion with this name and pv doesn't exist:: SELECT (1) AS `a` FROM `library_caseversion` WHERE (`library_caseversion`.`deleted_on` IS NULL AND `library_caseversion`.`name` = Bar AND `library_caseversion`.`productversion_id` = 12 ) LIMIT 1 Transaction: SAVEPOINT s140735243669888_x2 **NOTE: We didn't have to search for the user again, since it was cached** Query 12: Create the second new case:: INSERT INTO `library_case` (`created_on`, `created_by_id`, `modified_on`, `modified_by_id`, `deleted_on`, `deleted_by_id`, `product_id`) VALUES (2012-03-07 19:35:34, None, 2012-03-07 19:35:34, None, None, None, 12) Queries 13-17: Create the second new caseversion:: INSERT INTO `library_caseversion` (`created_on`, `created_by_id`, `modified_on`, `modified_by_id`, `deleted_on`, `deleted_by_id`, `status`, `productversion_id`, `case_id`, `name`, `description`, `latest`, `envs_narrowed`) VALUES (2012-03-07 19:35:34, 2, 2012-03-07 19:35:34, 2, None, None, draft, 12, 11, Bar, , False, False) SELECT `environments_environment`.`id`, `environments_environment`.`created_on`, `environments_environment`.`created_by_id`, `environments_environment`.`modified_on`, `environments_environment`.`modified_by_id`, `environments_environment`.`deleted_on`, `environments_environment`.`deleted_by_id`, `environments_environment`.`profile_id` FROM `environments_environment` INNER JOIN `core_productversion_environments` ON (`environments_environment`.`id` = `core_productversion_environments`.`environment_id`) WHERE (`environments_environment`.`deleted_on` IS NULL AND `core_productversion_environments`.`productversion_id` = 12 ) SELECT `library_caseversion`.`id`, `library_caseversion`.`created_on`, `library_caseversion`.`created_by_id`, `library_caseversion`.`modified_on`, `library_caseversion`.`modified_by_id`, `library_caseversion`.`deleted_on`, `library_caseversion`.`deleted_by_id`, `library_caseversion`.`status`, `library_caseversion`.`productversion_id`, `library_caseversion`.`case_id`, `library_caseversion`.`name`, `library_caseversion`.`description`, `library_caseversion`.`latest`, `library_caseversion`.`envs_narrowed` FROM `library_caseversion` INNER JOIN `core_productversion` ON (`library_caseversion`.`productversion_id` = `core_productversion`.`id`) WHERE (`library_caseversion`.`deleted_on` IS NULL AND `library_caseversion`.`case_id` = 11 ) ORDER BY `core_productversion`.`order` DESC LIMIT 1 UPDATE `library_caseversion` SET `latest` = False WHERE (`library_caseversion`.`deleted_on` IS NULL AND `library_caseversion`.`case_id` = 11 ) UPDATE `library_caseversion` SET `created_on` = 2012-03-07 19:35:34, `created_by_id` = 2, `modified_on` = 2012-03-07 19:35:34, `modified_by_id` = 2, `deleted_on` = NULL, `deleted_by_id` = NULL, `status` = draft, `productversion_id` = 12, `case_id` = 11, `name` = Bar, `description` = , `latest` = True, `envs_narrowed` = False WHERE `library_caseversion`.`id` = 11 Query 18: Check for other caseversions for the same case to sync names SELECT `library_caseversion`.`id`, `library_caseversion` .`created_on`, `library_caseversion`.`created_by_id`, `library_caseversion` .`modified_on`, `library_caseversion`.`modified_by_id`, `library_caseversion` .`deleted_on`, `library_caseversion`.`deleted_by_id`, `library_caseversion` .`cc_version`, `library_caseversion`.`status`, `library_caseversion` .`productversion_id`, `library_caseversion`.`case_id`, `library_caseversion`.`name`, `library_caseversion`.`description`, `library_caseversion` .`latest`, `library_caseversion`.`envs_narrowed` FROM `library_caseversion` INNER JOIN `core_productversion` ON (`library_caseversion` .`productversion_id` = `core_productversion`.`id`) WHERE (`library_caseversion` .`deleted_on` IS NULL AND `library_caseversion`.`case_id` = 2 ) ORDER BY `library_caseversion`.`case_id` ASC, `core_productversion`.`order` ASC Query 19: Add the step to the second caseversion:: INSERT INTO `library_casestep` (`created_on`, `created_by_id`, `modified_on`, `modified_by_id`, `deleted_on`, `deleted_by_id`, `caseversion_id`, `number`, `instruction`, `expected`) VALUES (2012-03-07 19:35:34, None, 2012-03-07 19:35:34, None, None, None, 11, 1, do this, ) Transaction: RELEASE SAVEPOINT s140735243669888_x2 Note: Django 1.4 now logs transaction points in the connection.queries EXPECT: 19 Queries + 4 Transaction actions = 23 queries. To re-capture this query list, use a block like this in place of the "with self.assertNumQueries..." block:: from django.conf import settings from django.db import connection import json settings.DEBUG = True connection.queries = [] result = self.import_data(case_data) print(json.dumps(connection.queries, indent=4)) settings.DEBUG = False """ # need a user to exist, so the import can find it. user = self.F.UserFactory.create(email="sumbudee@mozilla.com") case_data = { "cases": [ { "created_by": "sumbudee@mozilla.com", "name": "Foo", "steps": [{"instruction": "do this"}], }, { "created_by": "sumbudee@mozilla.com", "name": "Bar", "steps": [{"instruction": "do this"}], } ] } # Test code as normal with self.assertNumQueries(23): result = self.import_data(case_data) cv1 = self.model.CaseVersion.objects.get(name="Foo") self.assertEqual(cv1.created_by, user) cv2 = self.model.CaseVersion.objects.get(name="Bar") self.assertEqual(cv2.created_by, user) self.assertEqual(result.num_cases, 2) def test_create_caseversion_no_existing_user(self): """A caseversion with a user that does not exist in the db.""" result = self.import_data( { "cases": [ { "created_by": "sumbudee@mozilla.com", "name": "Foo", "steps": [{"instruction": "do this"}], } ] } ) cv = self.model.CaseVersion.objects.get() self.assertEqual(cv.created_by, None) self.assertEqual(result.num_cases, 1) self.assertEqual( result.warnings[0]["reason"], ImportResult.WARN_USER_NOT_FOUND, ) def test_create_caseversion_existing_tag(self): """A caseversion that uses an existing product tag""" # need a tag to exist, so the import can find it. tag = self.model.Tag.objects.create( name="FooTag", product=self.pv.product, ) result = self.import_data( { "cases": [ { "name": "Foo", "steps": [{"instruction": "do this"}], "tags": ["FooTag"], } ] } ) cv = self.model.CaseVersion.objects.get() self.assertEqual(cv.tags.get(), tag) self.assertEqual(result.num_cases, 1) def test_create_caseversion_existing_tag_different_case(self): """A caseversion that uses an existing product tag with diff case""" # need a tag to exist, so the import can find it. tag = self.model.Tag.objects.create( name="footag", product=self.pv.product, ) result = self.import_data( { "cases": [ { "name": "Foo", "steps": [{"instruction": "do this"}], "tags": ["FooTag"], } ] } ) cv = self.model.CaseVersion.objects.get() self.assertEqual(cv.tags.get(), tag) self.assertEqual(result.num_cases, 1) def test_create_caseversion_existing_suite(self): """A case that uses an existing suite.""" # need a suite to exist, so the import can find it. suite = self.model.Suite.objects.create( name="FooSuite", product=self.pv.product, ) result = self.import_data({ "cases": [{ "name": "Foo", "steps": [{"instruction": "do this"}], "suites": ["FooSuite"], }] } ) cv = self.model.CaseVersion.objects.get() self.assertEqual(cv.case.suites.get(), suite) self.assertEqual(result.num_cases, 1) self.assertEqual(result.num_suites, 0) def test_create_caseversion_existing_suite_different_case(self): """A case that uses an existing suite with different case.""" # need a suite to exist, so the import can find it. suite = self.model.Suite.objects.create( name="foosuite", product=self.pv.product, ) result = self.import_data( { "cases": [ { "name": "Foo", "steps": [{"instruction": "do this"}], "suites": ["FooSuite"], } ] } ) cv = self.model.CaseVersion.objects.get() self.assertEqual(cv.case.suites.get(), suite) self.assertEqual(result.num_cases, 1) self.assertEqual(result.num_suites, 0) def test_case_no_name_skip(self): """A case with no name is skipped.""" result = self.import_data( { "cases": [ { "description": "Foo", } ] } ) self.assertFalse(list(self.model.CaseVersion.objects.all())) self.assertEqual(result.num_cases, 0) self.assertEqual( result.warnings[0]["reason"], ImportResult.SKIP_CASE_NO_NAME, ) def test_case_name_conflict_skip(self): """A case with same name already exists.""" self.F.CaseVersionFactory.create(productversion=self.pv, name="Foo") case_to_import = { "cases": [ { "name": "Foo", } ] } result = self.import_data(case_to_import) self.assertEqual(result.num_cases, 0) self.assertEqual( result.warnings[0]["reason"], ImportResult.SKIP_CASE_NAME_CONFLICT, ) def test_no_step_warning(self): """A case with no steps emits a warning.""" result = self.import_data( { "cases": [ { "name": "Foo", } ] } ) cv = self.model.CaseVersion.objects.get() self.assertEqual(cv.steps.count(), 0) self.assertEqual(result.num_cases, 1) self.assertEqual(result.warnings[0]["item"], cv) self.assertEqual( result.warnings[0]["reason"], ImportResult.WARN_NO_STEPS, ) def test_steps(self): """Steps are created with correct instruction and expected values.""" new_steps = [ { "instruction": "instr1", "expected": "exp1" }, { "instruction": "instr2", "expected": "exp2" }, { "instruction": "instr3", "expected": "exp3" }, ] self.import_data( { "cases": [ { "name": "Foo", "steps": new_steps, } ] } ) cv = self.model.CaseVersion.objects.get() self.assertEqual( [(s.number, s.instruction, s.expected) for s in cv.steps.order_by( "number")], [(i + 1, s["instruction"], s["expected"]) for i, s in enumerate( new_steps)], ) def test_create_suite(self): """Successful import creates a suite with expected values.""" self.import_data( { "suites": [ { "name": "Foo", "description": "indescribable" } ] } ) s = self.model.Suite.objects.get() self.assertEqual(s.description, "indescribable") self.assertEqual(s.name, "Foo") def test_suite_no_name_skip(self): """A suite with no name is skipped.""" result = self.import_data( { "suites": [ { "description": "Foo", } ] } ) self.assertFalse(self.model.Suite.objects.count(), 0) self.assertEqual(result.num_suites, 0) self.assertEqual( result.warnings[0]["reason"], ImportResult.SKIP_SUITE_NO_NAME, ) def test_result_object(self): """Successful import returns a result summary object.""" result = self.import_data( { "cases": [ { "name": "Foo", "steps": [{"instruction": "do this"}] } ] } ) result_list = result.get_as_list() self.assertTrue("Imported 1 cases" in result_list) self.assertTrue("Imported 0 suites" in result_list) class ImporterTransactionTest(ImporterTestBase, case.TransactionTestCase): """Tests for ``Importer`` transactional behavior.""" @patch.object(SuiteImporter, 'import_suites') def test_unknown_exception_rollback(self, new_import_suites): """ An unknown exception is thrown by the import_suites method of SuiteImporter, so the entire transaction is rolled back and no cases are imported. """ case_suite_data = { "suites": [ { "name": "FooSuite", "description": "indescribable" } ], "cases": [ { "name": "FooCase", "steps": [{"instruction": "do this"}] }, { "name": "BarCase", "steps": [{"instruction": "do this"}] } ] } class SurpriseException(RuntimeError): pass def raise_exception(): raise SurpriseException("Surprise!") new_import_suites.side_effect = raise_exception with self.assertRaises(SurpriseException): self.import_data(case_suite_data) self.assertEqual(self.model.Case.objects.count(), 0) self.assertEqual(self.model.CaseVersion.objects.count(), 0) # @@@ This test won't work till we upgrade to Django 1.4 def test_step_no_instruction_skip(self): """Skip import on case with step and no instruction.""" result = self.import_data( { "cases": [ { "name": "Foo", "steps": [{"expected": "did this"}] } ] } ) # @@@ The savepoint-rollback won't work until Django 1.4. # cv = self.model.CaseVersion.objects.all() # self.assertFalse(list(cv)) # self.assertEqual(result.num_cases, 0) self.assertEqual( result.warnings[0]["reason"], ImportResult.SKIP_STEP_NO_INSTRUCTION, )
bsd-2-clause
tmerrick1/spack
var/spack/repos/builtin/packages/perl-module-build/package.py
5
1940
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## # from spack import * class PerlModuleBuild(PerlPackage): """Module::Build is a system for building, testing, and installing Perl modules. It is meant to be an alternative to ExtUtils::MakeMaker. Developers may alter the behavior of the module through subclassing in a much more straightforward way than with MakeMaker. It also does not require a make on your system - most of the Module::Build code is pure-perl and written in a very cross-platform way. """ homepage = "http://search.cpan.org/perldoc/Module::Build" url = "http://search.cpan.org/CPAN/authors/id/L/LE/LEONT/Module-Build-0.4220.tar.gz" version('0.4220', '9df204e188462a4410d496f316c2c531')
lgpl-2.1
bryx-inc/boto
tests/integration/ec2containerservice/test_ec2containerservice.py
99
1749
# Copyright (c) 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved # # 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, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing 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 MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # import boto from boto.ec2containerservice.exceptions import ClientException from tests.compat import unittest class TestEC2ContainerService(unittest.TestCase): def setUp(self): self.ecs = boto.connect_ec2containerservice() def test_list_clusters(self): response = self.ecs.list_clusters() self.assertIn('clusterArns', response['ListClustersResponse']['ListClustersResult']) def test_handle_not_found_exception(self): with self.assertRaises(ClientException): # Try to stop a task with an invalid arn. self.ecs.stop_task(task='foo')
mit
Stillbot/stillbot-master
stillbot_master/brew_master/migrations/0001_initial.py
1
5383
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Wash' db.create_table(u'brew_master_wash', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('created_on', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2014, 10, 17, 0, 0))), ('starting_sg', self.gf('django.db.models.fields.DecimalField')(max_digits=4, decimal_places=2)), ('procedure', self.gf('django.db.models.fields.TextField')()), )) db.send_create_signal(u'brew_master', ['Wash']) # Adding M2M table for field ingredients on 'Wash' m2m_table_name = db.shorten_name(u'brew_master_wash_ingredients') db.create_table(m2m_table_name, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('wash', models.ForeignKey(orm[u'brew_master.wash'], null=False)), ('ingredientmeasurement', models.ForeignKey(orm[u'brew_master.ingredientmeasurement'], null=False)) )) db.create_unique(m2m_table_name, ['wash_id', 'ingredientmeasurement_id']) # Adding model 'IngredientMeasurement' db.create_table(u'brew_master_ingredientmeasurement', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('ingredient', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['brew_master.Ingredient'])), ('amount', self.gf('django.db.models.fields.IntegerField')()), ('measurement', self.gf('django.db.models.fields.CharField')(max_length=5)), )) db.send_create_signal(u'brew_master', ['IngredientMeasurement']) # Adding model 'Ingredient' db.create_table(u'brew_master_ingredient', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=255)), ('barcode', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)), ('description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), ('place_of_origin', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['brew_master.Place'], null=True, blank=True)), )) db.send_create_signal(u'brew_master', ['Ingredient']) # Adding model 'Place' db.create_table(u'brew_master_place', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), )) db.send_create_signal(u'brew_master', ['Place']) def backwards(self, orm): # Deleting model 'Wash' db.delete_table(u'brew_master_wash') # Removing M2M table for field ingredients on 'Wash' db.delete_table(db.shorten_name(u'brew_master_wash_ingredients')) # Deleting model 'IngredientMeasurement' db.delete_table(u'brew_master_ingredientmeasurement') # Deleting model 'Ingredient' db.delete_table(u'brew_master_ingredient') # Deleting model 'Place' db.delete_table(u'brew_master_place') models = { u'brew_master.ingredient': { 'Meta': {'object_name': 'Ingredient'}, 'barcode': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'place_of_origin': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['brew_master.Place']", 'null': 'True', 'blank': 'True'}) }, u'brew_master.ingredientmeasurement': { 'Meta': {'object_name': 'IngredientMeasurement'}, 'amount': ('django.db.models.fields.IntegerField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ingredient': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['brew_master.Ingredient']"}), 'measurement': ('django.db.models.fields.CharField', [], {'max_length': '5'}) }, u'brew_master.place': { 'Meta': {'object_name': 'Place'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, u'brew_master.wash': { 'Meta': {'object_name': 'Wash'}, 'created_on': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 10, 17, 0, 0)'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ingredients': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['brew_master.IngredientMeasurement']", 'null': 'True', 'blank': 'True'}), 'procedure': ('django.db.models.fields.TextField', [], {}), 'starting_sg': ('django.db.models.fields.DecimalField', [], {'max_digits': '4', 'decimal_places': '2'}) } } complete_apps = ['brew_master']
mit
feardax/namebench
nb_third_party/jinja2/compiler.py
199
61044
# -*- coding: utf-8 -*- """ jinja2.compiler ~~~~~~~~~~~~~~~ Compiles nodes into python code. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ from cStringIO import StringIO from itertools import chain from copy import deepcopy from jinja2 import nodes from jinja2.nodes import EvalContext from jinja2.visitor import NodeVisitor, NodeTransformer from jinja2.exceptions import TemplateAssertionError from jinja2.utils import Markup, concat, escape, is_python_keyword, next operators = { 'eq': '==', 'ne': '!=', 'gt': '>', 'gteq': '>=', 'lt': '<', 'lteq': '<=', 'in': 'in', 'notin': 'not in' } try: exec '(0 if 0 else 0)' except SyntaxError: have_condexpr = False else: have_condexpr = True # what method to iterate over items do we want to use for dict iteration # in generated code? on 2.x let's go with iteritems, on 3.x with items if hasattr(dict, 'iteritems'): dict_item_iter = 'iteritems' else: dict_item_iter = 'items' # does if 0: dummy(x) get us x into the scope? def unoptimize_before_dead_code(): x = 42 def f(): if 0: dummy(x) return f unoptimize_before_dead_code = bool(unoptimize_before_dead_code().func_closure) def generate(node, environment, name, filename, stream=None, defer_init=False): """Generate the python source for a node tree.""" if not isinstance(node, nodes.Template): raise TypeError('Can\'t compile non template nodes') generator = CodeGenerator(environment, name, filename, stream, defer_init) generator.visit(node) if stream is None: return generator.stream.getvalue() def has_safe_repr(value): """Does the node have a safe representation?""" if value is None or value is NotImplemented or value is Ellipsis: return True if isinstance(value, (bool, int, long, float, complex, basestring, xrange, Markup)): return True if isinstance(value, (tuple, list, set, frozenset)): for item in value: if not has_safe_repr(item): return False return True elif isinstance(value, dict): for key, value in value.iteritems(): if not has_safe_repr(key): return False if not has_safe_repr(value): return False return True return False def find_undeclared(nodes, names): """Check if the names passed are accessed undeclared. The return value is a set of all the undeclared names from the sequence of names found. """ visitor = UndeclaredNameVisitor(names) try: for node in nodes: visitor.visit(node) except VisitorExit: pass return visitor.undeclared class Identifiers(object): """Tracks the status of identifiers in frames.""" def __init__(self): # variables that are known to be declared (probably from outer # frames or because they are special for the frame) self.declared = set() # undeclared variables from outer scopes self.outer_undeclared = set() # names that are accessed without being explicitly declared by # this one or any of the outer scopes. Names can appear both in # declared and undeclared. self.undeclared = set() # names that are declared locally self.declared_locally = set() # names that are declared by parameters self.declared_parameter = set() def add_special(self, name): """Register a special name like `loop`.""" self.undeclared.discard(name) self.declared.add(name) def is_declared(self, name, local_only=False): """Check if a name is declared in this or an outer scope.""" if name in self.declared_locally or name in self.declared_parameter: return True if local_only: return False return name in self.declared def copy(self): return deepcopy(self) class Frame(object): """Holds compile time information for us.""" def __init__(self, eval_ctx, parent=None): self.eval_ctx = eval_ctx self.identifiers = Identifiers() # a toplevel frame is the root + soft frames such as if conditions. self.toplevel = False # the root frame is basically just the outermost frame, so no if # conditions. This information is used to optimize inheritance # situations. self.rootlevel = False # in some dynamic inheritance situations the compiler needs to add # write tests around output statements. self.require_output_check = parent and parent.require_output_check # inside some tags we are using a buffer rather than yield statements. # this for example affects {% filter %} or {% macro %}. If a frame # is buffered this variable points to the name of the list used as # buffer. self.buffer = None # the name of the block we're in, otherwise None. self.block = parent and parent.block or None # a set of actually assigned names self.assigned_names = set() # the parent of this frame self.parent = parent if parent is not None: self.identifiers.declared.update( parent.identifiers.declared | parent.identifiers.declared_parameter | parent.assigned_names ) self.identifiers.outer_undeclared.update( parent.identifiers.undeclared - self.identifiers.declared ) self.buffer = parent.buffer def copy(self): """Create a copy of the current one.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.identifiers = object.__new__(self.identifiers.__class__) rv.identifiers.__dict__.update(self.identifiers.__dict__) return rv def inspect(self, nodes, hard_scope=False): """Walk the node and check for identifiers. If the scope is hard (eg: enforce on a python level) overrides from outer scopes are tracked differently. """ visitor = FrameIdentifierVisitor(self.identifiers, hard_scope) for node in nodes: visitor.visit(node) def find_shadowed(self, extra=()): """Find all the shadowed names. extra is an iterable of variables that may be defined with `add_special` which may occour scoped. """ i = self.identifiers return (i.declared | i.outer_undeclared) & \ (i.declared_locally | i.declared_parameter) | \ set(x for x in extra if i.is_declared(x)) def inner(self): """Return an inner frame.""" return Frame(self.eval_ctx, self) def soft(self): """Return a soft frame. A soft frame may not be modified as standalone thing as it shares the resources with the frame it was created of, but it's not a rootlevel frame any longer. """ rv = self.copy() rv.rootlevel = False return rv __copy__ = copy class VisitorExit(RuntimeError): """Exception used by the `UndeclaredNameVisitor` to signal a stop.""" class DependencyFinderVisitor(NodeVisitor): """A visitor that collects filter and test calls.""" def __init__(self): self.filters = set() self.tests = set() def visit_Filter(self, node): self.generic_visit(node) self.filters.add(node.name) def visit_Test(self, node): self.generic_visit(node) self.tests.add(node.name) def visit_Block(self, node): """Stop visiting at blocks.""" class UndeclaredNameVisitor(NodeVisitor): """A visitor that checks if a name is accessed without being declared. This is different from the frame visitor as it will not stop at closure frames. """ def __init__(self, names): self.names = set(names) self.undeclared = set() def visit_Name(self, node): if node.ctx == 'load' and node.name in self.names: self.undeclared.add(node.name) if self.undeclared == self.names: raise VisitorExit() else: self.names.discard(node.name) def visit_Block(self, node): """Stop visiting a blocks.""" class FrameIdentifierVisitor(NodeVisitor): """A visitor for `Frame.inspect`.""" def __init__(self, identifiers, hard_scope): self.identifiers = identifiers self.hard_scope = hard_scope def visit_Name(self, node): """All assignments to names go through this function.""" if node.ctx == 'store': self.identifiers.declared_locally.add(node.name) elif node.ctx == 'param': self.identifiers.declared_parameter.add(node.name) elif node.ctx == 'load' and not \ self.identifiers.is_declared(node.name, self.hard_scope): self.identifiers.undeclared.add(node.name) def visit_If(self, node): self.visit(node.test) real_identifiers = self.identifiers old_names = real_identifiers.declared_locally | \ real_identifiers.declared_parameter def inner_visit(nodes): if not nodes: return set() self.identifiers = real_identifiers.copy() for subnode in nodes: self.visit(subnode) rv = self.identifiers.declared_locally - old_names # we have to remember the undeclared variables of this branch # because we will have to pull them. real_identifiers.undeclared.update(self.identifiers.undeclared) self.identifiers = real_identifiers return rv body = inner_visit(node.body) else_ = inner_visit(node.else_ or ()) # the differences between the two branches are also pulled as # undeclared variables real_identifiers.undeclared.update(body.symmetric_difference(else_) - real_identifiers.declared) # remember those that are declared. real_identifiers.declared_locally.update(body | else_) def visit_Macro(self, node): self.identifiers.declared_locally.add(node.name) def visit_Import(self, node): self.generic_visit(node) self.identifiers.declared_locally.add(node.target) def visit_FromImport(self, node): self.generic_visit(node) for name in node.names: if isinstance(name, tuple): self.identifiers.declared_locally.add(name[1]) else: self.identifiers.declared_locally.add(name) def visit_Assign(self, node): """Visit assignments in the correct order.""" self.visit(node.node) self.visit(node.target) def visit_For(self, node): """Visiting stops at for blocks. However the block sequence is visited as part of the outer scope. """ self.visit(node.iter) def visit_CallBlock(self, node): self.visit(node.call) def visit_FilterBlock(self, node): self.visit(node.filter) def visit_Scope(self, node): """Stop visiting at scopes.""" def visit_Block(self, node): """Stop visiting at blocks.""" class CompilerExit(Exception): """Raised if the compiler encountered a situation where it just doesn't make sense to further process the code. Any block that raises such an exception is not further processed. """ class CodeGenerator(NodeVisitor): def __init__(self, environment, name, filename, stream=None, defer_init=False): if stream is None: stream = StringIO() self.environment = environment self.name = name self.filename = filename self.stream = stream self.created_block_context = False self.defer_init = defer_init # aliases for imports self.import_aliases = {} # a registry for all blocks. Because blocks are moved out # into the global python scope they are registered here self.blocks = {} # the number of extends statements so far self.extends_so_far = 0 # some templates have a rootlevel extends. In this case we # can safely assume that we're a child template and do some # more optimizations. self.has_known_extends = False # the current line number self.code_lineno = 1 # registry of all filters and tests (global, not block local) self.tests = {} self.filters = {} # the debug information self.debug_info = [] self._write_debug_info = None # the number of new lines before the next write() self._new_lines = 0 # the line number of the last written statement self._last_line = 0 # true if nothing was written so far. self._first_write = True # used by the `temporary_identifier` method to get new # unique, temporary identifier self._last_identifier = 0 # the current indentation self._indentation = 0 # -- Various compilation helpers def fail(self, msg, lineno): """Fail with a :exc:`TemplateAssertionError`.""" raise TemplateAssertionError(msg, lineno, self.name, self.filename) def temporary_identifier(self): """Get a new unique identifier.""" self._last_identifier += 1 return 't_%d' % self._last_identifier def buffer(self, frame): """Enable buffering for the frame from that point onwards.""" frame.buffer = self.temporary_identifier() self.writeline('%s = []' % frame.buffer) def return_buffer_contents(self, frame): """Return the buffer contents of the frame.""" if frame.eval_ctx.volatile: self.writeline('if context.eval_ctx.autoescape:') self.indent() self.writeline('return Markup(concat(%s))' % frame.buffer) self.outdent() self.writeline('else:') self.indent() self.writeline('return concat(%s)' % frame.buffer) self.outdent() elif frame.eval_ctx.autoescape: self.writeline('return Markup(concat(%s))' % frame.buffer) else: self.writeline('return concat(%s)' % frame.buffer) def indent(self): """Indent by one.""" self._indentation += 1 def outdent(self, step=1): """Outdent by step.""" self._indentation -= step def start_write(self, frame, node=None): """Yield or write into the frame buffer.""" if frame.buffer is None: self.writeline('yield ', node) else: self.writeline('%s.append(' % frame.buffer, node) def end_write(self, frame): """End the writing process started by `start_write`.""" if frame.buffer is not None: self.write(')') def simple_write(self, s, frame, node=None): """Simple shortcut for start_write + write + end_write.""" self.start_write(frame, node) self.write(s) self.end_write(frame) def blockvisit(self, nodes, frame): """Visit a list of nodes as block in a frame. If the current frame is no buffer a dummy ``if 0: yield None`` is written automatically unless the force_generator parameter is set to False. """ if frame.buffer is None: self.writeline('if 0: yield None') else: self.writeline('pass') try: for node in nodes: self.visit(node, frame) except CompilerExit: pass def write(self, x): """Write a string into the output stream.""" if self._new_lines: if not self._first_write: self.stream.write('\n' * self._new_lines) self.code_lineno += self._new_lines if self._write_debug_info is not None: self.debug_info.append((self._write_debug_info, self.code_lineno)) self._write_debug_info = None self._first_write = False self.stream.write(' ' * self._indentation) self._new_lines = 0 self.stream.write(x) def writeline(self, x, node=None, extra=0): """Combination of newline and write.""" self.newline(node, extra) self.write(x) def newline(self, node=None, extra=0): """Add one or more newlines before the next write.""" self._new_lines = max(self._new_lines, 1 + extra) if node is not None and node.lineno != self._last_line: self._write_debug_info = node.lineno self._last_line = node.lineno def signature(self, node, frame, extra_kwargs=None): """Writes a function call to the stream for the current node. A leading comma is added automatically. The extra keyword arguments may not include python keywords otherwise a syntax error could occour. The extra keyword arguments should be given as python dict. """ # if any of the given keyword arguments is a python keyword # we have to make sure that no invalid call is created. kwarg_workaround = False for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()): if is_python_keyword(kwarg): kwarg_workaround = True break for arg in node.args: self.write(', ') self.visit(arg, frame) if not kwarg_workaround: for kwarg in node.kwargs: self.write(', ') self.visit(kwarg, frame) if extra_kwargs is not None: for key, value in extra_kwargs.iteritems(): self.write(', %s=%s' % (key, value)) if node.dyn_args: self.write(', *') self.visit(node.dyn_args, frame) if kwarg_workaround: if node.dyn_kwargs is not None: self.write(', **dict({') else: self.write(', **{') for kwarg in node.kwargs: self.write('%r: ' % kwarg.key) self.visit(kwarg.value, frame) self.write(', ') if extra_kwargs is not None: for key, value in extra_kwargs.iteritems(): self.write('%r: %s, ' % (key, value)) if node.dyn_kwargs is not None: self.write('}, **') self.visit(node.dyn_kwargs, frame) self.write(')') else: self.write('}') elif node.dyn_kwargs is not None: self.write(', **') self.visit(node.dyn_kwargs, frame) def pull_locals(self, frame): """Pull all the references identifiers into the local scope.""" for name in frame.identifiers.undeclared: self.writeline('l_%s = context.resolve(%r)' % (name, name)) def pull_dependencies(self, nodes): """Pull all the dependencies.""" visitor = DependencyFinderVisitor() for node in nodes: visitor.visit(node) for dependency in 'filters', 'tests': mapping = getattr(self, dependency) for name in getattr(visitor, dependency): if name not in mapping: mapping[name] = self.temporary_identifier() self.writeline('%s = environment.%s[%r]' % (mapping[name], dependency, name)) def unoptimize_scope(self, frame): """Disable Python optimizations for the frame.""" # XXX: this is not that nice but it has no real overhead. It # mainly works because python finds the locals before dead code # is removed. If that breaks we have to add a dummy function # that just accepts the arguments and does nothing. if frame.identifiers.declared: self.writeline('%sdummy(%s)' % ( unoptimize_before_dead_code and 'if 0: ' or '', ', '.join('l_' + name for name in frame.identifiers.declared) )) def push_scope(self, frame, extra_vars=()): """This function returns all the shadowed variables in a dict in the form name: alias and will write the required assignments into the current scope. No indentation takes place. This also predefines locally declared variables from the loop body because under some circumstances it may be the case that `extra_vars` is passed to `Frame.find_shadowed`. """ aliases = {} for name in frame.find_shadowed(extra_vars): aliases[name] = ident = self.temporary_identifier() self.writeline('%s = l_%s' % (ident, name)) to_declare = set() for name in frame.identifiers.declared_locally: if name not in aliases: to_declare.add('l_' + name) if to_declare: self.writeline(' = '.join(to_declare) + ' = missing') return aliases def pop_scope(self, aliases, frame): """Restore all aliases and delete unused variables.""" for name, alias in aliases.iteritems(): self.writeline('l_%s = %s' % (name, alias)) to_delete = set() for name in frame.identifiers.declared_locally: if name not in aliases: to_delete.add('l_' + name) if to_delete: # we cannot use the del statement here because enclosed # scopes can trigger a SyntaxError: # a = 42; b = lambda: a; del a self.writeline(' = '.join(to_delete) + ' = missing') def function_scoping(self, node, frame, children=None, find_special=True): """In Jinja a few statements require the help of anonymous functions. Those are currently macros and call blocks and in the future also recursive loops. As there is currently technical limitation that doesn't allow reading and writing a variable in a scope where the initial value is coming from an outer scope, this function tries to fall back with a common error message. Additionally the frame passed is modified so that the argumetns are collected and callers are looked up. This will return the modified frame. """ # we have to iterate twice over it, make sure that works if children is None: children = node.iter_child_nodes() children = list(children) func_frame = frame.inner() func_frame.inspect(children, hard_scope=True) # variables that are undeclared (accessed before declaration) and # declared locally *and* part of an outside scope raise a template # assertion error. Reason: we can't generate reasonable code from # it without aliasing all the variables. # this could be fixed in Python 3 where we have the nonlocal # keyword or if we switch to bytecode generation overriden_closure_vars = ( func_frame.identifiers.undeclared & func_frame.identifiers.declared & (func_frame.identifiers.declared_locally | func_frame.identifiers.declared_parameter) ) if overriden_closure_vars: self.fail('It\'s not possible to set and access variables ' 'derived from an outer scope! (affects: %s)' % ', '.join(sorted(overriden_closure_vars)), node.lineno) # remove variables from a closure from the frame's undeclared # identifiers. func_frame.identifiers.undeclared -= ( func_frame.identifiers.undeclared & func_frame.identifiers.declared ) # no special variables for this scope, abort early if not find_special: return func_frame func_frame.accesses_kwargs = False func_frame.accesses_varargs = False func_frame.accesses_caller = False func_frame.arguments = args = ['l_' + x.name for x in node.args] undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs')) if 'caller' in undeclared: func_frame.accesses_caller = True func_frame.identifiers.add_special('caller') args.append('l_caller') if 'kwargs' in undeclared: func_frame.accesses_kwargs = True func_frame.identifiers.add_special('kwargs') args.append('l_kwargs') if 'varargs' in undeclared: func_frame.accesses_varargs = True func_frame.identifiers.add_special('varargs') args.append('l_varargs') return func_frame def macro_body(self, node, frame, children=None): """Dump the function def of a macro or call block.""" frame = self.function_scoping(node, frame, children) # macros are delayed, they never require output checks frame.require_output_check = False args = frame.arguments # XXX: this is an ugly fix for the loop nesting bug # (tests.test_old_bugs.test_loop_call_bug). This works around # a identifier nesting problem we have in general. It's just more # likely to happen in loops which is why we work around it. The # real solution would be "nonlocal" all the identifiers that are # leaking into a new python frame and might be used both unassigned # and assigned. if 'loop' in frame.identifiers.declared: args = args + ['l_loop=l_loop'] self.writeline('def macro(%s):' % ', '.join(args), node) self.indent() self.buffer(frame) self.pull_locals(frame) self.blockvisit(node.body, frame) self.return_buffer_contents(frame) self.outdent() return frame def macro_def(self, node, frame): """Dump the macro definition for the def created by macro_body.""" arg_tuple = ', '.join(repr(x.name) for x in node.args) name = getattr(node, 'name', None) if len(node.args) == 1: arg_tuple += ',' self.write('Macro(environment, macro, %r, (%s), (' % (name, arg_tuple)) for arg in node.defaults: self.visit(arg, frame) self.write(', ') self.write('), %r, %r, %r)' % ( bool(frame.accesses_kwargs), bool(frame.accesses_varargs), bool(frame.accesses_caller) )) def position(self, node): """Return a human readable position for the node.""" rv = 'line %d' % node.lineno if self.name is not None: rv += ' in ' + repr(self.name) return rv # -- Statement Visitors def visit_Template(self, node, frame=None): assert frame is None, 'no root frame allowed' eval_ctx = EvalContext(self.environment, self.name) from jinja2.runtime import __all__ as exported self.writeline('from __future__ import division') self.writeline('from jinja2.runtime import ' + ', '.join(exported)) if not unoptimize_before_dead_code: self.writeline('dummy = lambda *x: None') # if we want a deferred initialization we cannot move the # environment into a local name envenv = not self.defer_init and ', environment=environment' or '' # do we have an extends tag at all? If not, we can save some # overhead by just not processing any inheritance code. have_extends = node.find(nodes.Extends) is not None # find all blocks for block in node.find_all(nodes.Block): if block.name in self.blocks: self.fail('block %r defined twice' % block.name, block.lineno) self.blocks[block.name] = block # find all imports and import them for import_ in node.find_all(nodes.ImportedName): if import_.importname not in self.import_aliases: imp = import_.importname self.import_aliases[imp] = alias = self.temporary_identifier() if '.' in imp: module, obj = imp.rsplit('.', 1) self.writeline('from %s import %s as %s' % (module, obj, alias)) else: self.writeline('import %s as %s' % (imp, alias)) # add the load name self.writeline('name = %r' % self.name) # generate the root render function. self.writeline('def root(context%s):' % envenv, extra=1) # process the root frame = Frame(eval_ctx) frame.inspect(node.body) frame.toplevel = frame.rootlevel = True frame.require_output_check = have_extends and not self.has_known_extends self.indent() if have_extends: self.writeline('parent_template = None') if 'self' in find_undeclared(node.body, ('self',)): frame.identifiers.add_special('self') self.writeline('l_self = TemplateReference(context)') self.pull_locals(frame) self.pull_dependencies(node.body) self.blockvisit(node.body, frame) self.outdent() # make sure that the parent root is called. if have_extends: if not self.has_known_extends: self.indent() self.writeline('if parent_template is not None:') self.indent() self.writeline('for event in parent_template.' 'root_render_func(context):') self.indent() self.writeline('yield event') self.outdent(2 + (not self.has_known_extends)) # at this point we now have the blocks collected and can visit them too. for name, block in self.blocks.iteritems(): block_frame = Frame(eval_ctx) block_frame.inspect(block.body) block_frame.block = name self.writeline('def block_%s(context%s):' % (name, envenv), block, 1) self.indent() undeclared = find_undeclared(block.body, ('self', 'super')) if 'self' in undeclared: block_frame.identifiers.add_special('self') self.writeline('l_self = TemplateReference(context)') if 'super' in undeclared: block_frame.identifiers.add_special('super') self.writeline('l_super = context.super(%r, ' 'block_%s)' % (name, name)) self.pull_locals(block_frame) self.pull_dependencies(block.body) self.blockvisit(block.body, block_frame) self.outdent() self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x) for x in self.blocks), extra=1) # add a function that returns the debug info self.writeline('debug_info = %r' % '&'.join('%s=%s' % x for x in self.debug_info)) def visit_Block(self, node, frame): """Call a block and register it for the template.""" level = 1 if frame.toplevel: # if we know that we are a child template, there is no need to # check if we are one if self.has_known_extends: return if self.extends_so_far > 0: self.writeline('if parent_template is None:') self.indent() level += 1 context = node.scoped and 'context.derived(locals())' or 'context' self.writeline('for event in context.blocks[%r][0](%s):' % ( node.name, context), node) self.indent() self.simple_write('event', frame) self.outdent(level) def visit_Extends(self, node, frame): """Calls the extender.""" if not frame.toplevel: self.fail('cannot use extend from a non top-level scope', node.lineno) # if the number of extends statements in general is zero so # far, we don't have to add a check if something extended # the template before this one. if self.extends_so_far > 0: # if we have a known extends we just add a template runtime # error into the generated code. We could catch that at compile # time too, but i welcome it not to confuse users by throwing the # same error at different times just "because we can". if not self.has_known_extends: self.writeline('if parent_template is not None:') self.indent() self.writeline('raise TemplateRuntimeError(%r)' % 'extended multiple times') self.outdent() # if we have a known extends already we don't need that code here # as we know that the template execution will end here. if self.has_known_extends: raise CompilerExit() self.writeline('parent_template = environment.get_template(', node) self.visit(node.template, frame) self.write(', %r)' % self.name) self.writeline('for name, parent_block in parent_template.' 'blocks.%s():' % dict_item_iter) self.indent() self.writeline('context.blocks.setdefault(name, []).' 'append(parent_block)') self.outdent() # if this extends statement was in the root level we can take # advantage of that information and simplify the generated code # in the top level from this point onwards if frame.rootlevel: self.has_known_extends = True # and now we have one more self.extends_so_far += 1 def visit_Include(self, node, frame): """Handles includes.""" if node.with_context: self.unoptimize_scope(frame) if node.ignore_missing: self.writeline('try:') self.indent() func_name = 'get_or_select_template' if isinstance(node.template, nodes.Const): if isinstance(node.template.value, basestring): func_name = 'get_template' elif isinstance(node.template.value, (tuple, list)): func_name = 'select_template' elif isinstance(node.template, (nodes.Tuple, nodes.List)): func_name = 'select_template' self.writeline('template = environment.%s(' % func_name, node) self.visit(node.template, frame) self.write(', %r)' % self.name) if node.ignore_missing: self.outdent() self.writeline('except TemplateNotFound:') self.indent() self.writeline('pass') self.outdent() self.writeline('else:') self.indent() if node.with_context: self.writeline('for event in template.root_render_func(' 'template.new_context(context.parent, True, ' 'locals())):') else: self.writeline('for event in template.module._body_stream:') self.indent() self.simple_write('event', frame) self.outdent() if node.ignore_missing: self.outdent() def visit_Import(self, node, frame): """Visit regular imports.""" if node.with_context: self.unoptimize_scope(frame) self.writeline('l_%s = ' % node.target, node) if frame.toplevel: self.write('context.vars[%r] = ' % node.target) self.write('environment.get_template(') self.visit(node.template, frame) self.write(', %r).' % self.name) if node.with_context: self.write('make_module(context.parent, True, locals())') else: self.write('module') if frame.toplevel and not node.target.startswith('_'): self.writeline('context.exported_vars.discard(%r)' % node.target) frame.assigned_names.add(node.target) def visit_FromImport(self, node, frame): """Visit named imports.""" self.newline(node) self.write('included_template = environment.get_template(') self.visit(node.template, frame) self.write(', %r).' % self.name) if node.with_context: self.write('make_module(context.parent, True)') else: self.write('module') var_names = [] discarded_names = [] for name in node.names: if isinstance(name, tuple): name, alias = name else: alias = name self.writeline('l_%s = getattr(included_template, ' '%r, missing)' % (alias, name)) self.writeline('if l_%s is missing:' % alias) self.indent() self.writeline('l_%s = environment.undefined(%r %% ' 'included_template.__name__, ' 'name=%r)' % (alias, 'the template %%r (imported on %s) does ' 'not export the requested name %s' % ( self.position(node), repr(name) ), name)) self.outdent() if frame.toplevel: var_names.append(alias) if not alias.startswith('_'): discarded_names.append(alias) frame.assigned_names.add(alias) if var_names: if len(var_names) == 1: name = var_names[0] self.writeline('context.vars[%r] = l_%s' % (name, name)) else: self.writeline('context.vars.update({%s})' % ', '.join( '%r: l_%s' % (name, name) for name in var_names )) if discarded_names: if len(discarded_names) == 1: self.writeline('context.exported_vars.discard(%r)' % discarded_names[0]) else: self.writeline('context.exported_vars.difference_' 'update((%s))' % ', '.join(map(repr, discarded_names))) def visit_For(self, node, frame): # when calculating the nodes for the inner frame we have to exclude # the iterator contents from it children = node.iter_child_nodes(exclude=('iter',)) if node.recursive: loop_frame = self.function_scoping(node, frame, children, find_special=False) else: loop_frame = frame.inner() loop_frame.inspect(children) # try to figure out if we have an extended loop. An extended loop # is necessary if the loop is in recursive mode if the special loop # variable is accessed in the body. extended_loop = node.recursive or 'loop' in \ find_undeclared(node.iter_child_nodes( only=('body',)), ('loop',)) # if we don't have an recursive loop we have to find the shadowed # variables at that point. Because loops can be nested but the loop # variable is a special one we have to enforce aliasing for it. if not node.recursive: aliases = self.push_scope(loop_frame, ('loop',)) # otherwise we set up a buffer and add a function def else: self.writeline('def loop(reciter, loop_render_func):', node) self.indent() self.buffer(loop_frame) aliases = {} # make sure the loop variable is a special one and raise a template # assertion error if a loop tries to write to loop if extended_loop: loop_frame.identifiers.add_special('loop') for name in node.find_all(nodes.Name): if name.ctx == 'store' and name.name == 'loop': self.fail('Can\'t assign to special loop variable ' 'in for-loop target', name.lineno) self.pull_locals(loop_frame) if node.else_: iteration_indicator = self.temporary_identifier() self.writeline('%s = 1' % iteration_indicator) # Create a fake parent loop if the else or test section of a # loop is accessing the special loop variable and no parent loop # exists. if 'loop' not in aliases and 'loop' in find_undeclared( node.iter_child_nodes(only=('else_', 'test')), ('loop',)): self.writeline("l_loop = environment.undefined(%r, name='loop')" % ("'loop' is undefined. the filter section of a loop as well " "as the else block doesn't have access to the special 'loop'" " variable of the current loop. Because there is no parent " "loop it's undefined. Happened in loop on %s" % self.position(node))) self.writeline('for ', node) self.visit(node.target, loop_frame) self.write(extended_loop and ', l_loop in LoopContext(' or ' in ') # if we have an extened loop and a node test, we filter in the # "outer frame". if extended_loop and node.test is not None: self.write('(') self.visit(node.target, loop_frame) self.write(' for ') self.visit(node.target, loop_frame) self.write(' in ') if node.recursive: self.write('reciter') else: self.visit(node.iter, loop_frame) self.write(' if (') test_frame = loop_frame.copy() self.visit(node.test, test_frame) self.write('))') elif node.recursive: self.write('reciter') else: self.visit(node.iter, loop_frame) if node.recursive: self.write(', recurse=loop_render_func):') else: self.write(extended_loop and '):' or ':') # tests in not extended loops become a continue if not extended_loop and node.test is not None: self.indent() self.writeline('if not ') self.visit(node.test, loop_frame) self.write(':') self.indent() self.writeline('continue') self.outdent(2) self.indent() self.blockvisit(node.body, loop_frame) if node.else_: self.writeline('%s = 0' % iteration_indicator) self.outdent() if node.else_: self.writeline('if %s:' % iteration_indicator) self.indent() self.blockvisit(node.else_, loop_frame) self.outdent() # reset the aliases if there are any. if not node.recursive: self.pop_scope(aliases, loop_frame) # if the node was recursive we have to return the buffer contents # and start the iteration code if node.recursive: self.return_buffer_contents(loop_frame) self.outdent() self.start_write(frame, node) self.write('loop(') self.visit(node.iter, frame) self.write(', loop)') self.end_write(frame) def visit_If(self, node, frame): if_frame = frame.soft() self.writeline('if ', node) self.visit(node.test, if_frame) self.write(':') self.indent() self.blockvisit(node.body, if_frame) self.outdent() if node.else_: self.writeline('else:') self.indent() self.blockvisit(node.else_, if_frame) self.outdent() def visit_Macro(self, node, frame): macro_frame = self.macro_body(node, frame) self.newline() if frame.toplevel: if not node.name.startswith('_'): self.write('context.exported_vars.add(%r)' % node.name) self.writeline('context.vars[%r] = ' % node.name) self.write('l_%s = ' % node.name) self.macro_def(node, macro_frame) frame.assigned_names.add(node.name) def visit_CallBlock(self, node, frame): children = node.iter_child_nodes(exclude=('call',)) call_frame = self.macro_body(node, frame, children) self.writeline('caller = ') self.macro_def(node, call_frame) self.start_write(frame, node) self.visit_Call(node.call, call_frame, forward_caller=True) self.end_write(frame) def visit_FilterBlock(self, node, frame): filter_frame = frame.inner() filter_frame.inspect(node.iter_child_nodes()) aliases = self.push_scope(filter_frame) self.pull_locals(filter_frame) self.buffer(filter_frame) self.blockvisit(node.body, filter_frame) self.start_write(frame, node) self.visit_Filter(node.filter, filter_frame) self.end_write(frame) self.pop_scope(aliases, filter_frame) def visit_ExprStmt(self, node, frame): self.newline(node) self.visit(node.node, frame) def visit_Output(self, node, frame): # if we have a known extends statement, we don't output anything # if we are in a require_output_check section if self.has_known_extends and frame.require_output_check: return if self.environment.finalize: finalize = lambda x: unicode(self.environment.finalize(x)) else: finalize = unicode self.newline(node) # if we are inside a frame that requires output checking, we do so outdent_later = False if frame.require_output_check: self.writeline('if parent_template is None:') self.indent() outdent_later = True # try to evaluate as many chunks as possible into a static # string at compile time. body = [] for child in node.nodes: try: const = child.as_const(frame.eval_ctx) except nodes.Impossible: body.append(child) continue # the frame can't be volatile here, becaus otherwise the # as_const() function would raise an Impossible exception # at that point. try: if frame.eval_ctx.autoescape: if hasattr(const, '__html__'): const = const.__html__() else: const = escape(const) const = finalize(const) except: # if something goes wrong here we evaluate the node # at runtime for easier debugging body.append(child) continue if body and isinstance(body[-1], list): body[-1].append(const) else: body.append([const]) # if we have less than 3 nodes or a buffer we yield or extend/append if len(body) < 3 or frame.buffer is not None: if frame.buffer is not None: # for one item we append, for more we extend if len(body) == 1: self.writeline('%s.append(' % frame.buffer) else: self.writeline('%s.extend((' % frame.buffer) self.indent() for item in body: if isinstance(item, list): val = repr(concat(item)) if frame.buffer is None: self.writeline('yield ' + val) else: self.writeline(val + ', ') else: if frame.buffer is None: self.writeline('yield ', item) else: self.newline(item) close = 1 if frame.eval_ctx.volatile: self.write('(context.eval_ctx.autoescape and' ' escape or to_string)(') elif frame.eval_ctx.autoescape: self.write('escape(') else: self.write('to_string(') if self.environment.finalize is not None: self.write('environment.finalize(') close += 1 self.visit(item, frame) self.write(')' * close) if frame.buffer is not None: self.write(', ') if frame.buffer is not None: # close the open parentheses self.outdent() self.writeline(len(body) == 1 and ')' or '))') # otherwise we create a format string as this is faster in that case else: format = [] arguments = [] for item in body: if isinstance(item, list): format.append(concat(item).replace('%', '%%')) else: format.append('%s') arguments.append(item) self.writeline('yield ') self.write(repr(concat(format)) + ' % (') idx = -1 self.indent() for argument in arguments: self.newline(argument) close = 0 if frame.eval_ctx.volatile: self.write('(context.eval_ctx.autoescape and' ' escape or to_string)(') close += 1 elif frame.eval_ctx.autoescape: self.write('escape(') close += 1 if self.environment.finalize is not None: self.write('environment.finalize(') close += 1 self.visit(argument, frame) self.write(')' * close + ', ') self.outdent() self.writeline(')') if outdent_later: self.outdent() def visit_Assign(self, node, frame): self.newline(node) # toplevel assignments however go into the local namespace and # the current template's context. We create a copy of the frame # here and add a set so that the Name visitor can add the assigned # names here. if frame.toplevel: assignment_frame = frame.copy() assignment_frame.toplevel_assignments = set() else: assignment_frame = frame self.visit(node.target, assignment_frame) self.write(' = ') self.visit(node.node, frame) # make sure toplevel assignments are added to the context. if frame.toplevel: public_names = [x for x in assignment_frame.toplevel_assignments if not x.startswith('_')] if len(assignment_frame.toplevel_assignments) == 1: name = next(iter(assignment_frame.toplevel_assignments)) self.writeline('context.vars[%r] = l_%s' % (name, name)) else: self.writeline('context.vars.update({') for idx, name in enumerate(assignment_frame.toplevel_assignments): if idx: self.write(', ') self.write('%r: l_%s' % (name, name)) self.write('})') if public_names: if len(public_names) == 1: self.writeline('context.exported_vars.add(%r)' % public_names[0]) else: self.writeline('context.exported_vars.update((%s))' % ', '.join(map(repr, public_names))) # -- Expression Visitors def visit_Name(self, node, frame): if node.ctx == 'store' and frame.toplevel: frame.toplevel_assignments.add(node.name) self.write('l_' + node.name) frame.assigned_names.add(node.name) def visit_Const(self, node, frame): val = node.value if isinstance(val, float): self.write(str(val)) else: self.write(repr(val)) def visit_TemplateData(self, node, frame): self.write(repr(node.as_const(frame.eval_ctx))) def visit_Tuple(self, node, frame): self.write('(') idx = -1 for idx, item in enumerate(node.items): if idx: self.write(', ') self.visit(item, frame) self.write(idx == 0 and ',)' or ')') def visit_List(self, node, frame): self.write('[') for idx, item in enumerate(node.items): if idx: self.write(', ') self.visit(item, frame) self.write(']') def visit_Dict(self, node, frame): self.write('{') for idx, item in enumerate(node.items): if idx: self.write(', ') self.visit(item.key, frame) self.write(': ') self.visit(item.value, frame) self.write('}') def binop(operator): def visitor(self, node, frame): self.write('(') self.visit(node.left, frame) self.write(' %s ' % operator) self.visit(node.right, frame) self.write(')') return visitor def uaop(operator): def visitor(self, node, frame): self.write('(' + operator) self.visit(node.node, frame) self.write(')') return visitor visit_Add = binop('+') visit_Sub = binop('-') visit_Mul = binop('*') visit_Div = binop('/') visit_FloorDiv = binop('//') visit_Pow = binop('**') visit_Mod = binop('%') visit_And = binop('and') visit_Or = binop('or') visit_Pos = uaop('+') visit_Neg = uaop('-') visit_Not = uaop('not ') del binop, uaop def visit_Concat(self, node, frame): if frame.eval_ctx.volatile: func_name = '(context.eval_ctx.volatile and' \ ' markup_join or unicode_join)' elif frame.eval_ctx.autoescape: func_name = 'markup_join' else: func_name = 'unicode_join' self.write('%s((' % func_name) for arg in node.nodes: self.visit(arg, frame) self.write(', ') self.write('))') def visit_Compare(self, node, frame): self.visit(node.expr, frame) for op in node.ops: self.visit(op, frame) def visit_Operand(self, node, frame): self.write(' %s ' % operators[node.op]) self.visit(node.expr, frame) def visit_Getattr(self, node, frame): self.write('environment.getattr(') self.visit(node.node, frame) self.write(', %r)' % node.attr) def visit_Getitem(self, node, frame): # slices bypass the environment getitem method. if isinstance(node.arg, nodes.Slice): self.visit(node.node, frame) self.write('[') self.visit(node.arg, frame) self.write(']') else: self.write('environment.getitem(') self.visit(node.node, frame) self.write(', ') self.visit(node.arg, frame) self.write(')') def visit_Slice(self, node, frame): if node.start is not None: self.visit(node.start, frame) self.write(':') if node.stop is not None: self.visit(node.stop, frame) if node.step is not None: self.write(':') self.visit(node.step, frame) def visit_Filter(self, node, frame): self.write(self.filters[node.name] + '(') func = self.environment.filters.get(node.name) if func is None: self.fail('no filter named %r' % node.name, node.lineno) if getattr(func, 'contextfilter', False): self.write('context, ') elif getattr(func, 'evalcontextfilter', False): self.write('context.eval_ctx, ') elif getattr(func, 'environmentfilter', False): self.write('environment, ') # if the filter node is None we are inside a filter block # and want to write to the current buffer if node.node is not None: self.visit(node.node, frame) elif frame.eval_ctx.volatile: self.write('(context.eval_ctx.autoescape and' ' Markup(concat(%s)) or concat(%s))' % (frame.buffer, frame.buffer)) elif frame.eval_ctx.autoescape: self.write('Markup(concat(%s))' % frame.buffer) else: self.write('concat(%s)' % frame.buffer) self.signature(node, frame) self.write(')') def visit_Test(self, node, frame): self.write(self.tests[node.name] + '(') if node.name not in self.environment.tests: self.fail('no test named %r' % node.name, node.lineno) self.visit(node.node, frame) self.signature(node, frame) self.write(')') def visit_CondExpr(self, node, frame): def write_expr2(): if node.expr2 is not None: return self.visit(node.expr2, frame) self.write('environment.undefined(%r)' % ('the inline if-' 'expression on %s evaluated to false and ' 'no else section was defined.' % self.position(node))) if not have_condexpr: self.write('((') self.visit(node.test, frame) self.write(') and (') self.visit(node.expr1, frame) self.write(',) or (') write_expr2() self.write(',))[0]') else: self.write('(') self.visit(node.expr1, frame) self.write(' if ') self.visit(node.test, frame) self.write(' else ') write_expr2() self.write(')') def visit_Call(self, node, frame, forward_caller=False): if self.environment.sandboxed: self.write('environment.call(context, ') else: self.write('context.call(') self.visit(node.node, frame) extra_kwargs = forward_caller and {'caller': 'caller'} or None self.signature(node, frame, extra_kwargs) self.write(')') def visit_Keyword(self, node, frame): self.write(node.key + '=') self.visit(node.value, frame) # -- Unused nodes for extensions def visit_MarkSafe(self, node, frame): self.write('Markup(') self.visit(node.expr, frame) self.write(')') def visit_EnvironmentAttribute(self, node, frame): self.write('environment.' + node.name) def visit_ExtensionAttribute(self, node, frame): self.write('environment.extensions[%r].%s' % (node.identifier, node.name)) def visit_ImportedName(self, node, frame): self.write(self.import_aliases[node.importname]) def visit_InternalName(self, node, frame): self.write(node.name) def visit_ContextReference(self, node, frame): self.write('context') def visit_Continue(self, node, frame): self.writeline('continue', node) def visit_Break(self, node, frame): self.writeline('break', node) def visit_Scope(self, node, frame): scope_frame = frame.inner() scope_frame.inspect(node.iter_child_nodes()) aliases = self.push_scope(scope_frame) self.pull_locals(scope_frame) self.blockvisit(node.body, scope_frame) self.pop_scope(aliases, scope_frame) def visit_EvalContextModifier(self, node, frame): for keyword in node.options: self.writeline('context.eval_ctx.%s = ' % keyword.key) self.visit(keyword.value, frame) try: val = keyword.value.as_const(frame.eval_ctx) except nodes.Impossible: frame.eval_ctx.volatile = True else: setattr(frame.eval_ctx, keyword.key, val) def visit_ScopedEvalContextModifier(self, node, frame): old_ctx_name = self.temporary_identifier() safed_ctx = frame.eval_ctx.save() self.writeline('%s = context.eval_ctx.save()' % old_ctx_name) self.visit_EvalContextModifier(node, frame) for child in node.body: self.visit(child, frame) frame.eval_ctx.revert(safed_ctx) self.writeline('context.eval_ctx.revert(%s)' % old_ctx_name)
apache-2.0
smARTLab-liv/smartlabatwork-release
slaw_navigation/nodes/OdomScanMovePidMonitor.py
1
9756
#!/usr/bin/env python import rospy import actionlib from sensor_msgs.msg import LaserScan from geometry_msgs.msg import Twist, Pose2D, PoseStamped from nav_msgs.msg import Odometry from math import pi from slaw_actions.msg import * from slaw_srvs.srv import * import sys, select import tf odom = "/odom" base_frame = "/base_link" class OdomScanMovePidMonitor: x = y = theta = 0 def __init__(self): self.tfListen = tf.TransformListener() rospy.sleep(1) self.stopped = True self.eps_x = 0.01 self.eps_y = 0.01 self.eps_theta = 0.01 self.thetaa = 0 self.odomTargetPose = Pose2D() rospy.Subscriber("/odom", Odometry, self.cb_odom) rospy.Subscriber("/scan_registration/theta", Pose2D, self.cb_theta) self.pid_pub = rospy.Publisher('/scan_registration/tarDir', Pose2D) #change pid params? self.stopPid = rospy.ServiceProxy('scan_registration/switchOffPID', switchOff) self.action_server = actionlib.simple_action_server.SimpleActionServer('odom_fine_adjust', OdomFineAdjustAction, self.execute_cb, False) self.action_server.start() def cb_theta(self, pose): self.thetaa = pose.theta def execute_cb(self, goal): self.set_target_with_offset(goal.target.x, goal.target.y, goal.target.theta) self.eps_x = goal.threshold.x self.eps_y = goal.threshold.y self.eps_theta = goal.threshold.theta self.stopped = False rate_hz = 10 rate = rospy.Rate(rate_hz) counter = 0 result = OdomFineAdjustResult() while not self.is_done() and counter < goal.duration*rate_hz: counter += 1 result.success = False result.result.x = self.x result.result.y = self.y result.result.theta = self.theta if self.action_server.is_preempt_requested(): self.action_server.set_preempted() self.action_server.set_aborted(result) self.stop() return rate.sleep() self.stop() print counter result.success = True self.action_server.set_succeeded(result) def is_done(self): if abs(self.x)>self.eps_x or abs(self.y)>self.eps_y or abs(self.theta)>self.eps_theta: return False return True def stop(self): self.stopped = True # self.set_target_with_offset(0,0,0) self.pub_pid_target() req = switchOffRequest() req.pause = self.stopped #rospy.wait_for_service('/scan_registration/switchOffRegistration') try: resp = self.stopPid(req) print "pid stopped ", resp.success except rospy.ServiceException, e: rospy.logerr("Service did not process request: %s", str(e)) def cb_odom(self,msg): if self.stopped: return #self.set_target_with_offset(0.0, -0.2, 0) self.calc_diff(self.odom_to_2D_Pose(msg)) self.pub_pid_target() def odom_to_2D_Pose(self, odom_msg): pose = Pose2D() pose.x = odom_msg.pose.pose.position.x pose.y = odom_msg.pose.pose.position.y quat = [odom_msg.pose.pose.orientation.x, odom_msg.pose.pose.orientation.y, odom_msg.pose.pose.orientation.z,odom_msg.pose.pose.orientation.w] r,p, pose.theta = tf.transformations.euler_from_quaternion(quat) return pose def transformPose(self, pose_in): if self.tfListen.frameExists(base_frame) and self.tfListen.frameExists(odom): time = self.tfListen.getLatestCommonTime(odom, base_frame) pose_in.header.stamp = time pose = self.tfListen.transformPose(odom, pose_in) return pose return None def set_target_with_offset(self, x, y, theta): pose_stamped = PoseStamped() pose_stamped.header.stamp = rospy.Time.now() pose_stamped.header.frame_id = base_frame pose_stamped.pose.position.x = x pose_stamped.pose.position.y = y pose_stamped.pose.orientation.w = 1.0 tar = self.transformPose(pose_stamped) self.odomTargetPose.x = tar.pose.position.x self.odomTargetPose.y = tar.pose.position.y quat = [tar.pose.orientation.x, tar.pose.orientation.y, tar.pose.orientation.z,tar.pose.orientation.w] r,p, theta = tf.transformations.euler_from_quaternion(quat) self.odomTargetPose.theta = theta self.x = x self.y = y self.theta = theta def calc_diff(self, pose): self.x = self.odomTargetPose.x - pose.x self.y = self.odomTargetPose.y - pose.y self.theta = self.odomTargetPose.theta - pose.theta def pub_pid_target(self): pose = Pose2D() #pose.x = self.x / 2. #todo if self.x > 0.025: pose.x = 0.1 elif self.x < -0.025: pose.x = -0.1 else: pose.x = 0 # pose.x = 0 #pose.y = self.y / 2. # pose.y = 0 if self.y > 0.025: pose.y = 0.1 elif self.y < -0.025: pose.y = -0.1 else: pose.y = 0 #pose.theta = self.theta / 2. pose.theta = self.thetaa; self.pid_pub.publish(pose) def loop(self): rate = rospy.Rate(5) print "enter commands" while not rospy.is_shutdown(): i,o,e = select.select([sys.stdin],[],[],0.0001) for s in i: if s == sys.stdin: input_cmd = sys.stdin.readline() self.processKey(input_cmd) rate.sleep() def processKey(self, key): if key == 'forward-5\n': print "fw 5" tuck_arm_client = actionlib.SimpleActionClient('odom_fine_adjust', OdomFineAdjustAction) goal = OdomFineAdjustGoal() goal.target.x = 0.05 goal.target.y = 0 goal.threshold.x = 0.05 goal.threshold.y = 0.05 goal.threshold.theta = 1 goal.duration = 10; tuck_arm_client.wait_for_server(rospy.Duration(10.0)) print "waiting start" tuck_arm_client.send_goal_and_wait(goal, rospy.Duration(30.0), rospy.Duration(10.0)) print "result ", tuck_arm_client.get_result() print "state ", tuck_arm_client.get_state() print "waiting done" if key == 'back-20\n': print "back 20" tuck_arm_client = actionlib.SimpleActionClient('odom_fine_adjust', OdomFineAdjustAction) goal = OdomFineAdjustGoal() goal.target.x = -0.2 goal.target.y = 0 goal.threshold.x = 0.05 goal.threshold.y = 0.05 goal.threshold.theta = 1 goal.duration = 10; tuck_arm_client.wait_for_server(rospy.Duration(10.0)) print "waiting start" tuck_arm_client.send_goal_and_wait(goal, rospy.Duration(30.0), rospy.Duration(10.0)) print "result ", tuck_arm_client.get_result() print "state ", tuck_arm_client.get_state() print "waiting done" if key == 'forward-20\n': print "fw 20" tuck_arm_client = actionlib.SimpleActionClient('odom_fine_adjust', OdomFineAdjustAction) goal = OdomFineAdjustGoal() goal.target.x = 0.2 goal.target.y = 0 goal.threshold.x = 0.05 goal.threshold.y = 0.05 goal.threshold.theta = 1 goal.duration = 10; tuck_arm_client.wait_for_server(rospy.Duration(10.0)) print "waiting start" tuck_arm_client.send_goal_and_wait(goal, rospy.Duration(30.0), rospy.Duration(10.0)) print "result ", tuck_arm_client.get_result() print "state ", tuck_arm_client.get_state() print "waiting done" if key == 'right-5\n': print "right 5" tuck_arm_client = actionlib.SimpleActionClient('odom_fine_adjust', OdomFineAdjustAction) goal = OdomFineAdjustGoal() goal.target.x = 0 goal.target.y = -0.05 goal.threshold.x = 0.01 goal.threshold.y = 0.01 goal.threshold.theta = 0.01 goal.duration = 10; tuck_arm_client.wait_for_server(rospy.Duration(10.0)) print "waiting start" tuck_arm_client.send_goal_and_wait(goal, rospy.Duration(30.0), rospy.Duration(10.0)) print "result ", tuck_arm_client.get_result() print "state ", tuck_arm_client.get_state() print "waiting done" if key == 'left-5\n': print "left 5" tuck_arm_client = actionlib.SimpleActionClient('odom_fine_adjust', OdomFineAdjustAction) goal = OdomFineAdjustGoal() goal.target.x = 0 goal.target.y = 0.05 goal.threshold.x = 0.01 goal.threshold.y = 0.01 goal.threshold.theta = 0.01 goal.duration = 10; tuck_arm_client.wait_for_server(rospy.Duration(10.0)) print "waiting start" tuck_arm_client.send_goal_and_wait(goal, rospy.Duration(30.0), rospy.Duration(10.0)) print "result ", tuck_arm_client.get_result() print "state ", tuck_arm_client.get_state() print "waiting done" if __name__ == '__main__': rospy.init_node('odom_monitor', anonymous = False) mon = OdomScanMovePidMonitor() mon.loop() #rospy.spin()
mit
lord63/a_bunch_of_code
v2ex/setup.py
1
1231
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup import v2ex_daily_mission try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): with open('README.md') as f: long_description = f.read() setup( name='v2ex_daily_mission', version=v2ex_daily_mission.__version__, description='complete mission, get money, from v2ex', long_description=long_description, url='https://github.com/lord63/a_bunch_of_code/tree/master/v2ex', author='lord63', author_email='lord63.j@gmail.com', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Operating System :: POSIX', 'Operating System :: POSIX :: Linux', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], keywords='v2ex daily money sign', packages=['v2ex_daily_mission'], install_requires=['terminal','requests', 'lxml'], include_package_data=True, entry_points={ 'console_scripts':[ 'v2ex=v2ex_daily_mission.v2ex:main'] } )
mit
ltilve/ChromiumGStreamerBackend
content/test/gpu/gpu_tests/screenshot_sync.py
6
2440
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import random import gpu_test_base import screenshot_sync_expectations as expectations from telemetry import benchmark from telemetry.core import util from telemetry.page import page_test from telemetry.story import story_set as story_set_module from telemetry.util import image_util data_path = os.path.join( util.GetChromiumSrcDir(), 'content', 'test', 'data', 'gpu') class ScreenshotSyncValidator(gpu_test_base.ValidatorBase): def CustomizeBrowserOptions(self, options): options.AppendExtraBrowserArgs('--force-gpu-rasterization') def ValidateAndMeasurePageInner(self, page, tab, results): if not tab.screenshot_supported: raise page_test.Failure('Browser does not support screenshot capture') def CheckColorMatch(canvasRGB, screenshotRGB): for i in range(0, 3): if abs(canvasRGB[i] - screenshotRGB[i]) > 1: raise page_test.Failure('Color mismatch in component #%d: %d vs %d' % (i, canvasRGB[i], screenshotRGB[i])) def CheckScreenshot(): canvasRGB = []; for i in range(0, 3): canvasRGB.append(random.randint(0, 255)) tab.EvaluateJavaScript("window.draw(%d, %d, %d);" % tuple(canvasRGB)) screenshot = tab.Screenshot(5) CheckColorMatch(canvasRGB, image_util.Pixels(screenshot)) repetitions = 50 for n in range(0, repetitions): CheckScreenshot() class ScreenshotSyncPage(gpu_test_base.PageBase): def __init__(self, story_set, base_dir, expectations): super(ScreenshotSyncPage, self).__init__( url='file://screenshot_sync.html', page_set=story_set, base_dir=base_dir, name='ScreenshotSync', expectations=expectations) @benchmark.Disabled('linux', 'mac', 'win') class ScreenshotSyncProcess(gpu_test_base.TestBase): """Tests that screenhots are properly synchronized with the frame one which they were requested""" test = ScreenshotSyncValidator @classmethod def Name(cls): return 'screenshot_sync' def _CreateExpectations(self): return expectations.ScreenshotSyncExpectations() def CreateStorySet(self, options): ps = story_set_module.StorySet(base_dir=data_path, serving_dirs=['']) ps.AddStory(ScreenshotSyncPage(ps, ps.base_dir, self.GetExpectations())) return ps
bsd-3-clause
40223245/40223245W11
wsgi.py
5
7752
# coding=utf-8 # 上面的程式內容編碼必須在程式的第一或者第二行才會有作用 ################# (1) 模組導入區 # 導入 cherrypy 模組, 為了在 OpenShift 平台上使用 cherrypy 模組, 必須透過 setup.py 安裝 import cherrypy # 導入 Python 內建的 os 模組, 因為 os 模組為 Python 內建, 所以無需透過 setup.py 安裝 import os # 導入 random 模組 import random ################# (2) 廣域變數設定區 # 確定程式檔案所在目錄, 在 Windows 下有最後的反斜線 _curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) # 設定在雲端與近端的資料儲存目錄 if 'OPENSHIFT_REPO_DIR' in os.environ.keys(): # 表示程式在雲端執行 download_root_dir = os.environ['OPENSHIFT_DATA_DIR'] data_dir = os.environ['OPENSHIFT_DATA_DIR'] else: # 表示程式在近端執行 download_root_dir = _curdir + "/local_data/" data_dir = _curdir + "/local_data/" '''以下為近端 input() 與 for 迴圈應用的程式碼, 若要將程式送到 OpenShift 執行, 除了採用 CherryPy 網際框架外, 還要轉為 html 列印 # 利用 input() 取得的資料型別為字串 toprint = input("要印甚麼內容?") # 若要將 input() 取得的字串轉為整數使用, 必須利用 int() 轉換 repeat_no = int(input("重複列印幾次?")) for i in range(repeat_no): print(toprint) ''' ################# (3) 程式類別定義區 # 以下改用 CherryPy 網際框架程式架構 # 以下為 Hello 類別的設計內容, 其中的 object 使用, 表示 Hello 類別繼承 object 的所有特性, 包括方法與屬性設計 class Hello(object): # Hello 類別的啟動設定 _cp_config = { 'tools.encode.encoding': 'utf-8', 'tools.sessions.on' : True, 'tools.sessions.storage_type' : 'file', #'tools.sessions.locking' : 'explicit', # session 以檔案儲存, 而且位於 data_dir 下的 tmp 目錄 'tools.sessions.storage_path' : data_dir+'/tmp', # session 有效時間設為 60 分鐘 'tools.sessions.timeout' : 60 } def __init__(self): # 配合透過案例啟始建立所需的目錄 if not os.path.isdir(data_dir+'/tmp'): os.mkdir(data_dir+'/tmp') if not os.path.isdir(data_dir+"/downloads"): os.mkdir(data_dir+"/downloads") if not os.path.isdir(data_dir+"/images"): os.mkdir(data_dir+"/images") # 以 @ 開頭的 cherrypy.expose 為 decorator, 用來表示隨後的成員方法, 可以直接讓使用者以 URL 連結執行 @cherrypy.expose # index 方法為 CherryPy 各類別成員方法中的內建(default)方法, 當使用者執行時未指定方法, 系統將會優先執行 index 方法 # 有 self 的方法為類別中的成員方法, Python 程式透過此一 self 在各成員方法間傳遞物件內容 def index_orig(self, toprint="Hello World!"): return toprint @cherrypy.expose def hello(self, toprint="Hello World!"): return toprint @cherrypy.expose def index(self, guess=None): # 將標準答案存入 answer session 對應區 theanswer = random.randint(1, 100) thecount = 0 # 將答案與計算次數變數存進 session 對應變數 cherrypy.session['answer'] = theanswer cherrypy.session['count'] = thecount # 印出讓使用者輸入的超文件表單 outstring = ''' <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <!-- 載入 brython.js --> <script type="text/javascript" src="/static/Brython3.1.0-20150301-090019/brython.js"></script> <script src="/static/Cango2D.js" type="text/javascript"></script> <script src="/static/gearUtils-04.js" type="text/javascript"></script> </head> <!-- 啟動 brython() --> <body onload="brython()"> <form method=POST action=doCheck> 請輸入您所猜的整數:<input type=text name=guess><br /> <input type=submit value=send> </form> <hr> <!-- 以下在網頁內嵌 Brython 程式 --> <script type="text/python"> from browser import document, alert def echo(ev): alert(document["zone"].value) # 將文件中名稱為 mybutton 的物件, 透過 click 事件與 echo 函式 bind 在一起 document['mybutton'].bind('click',echo) </script> <input id="zone"><button id="mybutton">click !</button> <hr> <!-- 以下為 canvas 畫圖程式 --> <script type="text/python"> # 從 browser 導入 document from browser import document import math # 畫布指定在名稱為 plotarea 的 canvas 上 canvas = document["plotarea"] ctx = canvas.getContext("2d") # 用紅色畫一條直線 ctx.beginPath() ctx.lineWidth = 3 ctx.moveTo(0, 0) ctx.lineTo(0, 500) ctx.strokeStyle = "red" ctx.stroke() # 用藍色再畫一條直線 ctx.beginPath() ctx.lineWidth = 3 ctx.moveTo(0, 0) ctx.lineTo(500, 0) ctx.strokeStyle = "blue" ctx.stroke() # 用綠色再畫一條直線 ctx.beginPath() ctx.lineWidth = 3 ctx.moveTo(0, 0) ctx.lineTo(500, 500) ctx.strokeStyle = "green" ctx.stroke() # 用黑色畫一個圓 ctx.beginPath() ctx.lineWidth = 3 ctx.strokeStyle = "black" ctx.arc(250,250,50,0,2*math.pi) ctx.stroke() </script> <canvas id="plotarea" width="800" height="600"></canvas> </body> </html> ''' return outstring @cherrypy.expose def doCheck(self, guess=None): # 假如使用者直接執行 doCheck, 則設法轉回根方法 if guess is None: raise cherrypy.HTTPRedirect("/") # 從 session 取出 answer 對應資料, 且處理直接執行 doCheck 時無法取 session 值情況 try: theanswer = int(cherrypy.session.get('answer')) except: raise cherrypy.HTTPRedirect("/") # 經由表單所取得的 guess 資料型別為 string try: theguess = int(guess) except: return "error " + self.guessform() # 每執行 doCheck 一次,次數增量一次 cherrypy.session['count'] += 1 # 答案與所猜數字進行比對 if theanswer < theguess: return "big " + self.guessform() elif theanswer > theguess: return "small " + self.guessform() else: # 已經猜對, 從 session 取出累計猜測次數 thecount = cherrypy.session.get('count') return "exact: <a href=''>再猜</a>" def guessform(self): # 印出讓使用者輸入的超文件表單 outstring = str(cherrypy.session.get('answer')) + "/" + str(cherrypy.session.get('count')) + '''<form method=POST action=doCheck> 請輸入您所猜的整數:<input type=text name=guess><br /> <input type=submit value=send> </form>''' return outstring ################# (4) 程式啟動區 # 配合程式檔案所在目錄設定靜態目錄或靜態檔案 application_conf = {'/static':{ 'tools.staticdir.on': True, # 程式執行目錄下, 必須自行建立 static 目錄 'tools.staticdir.dir': _curdir+"/static"}, '/downloads':{ 'tools.staticdir.on': True, 'tools.staticdir.dir': data_dir+"/downloads"}, '/images':{ 'tools.staticdir.on': True, 'tools.staticdir.dir': data_dir+"/images"} } if 'OPENSHIFT_REPO_DIR' in os.environ.keys(): # 表示在 OpenSfhit 執行 application = cherrypy.Application(Hello(), config=application_conf) else: # 表示在近端執行 cherrypy.quickstart(Hello(), config=application_conf)
gpl-3.0
maurofaccenda/ansible
test/runner/test.py
2
20662
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """Test runner for all Ansible tests.""" from __future__ import absolute_import, print_function import errno import os import sys from lib.util import ( ApplicationError, display, raw_command, ) from lib.delegation import ( delegate, ) from lib.executor import ( command_posix_integration, command_network_integration, command_windows_integration, command_units, command_compile, command_shell, SUPPORTED_PYTHON_VERSIONS, COMPILE_PYTHON_VERSIONS, PosixIntegrationConfig, WindowsIntegrationConfig, NetworkIntegrationConfig, SanityConfig, UnitsConfig, CompileConfig, ShellConfig, ApplicationWarning, Delegate, generate_pip_install, check_startup, ) from lib.sanity import ( command_sanity, sanity_init, sanity_get_tests, ) from lib.target import ( find_target_completion, walk_posix_integration_targets, walk_network_integration_targets, walk_windows_integration_targets, walk_units_targets, walk_compile_targets, walk_sanity_targets, ) from lib.core_ci import ( AWS_ENDPOINTS, ) from lib.cloud import ( initialize_cloud_plugins, ) import lib.cover def main(): """Main program function.""" try: git_root = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..')) os.chdir(git_root) initialize_cloud_plugins() sanity_init() args = parse_args() config = args.config(args) display.verbosity = config.verbosity display.color = config.color display.info_stderr = isinstance(config, SanityConfig) and config.lint check_startup() try: args.func(config) except Delegate as ex: delegate(config, ex.exclude, ex.require) display.review_warnings() except ApplicationWarning as ex: display.warning(str(ex)) exit(0) except ApplicationError as ex: display.error(str(ex)) exit(1) except KeyboardInterrupt: exit(2) except IOError as ex: if ex.errno == errno.EPIPE: exit(3) raise def parse_args(): """Parse command line arguments.""" try: import argparse except ImportError: if '--requirements' not in sys.argv: raise raw_command(generate_pip_install('ansible-test')) import argparse try: import argcomplete except ImportError: argcomplete = None if argcomplete: epilog = 'Tab completion available using the "argcomplete" python package.' else: epilog = 'Install the "argcomplete" python package to enable tab completion.' parser = argparse.ArgumentParser(epilog=epilog) common = argparse.ArgumentParser(add_help=False) common.add_argument('-e', '--explain', action='store_true', help='explain commands that would be executed') common.add_argument('-v', '--verbose', dest='verbosity', action='count', default=0, help='display more output') common.add_argument('--color', metavar='COLOR', nargs='?', help='generate color output: %(choices)s', choices=('yes', 'no', 'auto'), const='yes', default='auto') common.add_argument('--debug', action='store_true', help='run ansible commands in debug mode') test = argparse.ArgumentParser(add_help=False, parents=[common]) test.add_argument('include', metavar='TARGET', nargs='*', help='test the specified target').completer = complete_target test.add_argument('--exclude', metavar='TARGET', action='append', help='exclude the specified target').completer = complete_target test.add_argument('--require', metavar='TARGET', action='append', help='require the specified target').completer = complete_target test.add_argument('--coverage', action='store_true', help='analyze code coverage when running tests') test.add_argument('--metadata', help=argparse.SUPPRESS) add_changes(test, argparse) add_environments(test) integration = argparse.ArgumentParser(add_help=False, parents=[test]) integration.add_argument('--python', metavar='VERSION', choices=SUPPORTED_PYTHON_VERSIONS, help='python version: %s' % ', '.join(SUPPORTED_PYTHON_VERSIONS)) integration.add_argument('--start-at', metavar='TARGET', help='start at the specified target').completer = complete_target integration.add_argument('--start-at-task', metavar='TASK', help='start at the specified task') integration.add_argument('--allow-destructive', action='store_true', help='allow destructive tests (--local and --tox only)') integration.add_argument('--retry-on-error', action='store_true', help='retry failed test with increased verbosity') subparsers = parser.add_subparsers(metavar='COMMAND') subparsers.required = True # work-around for python 3 bug which makes subparsers optional posix_integration = subparsers.add_parser('integration', parents=[integration], help='posix integration tests') posix_integration.set_defaults(func=command_posix_integration, targets=walk_posix_integration_targets, config=PosixIntegrationConfig) add_extra_docker_options(posix_integration) network_integration = subparsers.add_parser('network-integration', parents=[integration], help='network integration tests') network_integration.set_defaults(func=command_network_integration, targets=walk_network_integration_targets, config=NetworkIntegrationConfig) network_integration.add_argument('--platform', metavar='PLATFORM', action='append', help='network platform/version').completer = complete_network_platform windows_integration = subparsers.add_parser('windows-integration', parents=[integration], help='windows integration tests') windows_integration.set_defaults(func=command_windows_integration, targets=walk_windows_integration_targets, config=WindowsIntegrationConfig) windows_integration.add_argument('--windows', metavar='VERSION', action='append', help='windows version').completer = complete_windows units = subparsers.add_parser('units', parents=[test], help='unit tests') units.set_defaults(func=command_units, targets=walk_units_targets, config=UnitsConfig) units.add_argument('--python', metavar='VERSION', choices=SUPPORTED_PYTHON_VERSIONS + ('default',), help='python version: %s' % ', '.join(SUPPORTED_PYTHON_VERSIONS)) units.add_argument('--collect-only', action='store_true', help='collect tests but do not execute them') add_extra_docker_options(units, integration=False) compiler = subparsers.add_parser('compile', parents=[test], help='compile tests') compiler.set_defaults(func=command_compile, targets=walk_compile_targets, config=CompileConfig) compiler.add_argument('--python', metavar='VERSION', choices=COMPILE_PYTHON_VERSIONS, help='python version: %s' % ', '.join(COMPILE_PYTHON_VERSIONS)) add_lint(compiler) add_extra_docker_options(compiler, integration=False) sanity = subparsers.add_parser('sanity', parents=[test], help='sanity tests') sanity.set_defaults(func=command_sanity, targets=walk_sanity_targets, config=SanityConfig) sanity.add_argument('--test', metavar='TEST', action='append', choices=[test.name for test in sanity_get_tests()], help='tests to run').completer = complete_sanity_test sanity.add_argument('--skip-test', metavar='TEST', action='append', choices=[test.name for test in sanity_get_tests()], help='tests to skip').completer = complete_sanity_test sanity.add_argument('--list-tests', action='store_true', help='list available tests') sanity.add_argument('--python', metavar='VERSION', choices=SUPPORTED_PYTHON_VERSIONS, help='python version: %s' % ', '.join(SUPPORTED_PYTHON_VERSIONS)) sanity.add_argument('--base-branch', help=argparse.SUPPRESS) add_lint(sanity) add_extra_docker_options(sanity, integration=False) shell = subparsers.add_parser('shell', parents=[common], help='open an interactive shell') shell.set_defaults(func=command_shell, config=ShellConfig) add_environments(shell, tox_version=True) add_extra_docker_options(shell) coverage_common = argparse.ArgumentParser(add_help=False, parents=[common]) add_environments(coverage_common, tox_version=True, tox_only=True) coverage = subparsers.add_parser('coverage', help='code coverage management and reporting') coverage_subparsers = coverage.add_subparsers(metavar='COMMAND') coverage_subparsers.required = True # work-around for python 3 bug which makes subparsers optional coverage_combine = coverage_subparsers.add_parser('combine', parents=[coverage_common], help='combine coverage data and rewrite remote paths') coverage_combine.set_defaults(func=lib.cover.command_coverage_combine, config=lib.cover.CoverageConfig) coverage_erase = coverage_subparsers.add_parser('erase', parents=[coverage_common], help='erase coverage data files') coverage_erase.set_defaults(func=lib.cover.command_coverage_erase, config=lib.cover.CoverageConfig) coverage_report = coverage_subparsers.add_parser('report', parents=[coverage_common], help='generate console coverage report') coverage_report.set_defaults(func=lib.cover.command_coverage_report, config=lib.cover.CoverageConfig) coverage_html = coverage_subparsers.add_parser('html', parents=[coverage_common], help='generate html coverage report') coverage_html.set_defaults(func=lib.cover.command_coverage_html, config=lib.cover.CoverageConfig) coverage_xml = coverage_subparsers.add_parser('xml', parents=[coverage_common], help='generate xml coverage report') coverage_xml.set_defaults(func=lib.cover.command_coverage_xml, config=lib.cover.CoverageConfig) if argcomplete: argcomplete.autocomplete(parser, always_complete_options=False, validator=lambda i, k: True) args = parser.parse_args() if args.explain and not args.verbosity: args.verbosity = 1 if args.color == 'yes': args.color = True elif args.color == 'no': args.color = False else: args.color = sys.stdout.isatty() return args def add_lint(parser): """ :type parser: argparse.ArgumentParser """ parser.add_argument('--lint', action='store_true', help='write lint output to stdout, everything else stderr') parser.add_argument('--junit', action='store_true', help='write test failures to junit xml files') parser.add_argument('--failure-ok', action='store_true', help='exit successfully on failed tests after saving results') def add_changes(parser, argparse): """ :type parser: argparse.ArgumentParser :type argparse: argparse """ parser.add_argument('--changed', action='store_true', help='limit targets based on changes') changes = parser.add_argument_group(title='change detection arguments') changes.add_argument('--tracked', action='store_true', help=argparse.SUPPRESS) changes.add_argument('--untracked', action='store_true', help='include untracked files') changes.add_argument('--ignore-committed', dest='committed', action='store_false', help='exclude committed files') changes.add_argument('--ignore-staged', dest='staged', action='store_false', help='exclude staged files') changes.add_argument('--ignore-unstaged', dest='unstaged', action='store_false', help='exclude unstaged files') changes.add_argument('--changed-from', metavar='PATH', help=argparse.SUPPRESS) changes.add_argument('--changed-path', metavar='PATH', action='append', help=argparse.SUPPRESS) def add_environments(parser, tox_version=False, tox_only=False): """ :type parser: argparse.ArgumentParser :type tox_version: bool :type tox_only: bool """ parser.add_argument('--requirements', action='store_true', help='install command requirements') environments = parser.add_mutually_exclusive_group() environments.add_argument('--local', action='store_true', help='run from the local environment') if tox_version: environments.add_argument('--tox', metavar='VERSION', nargs='?', default=None, const='.'.join(str(i) for i in sys.version_info[:2]), choices=SUPPORTED_PYTHON_VERSIONS, help='run from a tox virtualenv: %s' % ', '.join(SUPPORTED_PYTHON_VERSIONS)) else: environments.add_argument('--tox', action='store_true', help='run from a tox virtualenv') tox = parser.add_argument_group(title='tox arguments') tox.add_argument('--tox-sitepackages', action='store_true', help='allow access to globally installed packages') if tox_only: environments.set_defaults( docker=None, remote=None, remote_stage=None, remote_aws_region=None, ) return environments.add_argument('--docker', metavar='IMAGE', nargs='?', default=None, const='ubuntu1604', help='run from a docker container').completer = complete_docker environments.add_argument('--remote', metavar='PLATFORM', default=None, help='run from a remote instance').completer = complete_remote remote = parser.add_argument_group(title='remote arguments') remote.add_argument('--remote-stage', metavar='STAGE', help='remote stage to use: %(choices)s', choices=['prod', 'dev'], default='prod') remote.add_argument('--remote-aws-region', metavar='REGION', help='remote aws region to use: %(choices)s (default: auto)', choices=sorted(AWS_ENDPOINTS), default=None) def add_extra_docker_options(parser, integration=True): """ :type parser: argparse.ArgumentParser :type integration: bool """ docker = parser.add_argument_group(title='docker arguments') docker.add_argument('--docker-no-pull', action='store_false', dest='docker_pull', help='do not explicitly pull the latest docker images') if not integration: return docker.add_argument('--docker-util', metavar='IMAGE', default='httptester', help='docker utility image to provide test services') docker.add_argument('--docker-privileged', action='store_true', help='run docker container in privileged mode') def complete_target(prefix, parsed_args, **_): """ :type prefix: unicode :type parsed_args: any :rtype: list[str] """ return find_target_completion(parsed_args.targets, prefix) def complete_remote(prefix, parsed_args, **_): """ :type prefix: unicode :type parsed_args: any :rtype: list[str] """ del parsed_args with open('test/runner/completion/remote.txt', 'r') as completion_fd: images = completion_fd.read().splitlines() return [i for i in images if i.startswith(prefix)] def complete_docker(prefix, parsed_args, **_): """ :type prefix: unicode :type parsed_args: any :rtype: list[str] """ del parsed_args with open('test/runner/completion/docker.txt', 'r') as completion_fd: images = completion_fd.read().splitlines() return [i for i in images if i.startswith(prefix)] def complete_windows(prefix, parsed_args, **_): """ :type prefix: unicode :type parsed_args: any :rtype: list[str] """ with open('test/runner/completion/windows.txt', 'r') as completion_fd: images = completion_fd.read().splitlines() return [i for i in images if i.startswith(prefix) and (not parsed_args.windows or i not in parsed_args.windows)] def complete_network_platform(prefix, parsed_args, **_): """ :type prefix: unicode :type parsed_args: any :rtype: list[str] """ with open('test/runner/completion/network.txt', 'r') as completion_fd: images = completion_fd.read().splitlines() return [i for i in images if i.startswith(prefix) and (not parsed_args.platform or i not in parsed_args.platform)] def complete_sanity_test(prefix, parsed_args, **_): """ :type prefix: unicode :type parsed_args: any :rtype: list[str] """ del parsed_args tests = sorted(t.name for t in sanity_get_tests()) return [i for i in tests if i.startswith(prefix)] if __name__ == '__main__': main()
gpl-3.0
digital-abyss/ansible-modules-core
cloud/amazon/ec2_lc.py
47
12492
#!/usr/bin/python # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = """ --- module: ec2_lc short_description: Create or delete AWS Autoscaling Launch Configurations description: - Can create or delete AwS Autoscaling Configurations - Works with the ec2_asg module to manage Autoscaling Groups notes: - "Amazon ASG Autoscaling Launch Configurations are immutable once created, so modifying the configuration after it is changed will not modify the launch configuration on AWS. You must create a new config and assign it to the ASG instead." version_added: "1.6" author: "Gareth Rushgrove (@garethr)" options: state: description: - register or deregister the instance required: true choices: ['present', 'absent'] name: description: - Unique name for configuration required: true instance_type: description: - instance type to use for the instance required: true default: null aliases: [] image_id: description: - The AMI unique identifier to be used for the group required: false key_name: description: - The SSH key name to be used for access to managed instances required: false security_groups: description: - A list of security groups into which instances should be found required: false region: description: - The AWS region to use. If not specified then the value of the EC2_REGION environment variable, if any, is used. required: false aliases: ['aws_region', 'ec2_region'] volumes: description: - a list of volume dicts, each containing device name and optionally ephemeral id or snapshot id. Size and type (and number of iops for io device type) must be specified for a new volume or a root volume, and may be passed for a snapshot volume. For any volume, a volume size less than 1 will be interpreted as a request not to create the volume. required: false default: null aliases: [] user_data: description: - opaque blob of data which is made available to the ec2 instance required: false default: null aliases: [] kernel_id: description: - Kernel id for the EC2 instance required: false default: null aliases: [] spot_price: description: - The spot price you are bidding. Only applies for an autoscaling group with spot instances. required: false default: null instance_monitoring: description: - whether instances in group are launched with detailed monitoring. required: false default: false aliases: [] assign_public_ip: description: - Used for Auto Scaling groups that launch instances into an Amazon Virtual Private Cloud. Specifies whether to assign a public IP address to each instance launched in a Amazon VPC. required: false aliases: [] version_added: "1.8" ramdisk_id: description: - A RAM disk id for the instances. required: false default: null aliases: [] version_added: "1.8" instance_profile_name: description: - The name or the Amazon Resource Name (ARN) of the instance profile associated with the IAM role for the instances. required: false default: null aliases: [] version_added: "1.8" ebs_optimized: description: - Specifies whether the instance is optimized for EBS I/O (true) or not (false). required: false default: false aliases: [] version_added: "1.8" classic_link_vpc_id: description: - Id of ClassicLink enabled VPC required: false default: null version_added: "2.0" classic_link_vpc_security_groups: description: - A list of security group id's with which to associate the ClassicLink VPC instances. required: false default: null version_added: "2.0" extends_documentation_fragment: aws """ EXAMPLES = ''' - ec2_lc: name: special image_id: ami-XXX key_name: default security_groups: ['group', 'group2' ] instance_type: t1.micro volumes: - device_name: /dev/sda1 volume_size: 100 device_type: io1 iops: 3000 delete_on_termination: true ''' from ansible.module_utils.basic import * from ansible.module_utils.ec2 import * try: from boto.ec2.blockdevicemapping import BlockDeviceType, BlockDeviceMapping import boto.ec2.autoscale from boto.ec2.autoscale import LaunchConfiguration from boto.exception import BotoServerError HAS_BOTO = True except ImportError: HAS_BOTO = False def create_block_device(module, volume): # Not aware of a way to determine this programatically # http://aws.amazon.com/about-aws/whats-new/2013/10/09/ebs-provisioned-iops-maximum-iops-gb-ratio-increased-to-30-1/ MAX_IOPS_TO_SIZE_RATIO = 30 if 'snapshot' not in volume and 'ephemeral' not in volume: if 'volume_size' not in volume: module.fail_json(msg='Size must be specified when creating a new volume or modifying the root volume') if 'snapshot' in volume: if 'device_type' in volume and volume.get('device_type') == 'io1' and 'iops' not in volume: module.fail_json(msg='io1 volumes must have an iops value set') if 'ephemeral' in volume: if 'snapshot' in volume: module.fail_json(msg='Cannot set both ephemeral and snapshot') return BlockDeviceType(snapshot_id=volume.get('snapshot'), ephemeral_name=volume.get('ephemeral'), size=volume.get('volume_size'), volume_type=volume.get('device_type'), delete_on_termination=volume.get('delete_on_termination', False), iops=volume.get('iops')) def create_launch_config(connection, module): name = module.params.get('name') image_id = module.params.get('image_id') key_name = module.params.get('key_name') security_groups = module.params['security_groups'] user_data = module.params.get('user_data') volumes = module.params['volumes'] instance_type = module.params.get('instance_type') spot_price = module.params.get('spot_price') instance_monitoring = module.params.get('instance_monitoring') assign_public_ip = module.params.get('assign_public_ip') kernel_id = module.params.get('kernel_id') ramdisk_id = module.params.get('ramdisk_id') instance_profile_name = module.params.get('instance_profile_name') ebs_optimized = module.params.get('ebs_optimized') classic_link_vpc_id = module.params.get('classic_link_vpc_id') classic_link_vpc_security_groups = module.params.get('classic_link_vpc_security_groups') bdm = BlockDeviceMapping() if volumes: for volume in volumes: if 'device_name' not in volume: module.fail_json(msg='Device name must be set for volume') # Minimum volume size is 1GB. We'll use volume size explicitly set to 0 # to be a signal not to create this volume if 'volume_size' not in volume or int(volume['volume_size']) > 0: bdm[volume['device_name']] = create_block_device(module, volume) lc = LaunchConfiguration( name=name, image_id=image_id, key_name=key_name, security_groups=security_groups, user_data=user_data, block_device_mappings=[bdm], instance_type=instance_type, kernel_id=kernel_id, spot_price=spot_price, instance_monitoring=instance_monitoring, associate_public_ip_address=assign_public_ip, ramdisk_id=ramdisk_id, instance_profile_name=instance_profile_name, ebs_optimized=ebs_optimized, classic_link_vpc_security_groups=classic_link_vpc_security_groups, classic_link_vpc_id=classic_link_vpc_id, ) launch_configs = connection.get_all_launch_configurations(names=[name]) changed = False if not launch_configs: try: connection.create_launch_configuration(lc) launch_configs = connection.get_all_launch_configurations(names=[name]) changed = True except BotoServerError, e: module.fail_json(msg=str(e)) result = dict( ((a[0], a[1]) for a in vars(launch_configs[0]).items() if a[0] not in ('connection', 'created_time', 'instance_monitoring', 'block_device_mappings')) ) result['created_time'] = str(launch_configs[0].created_time) # Looking at boto's launchconfig.py, it looks like this could be a boolean # value or an object with an enabled attribute. The enabled attribute # could be a boolean or a string representation of a boolean. Since # I can't test all permutations myself to see if my reading of the code is # correct, have to code this *very* defensively if launch_configs[0].instance_monitoring is True: result['instance_monitoring'] = True else: try: result['instance_monitoring'] = module.boolean(launch_configs[0].instance_monitoring.enabled) except AttributeError: result['instance_monitoring'] = False if launch_configs[0].block_device_mappings is not None: result['block_device_mappings'] = [] for bdm in launch_configs[0].block_device_mappings: result['block_device_mappings'].append(dict(device_name=bdm.device_name, virtual_name=bdm.virtual_name)) if bdm.ebs is not None: result['block_device_mappings'][-1]['ebs'] = dict(snapshot_id=bdm.ebs.snapshot_id, volume_size=bdm.ebs.volume_size) module.exit_json(changed=changed, name=result['name'], created_time=result['created_time'], image_id=result['image_id'], arn=result['launch_configuration_arn'], security_groups=result['security_groups'], instance_type=result['instance_type'], result=result) def delete_launch_config(connection, module): name = module.params.get('name') launch_configs = connection.get_all_launch_configurations(names=[name]) if launch_configs: launch_configs[0].delete() module.exit_json(changed=True) else: module.exit_json(changed=False) def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( name=dict(required=True, type='str'), image_id=dict(type='str'), key_name=dict(type='str'), security_groups=dict(type='list'), user_data=dict(type='str'), kernel_id=dict(type='str'), volumes=dict(type='list'), instance_type=dict(type='str'), state=dict(default='present', choices=['present', 'absent']), spot_price=dict(type='float'), ramdisk_id=dict(type='str'), instance_profile_name=dict(type='str'), ebs_optimized=dict(default=False, type='bool'), associate_public_ip_address=dict(type='bool'), instance_monitoring=dict(default=False, type='bool'), assign_public_ip=dict(type='bool'), classic_link_vpc_security_groups=dict(type='list'), classic_link_vpc_id=dict(type='str') ) ) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO: module.fail_json(msg='boto required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module) try: connection = connect_to_aws(boto.ec2.autoscale, region, **aws_connect_params) except (boto.exception.NoAuthHandlerFound, StandardError), e: module.fail_json(msg=str(e)) state = module.params.get('state') if state == 'present': create_launch_config(connection, module) elif state == 'absent': delete_launch_config(connection, module) main()
gpl-3.0
ecell/ecell3
ecell/frontend/session-monitor/ecell/ui/osogo/PluginInstanceSelection.py
1
4155
#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: # # This file is part of the E-Cell System # # Copyright (C) 1996-2016 Keio University # Copyright (C) 2008-2016 RIKEN # Copyright (C) 2005-2009 The Molecular Sciences Institute # #:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: # # # E-Cell System is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # E-Cell System is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public # License along with E-Cell System -- see the file COPYING. # If not, write to the Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # #END_HEADER import gtk import gobject import copy from ecell.ecssupport import * from ecell.ui.osogo.OsogoWindow import * from ecell.ui.osogo.OsogoUtil import * class PluginInstanceSelection(OsogoWindow): """PluginInstanceSelection """ def __init__( self, aSession, anEntityListWindow ): """Constructor aSession --- a reference to Session (Session) anEntityListWindow --- a reference to EntityListWindow (EntityListWindow) """ # calls superclass's constructor OsogoWindow.__init__( self, aSession ) self.theEntityListWindow = anEntityListWindow self.thePluginManager = aSession.thePluginManager # ==================================================================== def openWindow( self ): # calls superclass's openWindow OsogoWindow.openWindow( self ) # add handers self.addHandlers( { 'on_ok_button_plugin_selection_clicked' : \ self.theEntityListWindow.appendData,\ 'on_cancel_button_plugin_selection_clicked' : \ self.theEntityListWindow.closePluginInstanceSelectionWindow,\ } ) self.__initializePluginInstanceSelectonWindow() self[self.__class__.__name__].connect('delete_event', self.theEntityListWindow.closePluginInstanceSelectionWindow ) self.show_all() # ==================================================================== def deleted( self, *arg ): self['PluginInstanceSelection'].hide_all() #self.theEntityListWindow.closePluginInstanceSelectionWindow() return False # ==================================================================== def update( self ): """updates list Returns None """ self.thePluginInstanceListStore.clear() aPluginInstanceList = self.thePluginManager.thePluginTitleDict.keys() for aPluginInstance in aPluginInstanceList: if aPluginInstance.theViewType == MULTIPLE: aPluginInstanceTitle = self.thePluginManager.thePluginTitleDict[aPluginInstance] iter = self.thePluginInstanceListStore.append() self.thePluginInstanceListStore.set_value( iter, 0, aPluginInstanceTitle ) self.thePluginInstanceListStore.set_data( aPluginInstanceTitle, aPluginInstanceTitle ) # ==================================================================== def __initializePluginInstanceSelectonWindow( self ): """initializes PluginInstanceSelectionWindow Returns None """ column = gtk.TreeViewColumn( 'Plugin List', gtk.CellRendererText(), text=0 ) self['plugin_tree'].append_column(column) self.thePluginInstanceListStore=gtk.ListStore( gobject.TYPE_STRING ) self['plugin_tree'].get_selection().set_mode( gtk.SELECTION_MULTIPLE ) self['plugin_tree'].set_model( self.thePluginInstanceListStore ) column = gtk.TreeViewColumn( 'Plugin List', gtk.CellRendererText(), text=0 ) # ======================================================================== def plugin_select_func(self,tree,path,iter): key=self.thePluginInstanceListStore.get_value(iter,0) aTitle = self.thePluginInstanceListStore.get_data( key ) self.theEntityListWindow.theSelectedPluginInstanceList.append( aTitle )
lgpl-3.0
EDUlib/edx-platform
lms/djangoapps/lti_provider/tasks.py
5
3591
""" Asynchronous tasks for the LTI provider app. """ import logging from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from opaque_keys.edx.keys import CourseKey import lms.djangoapps.lti_provider.outcomes as outcomes from lms import CELERY_APP from lms.djangoapps.grades.api import CourseGradeFactory from lms.djangoapps.lti_provider.models import GradedAssignment from xmodule.modulestore.django import modulestore log = logging.getLogger(__name__) @CELERY_APP.task(name='lms.djangoapps.lti_provider.tasks.send_composite_outcome') def send_composite_outcome(user_id, course_id, assignment_id, version): """ Calculate and transmit the score for a composite module (such as a vertical). A composite module may contain multiple problems, so we need to calculate the total points earned and possible for all child problems. This requires calculating the scores for the whole course, which is an expensive operation. Callers should be aware that the score calculation code accesses the latest scores from the database. This can lead to a race condition between a view that updates a user's score and the calculation of the grade. If the Celery task attempts to read the score from the database before the view exits (and its transaction is committed), it will see a stale value. Care should be taken that this task is not triggered until the view exits. The GradedAssignment model has a version_number field that is incremented whenever the score is updated. It is used by this method for two purposes. First, it allows the task to exit if it detects that it has been superseded by another task that will transmit the score for the same assignment. Second, it prevents a race condition where two tasks calculate different scores for a single assignment, and may potentially update the campus LMS in the wrong order. """ assignment = GradedAssignment.objects.get(id=assignment_id) if version != assignment.version_number: log.info( "Score passback for GradedAssignment %s skipped. More recent score available.", assignment.id ) return course_key = CourseKey.from_string(course_id) mapped_usage_key = assignment.usage_key.map_into_course(course_key) user = User.objects.get(id=user_id) course = modulestore().get_course(course_key, depth=0) course_grade = CourseGradeFactory().read(user, course) earned, possible = course_grade.score_for_module(mapped_usage_key) if possible == 0: weighted_score = 0 else: weighted_score = float(earned) / float(possible) assignment = GradedAssignment.objects.get(id=assignment_id) if assignment.version_number == version: outcomes.send_score_update(assignment, weighted_score) @CELERY_APP.task def send_leaf_outcome(assignment_id, points_earned, points_possible): """ Calculate and transmit the score for a single problem. This method assumes that the individual problem was the source of a score update, and so it directly takes the points earned and possible values. As such it does not have to calculate the scores for the course, making this method far faster than send_outcome_for_composite_assignment. """ assignment = GradedAssignment.objects.get(id=assignment_id) if points_possible == 0: weighted_score = 0 else: weighted_score = float(points_earned) / float(points_possible) outcomes.send_score_update(assignment, weighted_score)
agpl-3.0
jturner77/notepad-plus-plus
scintilla/test/ScintillaCallable.py
56
5129
# -*- coding: utf-8 -*- from __future__ import unicode_literals import ctypes, os, sys from ctypes import c_int, c_ulong, c_char_p, c_wchar_p, c_ushort, c_uint, c_long class TEXTRANGE(ctypes.Structure): _fields_= (\ ('cpMin', c_long), ('cpMax', c_long), ('lpstrText', ctypes.POINTER(ctypes.c_char)), ) class FINDTEXT(ctypes.Structure): _fields_= (\ ('cpMin', c_long), ('cpMax', c_long), ('lpstrText', c_char_p), ('cpMinText', c_long), ('cpMaxText', c_long), ) class SciCall: def __init__(self, fn, ptr, msg, stringResult=False): self._fn = fn self._ptr = ptr self._msg = msg self._stringResult = stringResult def __call__(self, w=0, l=0): ww = ctypes.cast(w, c_char_p) if self._stringResult: lengthBytes = self._fn(self._ptr, self._msg, ww, None) if lengthBytes == 0: return bytearray() result = (ctypes.c_byte * lengthBytes)(0) lengthBytes2 = self._fn(self._ptr, self._msg, ww, ctypes.cast(result, c_char_p)) assert lengthBytes == lengthBytes2 return bytearray(result)[:lengthBytes] else: ll = ctypes.cast(l, c_char_p) return self._fn(self._ptr, self._msg, ww, ll) sciFX = ctypes.CFUNCTYPE(c_long, c_char_p, c_int, c_char_p, c_char_p) class ScintillaCallable: def __init__(self, face, scifn, sciptr): self.__dict__["face"] = face self.__dict__["used"] = set() self.__dict__["all"] = set() # The k member is for accessing constants as a dictionary self.__dict__["k"] = {} for f in face.features: self.all.add(f) if face.features[f]["FeatureType"] == "val": self.k[f] = int(self.face.features[f]["Value"], 0) elif face.features[f]["FeatureType"] == "evt": self.k["SCN_"+f] = int(self.face.features[f]["Value"], 0) scifn = sciFX(scifn) self.__dict__["_scifn"] = scifn self.__dict__["_sciptr"] = sciptr def __getattr__(self, name): if name in self.face.features: self.used.add(name) feature = self.face.features[name] value = int(feature["Value"], 0) #~ print("Feature", name, feature) if feature["FeatureType"] == "val": self.__dict__[name] = value return value else: if feature["Param2Type"] == "stringresult" and \ name not in ["GetText", "GetLine", "GetCurLine"]: return SciCall(self._scifn, self._sciptr, value, True) else: return SciCall(self._scifn, self._sciptr, value) elif ("Get" + name) in self.face.features: self.used.add("Get" + name) feature = self.face.features["Get" + name] value = int(feature["Value"], 0) if feature["FeatureType"] == "get" and \ not name.startswith("Get") and \ not feature["Param1Type"] and \ not feature["Param2Type"] and \ feature["ReturnType"] in ["bool", "int", "position"]: #~ print("property", feature) return self._scifn(self._sciptr, value, None, None) elif name.startswith("SCN_") and name in self.k: self.used.add(name) feature = self.face.features[name[4:]] value = int(feature["Value"], 0) #~ print("Feature", name, feature) if feature["FeatureType"] == "val": return value raise AttributeError(name) def __setattr__(self, name, val): if ("Set" + name) in self.face.features: self.used.add("Set" + name) feature = self.face.features["Set" + name] value = int(feature["Value"], 0) #~ print("setproperty", feature) if feature["FeatureType"] == "set" and not name.startswith("Set"): if feature["Param1Type"] in ["bool", "int", "position"]: return self._scifn(self._sciptr, value, c_char_p(val), None) elif feature["Param2Type"] in ["string"]: return self._scifn(self._sciptr, value, None, c_char_p(val)) raise AttributeError(name) raise AttributeError(name) def getvalue(self, name): if name in self.face.features: feature = self.face.features[name] if feature["FeatureType"] != "evt": try: return int(feature["Value"], 0) except ValueError: return -1 return -1 def ByteRange(self, start, end): tr = TEXTRANGE() tr.cpMin = start tr.cpMax = end length = end - start tr.lpstrText = ctypes.create_string_buffer(length + 1) self.GetTextRange(0, ctypes.byref(tr)) text = tr.lpstrText[:length] text += b"\0" * (length - len(text)) return text def StyledTextRange(self, start, end): tr = TEXTRANGE() tr.cpMin = start tr.cpMax = end length = 2 * (end - start) tr.lpstrText = ctypes.create_string_buffer(length + 2) self.GetStyledText(0, ctypes.byref(tr)) styledText = tr.lpstrText[:length] styledText += b"\0" * (length - len(styledText)) return styledText def FindBytes(self, start, end, s, flags): ft = FINDTEXT() ft.cpMin = start ft.cpMax = end ft.lpstrText = s ft.cpMinText = 0 ft.cpMaxText = 0 pos = self.FindText(flags, ctypes.byref(ft)) #~ print(start, end, ft.cpMinText, ft.cpMaxText) return pos def Contents(self): return self.ByteRange(0, self.Length) def SetContents(self, s): self.TargetStart = 0 self.TargetEnd = self.Length self.ReplaceTarget(len(s), s)
gpl-2.0
LukeM12/samba
lib/dnspython/tests/bugs.py
56
1782
# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import unittest import dns.rdata import dns.rdataclass import dns.rdatatype import dns.ttl class BugsTestCase(unittest.TestCase): def test_float_LOC(self): rdata = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.LOC, "30 30 0.000 N 100 30 0.000 W 10.00m 20m 2000m 20m") self.failUnless(rdata.float_latitude == 30.5) self.failUnless(rdata.float_longitude == -100.5) def test_SOA_BIND8_TTL(self): rdata1 = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.SOA, "a b 100 1s 1m 1h 1d") rdata2 = dns.rdata.from_text(dns.rdataclass.IN, dns.rdatatype.SOA, "a b 100 1 60 3600 86400") self.failUnless(rdata1 == rdata2) def test_TTL_bounds_check(self): def bad(): ttl = dns.ttl.from_text("2147483648") self.failUnlessRaises(dns.ttl.BadTTL, bad) if __name__ == '__main__': unittest.main()
gpl-3.0
tinloaf/home-assistant
tests/components/image_processing/test_init.py
6
10498
"""The tests for the image_processing component.""" from unittest.mock import patch, PropertyMock from homeassistant.core import callback from homeassistant.const import ATTR_ENTITY_PICTURE from homeassistant.setup import setup_component from homeassistant.exceptions import HomeAssistantError import homeassistant.components.http as http import homeassistant.components.image_processing as ip from tests.common import ( get_test_home_assistant, get_test_instance_port, assert_setup_component) from tests.components.image_processing import common class TestSetupImageProcessing: """Test class for setup image processing.""" def setup_method(self): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() def teardown_method(self): """Stop everything that was started.""" self.hass.stop() def test_setup_component(self): """Set up demo platform on image_process component.""" config = { ip.DOMAIN: { 'platform': 'demo' } } with assert_setup_component(1, ip.DOMAIN): setup_component(self.hass, ip.DOMAIN, config) def test_setup_component_with_service(self): """Set up demo platform on image_process component test service.""" config = { ip.DOMAIN: { 'platform': 'demo' } } with assert_setup_component(1, ip.DOMAIN): setup_component(self.hass, ip.DOMAIN, config) assert self.hass.services.has_service(ip.DOMAIN, 'scan') class TestImageProcessing: """Test class for image processing.""" def setup_method(self): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() setup_component( self.hass, http.DOMAIN, {http.DOMAIN: {http.CONF_SERVER_PORT: get_test_instance_port()}}) config = { ip.DOMAIN: { 'platform': 'test' }, 'camera': { 'platform': 'demo' }, } setup_component(self.hass, ip.DOMAIN, config) state = self.hass.states.get('camera.demo_camera') self.url = "{0}{1}".format( self.hass.config.api.base_url, state.attributes.get(ATTR_ENTITY_PICTURE)) def teardown_method(self): """Stop everything that was started.""" self.hass.stop() @patch('homeassistant.components.camera.demo.DemoCamera.camera_image', autospec=True, return_value=b'Test') def test_get_image_from_camera(self, mock_camera): """Grab an image from camera entity.""" self.hass.start() common.scan(self.hass, entity_id='image_processing.test') self.hass.block_till_done() state = self.hass.states.get('image_processing.test') assert mock_camera.called assert state.state == '1' assert state.attributes['image'] == b'Test' @patch('homeassistant.components.camera.async_get_image', side_effect=HomeAssistantError()) def test_get_image_without_exists_camera(self, mock_image): """Try to get image without exists camera.""" self.hass.states.remove('camera.demo_camera') common.scan(self.hass, entity_id='image_processing.test') self.hass.block_till_done() state = self.hass.states.get('image_processing.test') assert mock_image.called assert state.state == '0' class TestImageProcessingAlpr: """Test class for alpr image processing.""" def setup_method(self): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() config = { ip.DOMAIN: { 'platform': 'demo' }, 'camera': { 'platform': 'demo' }, } with patch('homeassistant.components.image_processing.demo.' 'DemoImageProcessingAlpr.should_poll', new_callable=PropertyMock(return_value=False)): setup_component(self.hass, ip.DOMAIN, config) state = self.hass.states.get('camera.demo_camera') self.url = "{0}{1}".format( self.hass.config.api.base_url, state.attributes.get(ATTR_ENTITY_PICTURE)) self.alpr_events = [] @callback def mock_alpr_event(event): """Mock event.""" self.alpr_events.append(event) self.hass.bus.listen('image_processing.found_plate', mock_alpr_event) def teardown_method(self): """Stop everything that was started.""" self.hass.stop() def test_alpr_event_single_call(self, aioclient_mock): """Set up and scan a picture and test plates from event.""" aioclient_mock.get(self.url, content=b'image') common.scan(self.hass, entity_id='image_processing.demo_alpr') self.hass.block_till_done() state = self.hass.states.get('image_processing.demo_alpr') assert len(self.alpr_events) == 4 assert state.state == 'AC3829' event_data = [event.data for event in self.alpr_events if event.data.get('plate') == 'AC3829'] assert len(event_data) == 1 assert event_data[0]['plate'] == 'AC3829' assert event_data[0]['confidence'] == 98.3 assert event_data[0]['entity_id'] == 'image_processing.demo_alpr' def test_alpr_event_double_call(self, aioclient_mock): """Set up and scan a picture and test plates from event.""" aioclient_mock.get(self.url, content=b'image') common.scan(self.hass, entity_id='image_processing.demo_alpr') common.scan(self.hass, entity_id='image_processing.demo_alpr') self.hass.block_till_done() state = self.hass.states.get('image_processing.demo_alpr') assert len(self.alpr_events) == 4 assert state.state == 'AC3829' event_data = [event.data for event in self.alpr_events if event.data.get('plate') == 'AC3829'] assert len(event_data) == 1 assert event_data[0]['plate'] == 'AC3829' assert event_data[0]['confidence'] == 98.3 assert event_data[0]['entity_id'] == 'image_processing.demo_alpr' @patch('homeassistant.components.image_processing.demo.' 'DemoImageProcessingAlpr.confidence', new_callable=PropertyMock(return_value=95)) def test_alpr_event_single_call_confidence(self, confidence_mock, aioclient_mock): """Set up and scan a picture and test plates from event.""" aioclient_mock.get(self.url, content=b'image') common.scan(self.hass, entity_id='image_processing.demo_alpr') self.hass.block_till_done() state = self.hass.states.get('image_processing.demo_alpr') assert len(self.alpr_events) == 2 assert state.state == 'AC3829' event_data = [event.data for event in self.alpr_events if event.data.get('plate') == 'AC3829'] assert len(event_data) == 1 assert event_data[0]['plate'] == 'AC3829' assert event_data[0]['confidence'] == 98.3 assert event_data[0]['entity_id'] == 'image_processing.demo_alpr' class TestImageProcessingFace: """Test class for face image processing.""" def setup_method(self): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() config = { ip.DOMAIN: { 'platform': 'demo' }, 'camera': { 'platform': 'demo' }, } with patch('homeassistant.components.image_processing.demo.' 'DemoImageProcessingFace.should_poll', new_callable=PropertyMock(return_value=False)): setup_component(self.hass, ip.DOMAIN, config) state = self.hass.states.get('camera.demo_camera') self.url = "{0}{1}".format( self.hass.config.api.base_url, state.attributes.get(ATTR_ENTITY_PICTURE)) self.face_events = [] @callback def mock_face_event(event): """Mock event.""" self.face_events.append(event) self.hass.bus.listen('image_processing.detect_face', mock_face_event) def teardown_method(self): """Stop everything that was started.""" self.hass.stop() def test_face_event_call(self, aioclient_mock): """Set up and scan a picture and test faces from event.""" aioclient_mock.get(self.url, content=b'image') common.scan(self.hass, entity_id='image_processing.demo_face') self.hass.block_till_done() state = self.hass.states.get('image_processing.demo_face') assert len(self.face_events) == 2 assert state.state == 'Hans' assert state.attributes['total_faces'] == 4 event_data = [event.data for event in self.face_events if event.data.get('name') == 'Hans'] assert len(event_data) == 1 assert event_data[0]['name'] == 'Hans' assert event_data[0]['confidence'] == 98.34 assert event_data[0]['gender'] == 'male' assert event_data[0]['entity_id'] == \ 'image_processing.demo_face' @patch('homeassistant.components.image_processing.demo.' 'DemoImageProcessingFace.confidence', new_callable=PropertyMock(return_value=None)) def test_face_event_call_no_confidence(self, mock_config, aioclient_mock): """Set up and scan a picture and test faces from event.""" aioclient_mock.get(self.url, content=b'image') common.scan(self.hass, entity_id='image_processing.demo_face') self.hass.block_till_done() state = self.hass.states.get('image_processing.demo_face') assert len(self.face_events) == 3 assert state.state == '4' assert state.attributes['total_faces'] == 4 event_data = [event.data for event in self.face_events if event.data.get('name') == 'Hans'] assert len(event_data) == 1 assert event_data[0]['name'] == 'Hans' assert event_data[0]['confidence'] == 98.34 assert event_data[0]['gender'] == 'male' assert event_data[0]['entity_id'] == \ 'image_processing.demo_face'
apache-2.0
Diyago/Machine-Learning-scripts
DEEP LEARNING/segmentation/Severstal-Steel-Defect-Detection-master/common_blocks/new_metrics.py
1
15642
from functools import partial import numpy as np import torch from catalyst.dl import Callback, RunnerState, MetricCallback, CallbackOrder from pytorch_toolbelt.utils.catalyst.visualization import get_tensorboard_logger from pytorch_toolbelt.utils.torch_utils import to_numpy from pytorch_toolbelt.utils.visualization import ( render_figure_to_tensor, plot_confusion_matrix, ) from sklearn.metrics import f1_score, multilabel_confusion_matrix __all__ = [ "pixel_accuracy", "binary_dice_iou_score", "multiclass_dice_iou_score", "multilabel_dice_iou_score", "PixelAccuracyCallback", "MacroF1Callback", "ConfusionMatrixCallback", "IoUMetricsCallback", ] BINARY_MODE = "binary" MULTICLASS_MODE = "multiclass" MULTILABEL_MODE = "multilabel" def pixel_accuracy(outputs: torch.Tensor, targets: torch.Tensor, ignore_index=None): """ Compute the pixel accuracy """ outputs = outputs.detach() targets = targets.detach() if ignore_index is not None: mask = targets != ignore_index outputs = outputs[mask] targets = targets[mask] outputs = (outputs > 0).float() correct = float(torch.sum(outputs == targets)) total = targets.numel() return correct / total class PixelAccuracyCallback(MetricCallback): """Pixel accuracy metric callback """ def __init__( self, input_key: str = "targets", output_key: str = "logits", prefix: str = "accuracy", ignore_index=None, ): """ :param input_key: input key to use for iou calculation; specifies our `y_true`. :param output_key: output key to use for iou calculation; specifies our `y_pred` :param ignore_index: same meaning as in nn.CrossEntropyLoss """ super().__init__( prefix=prefix, metric_fn=partial(pixel_accuracy, ignore_index=ignore_index), input_key=input_key, output_key=output_key, ) class ConfusionMatrixCallback(Callback): """ Compute and log confusion matrix to Tensorboard. For use with Multiclass classification/segmentation. """ def __init__( self, input_key: str = "targets", output_key: str = "logits", prefix: str = "confusion_matrix", class_names=None, ignore_index=None, ): """ :param input_key: input key to use for precision calculation; specifies our `y_true`. :param output_key: output key to use for precision calculation; specifies our `y_pred`. :param ignore_index: same meaning as in nn.CrossEntropyLoss """ super().__init__(CallbackOrder.Logger) self.prefix = prefix self.class_names = class_names self.output_key = output_key self.input_key = input_key self.outputs = [] self.targets = [] self.ignore_index = ignore_index def on_loader_start(self, state): self.outputs = [] self.targets = [] def on_batch_end(self, state: RunnerState): outputs = to_numpy(torch.sigmoid(state.output[self.output_key])) targets = to_numpy(state.input[self.input_key]) # outputs = 1*(outputs>0.5) # targets = np.argmax(targets, axis=1) if self.ignore_index is not None: mask = targets != self.ignore_index outputs = outputs[mask] targets = targets[mask] self.outputs.extend(outputs) self.targets.extend(targets) def on_loader_end(self, state): targets = np.array(self.targets) outputs = np.array(self.outputs) if self.class_names is None: class_names = [str(i) for i in range(targets.shape[1])] else: class_names = self.class_names num_classes = len(class_names) best_score = 0 best_th = 0 best_fsores = {c: 0 for c in range(num_classes)} best_fsores_th = {} for th in np.linspace(0, 1, 41): cm = multilabel_confusion_matrix( targets, outputs > th, labels=range(num_classes) ) for c in range(num_classes): tn, fp, fn, tp = cm[c].ravel() if (tp + fp) == 0: precision = 0 else: precision = tp / (tp + fp) if (tp + fn) == 0: recall = 0 else: recall = tp / (tp + fn) if precision == 0 or recall == 0: fscore = 0 else: fscore = 2 * (precision * recall / (precision + recall)) if best_fsores[c] < fscore: best_fsores_th[c] = th state.metrics.epoch_values[state.loader_name][ str(c) + "_precision_best" ] = precision state.metrics.epoch_values[state.loader_name][ str(c) + "_recall_best" ] = recall state.metrics.epoch_values[state.loader_name][ str(c) + "_fscore_best" ] = fscore state.metrics.epoch_values[state.loader_name][ str(c) + "_fscore_best_th" ] = th best_fsores[c] = fscore state.metrics.epoch_values[state.loader_name]["fscore_macro_best"] = np.mean( [best_fsores[i] for i in best_fsores] ) cm = multilabel_confusion_matrix( targets, outputs > 0.5, labels=range(num_classes) ) for c in range(num_classes): tn, fp, fn, tp = cm[c].ravel() if (tp + fp) == 0: precision = 0 else: precision = tp / (tp + fp) if (tp + fn) == 0: recall = 0 else: recall = tp / (tp + fn) if precision == 0 or recall == 0: fscore = 0 else: fscore = 2 * (precision * recall / (precision + recall)) state.metrics.epoch_values[state.loader_name][ str(c) + "_precision_05" ] = precision state.metrics.epoch_values[state.loader_name][ str(c) + "_recall_05" ] = recall state.metrics.epoch_values[state.loader_name][ str(c) + "_fscore_05" ] = fscore # logger = get_tensorboard_logger(state) # logger.add_image(f"{self.prefix}/epoch", fig, global_step=state.step) class MacroF1Callback(Callback): """ Compute F1-macro metric """ def __init__( self, input_key: str = "targets", output_key: str = "logits", prefix: str = "macro_f1", ignore_index=None, ): """ :param input_key: input key to use for precision calculation; specifies our `y_true`. :param output_key: output key to use for precision calculation; specifies our `y_pred`. """ super().__init__(CallbackOrder.Metric) self.metric_fn = lambda outputs, targets: f1_score( targets, outputs, average="macro" ) self.prefix = prefix self.output_key = output_key self.input_key = input_key self.outputs = [] self.targets = [] self.ignore_index = ignore_index def on_batch_end(self, state: RunnerState): outputs = to_numpy(torch.sigmoid(state.output[self.output_key])) targets = to_numpy(state.input[self.input_key]) num_classes = outputs.shape[1] outputs = 1 * (outputs > 0.5) # targets = np.argmax(targets, axis=1) if self.ignore_index is not None: mask = targets != self.ignore_index outputs = outputs[mask] targets = targets[mask] # outputs = [np.eye(num_classes)[y] for y in outputs] # targets = [np.eye(num_classes)[y] for y in targets] self.outputs.extend(outputs) self.targets.extend(targets) # metric = self.metric_fn(self.targets, self.outputs) # state.metrics.add_batch_value(name=self.prefix, value=metric) def on_loader_start(self, state): self.outputs = [] self.targets = [] def on_loader_end(self, state): metric_name = self.prefix targets = np.array(self.targets) outputs = np.array(self.outputs) metric = self.metric_fn(outputs, targets) state.metrics.epoch_values[state.loader_name][metric_name] = metric def binary_dice_iou_score( y_pred: torch.Tensor, y_true: torch.Tensor, mode="dice", threshold=None, nan_score_on_empty=False, eps=1e-7, ) -> float: """ Compute IoU score between two image tensors :param y_pred: Input image tensor of any shape :param y_true: Target image of any shape (must match size of y_pred) :param mode: Metric to compute (dice, iou) :param threshold: Optional binarization threshold to apply on @y_pred :param nan_score_on_empty: If true, return np.nan if target has no positive pixels; If false, return 1. if both target and input are empty, and 0 otherwise. :param eps: Small value to add to denominator for numerical stability :return: Float scalar """ assert mode in {"dice", "iou"} # Binarize predictions if threshold is not None: y_pred = (y_pred > threshold).to(y_true.dtype) intersection = torch.sum(y_pred * y_true).item() cardinality = (torch.sum(y_pred) + torch.sum(y_true)).item() if mode == "dice": score = (2.0 * intersection) / (cardinality + eps) else: score = intersection / (cardinality + eps) has_targets = torch.sum(y_true) > 0 has_predicted = torch.sum(y_pred) > 0 if not has_targets: if nan_score_on_empty: score = np.nan else: score = float(not has_predicted) return score def multiclass_dice_iou_score( y_pred: torch.Tensor, y_true: torch.Tensor, mode="dice", threshold=None, eps=1e-7, nan_score_on_empty=False, classes_of_interest=None, ): ious = [] num_classes = y_pred.size(0) y_pred = y_pred.argmax(dim=0) if classes_of_interest is None: classes_of_interest = range(num_classes) for class_index in classes_of_interest: iou = binary_dice_iou_score( y_pred=(y_pred == class_index).float(), y_true=(y_true == class_index).float(), mode=mode, nan_score_on_empty=nan_score_on_empty, threshold=threshold, eps=eps, ) ious.append(iou) return ious def multilabel_dice_iou_score( y_true: torch.Tensor, y_pred: torch.Tensor, mode="dice", threshold=None, eps=1e-7, nan_score_on_empty=False, classes_of_interest=None, ): ious = [] num_classes = y_pred.size(0) if classes_of_interest is None: classes_of_interest = range(num_classes) for class_index in classes_of_interest: iou = binary_dice_iou_score( y_pred=y_pred[class_index], y_true=y_true[class_index], mode=mode, threshold=threshold, nan_score_on_empty=nan_score_on_empty, eps=eps, ) ious.append(iou) return ious class IoUMetricsCallback(Callback): """ A metric callback for computing either Dice or Jaccard metric which is computed across whole epoch, not per-batch. """ def __init__( self, mode: str, metric="dice", class_names=None, classes_of_interest=None, input_key: str = "targets", output_key: str = "logits", nan_score_on_empty=True, prefix: str = None, ): """ :param mode: One of: 'binary', 'multiclass', 'multilabel'. :param input_key: input key to use for precision calculation; specifies our `y_true`. :param output_key: output key to use for precision calculation; specifies our `y_pred`. :param accuracy_for_empty: """ super().__init__(CallbackOrder.Metric) assert mode in {BINARY_MODE, MULTILABEL_MODE, MULTICLASS_MODE} if prefix is None: prefix = metric if classes_of_interest is not None: if classes_of_interest.dtype == np.bool: num_classes = len(classes_of_interest) classes_of_interest = np.arange(num_classes)[classes_of_interest] if class_names is not None: if len(class_names) != len(classes_of_interest): raise ValueError( "Length of 'classes_of_interest' must be equal to length of 'classes_of_interest'" ) self.mode = mode self.prefix = prefix self.output_key = output_key self.input_key = input_key self.class_names = class_names self.classes_of_interest = classes_of_interest self.scores = [] if self.mode == BINARY_MODE: self.score_fn = partial( binary_dice_iou_score, threshold=0.0, nan_score_on_empty=nan_score_on_empty, mode=metric, ) if self.mode == MULTICLASS_MODE: self.score_fn = partial( multiclass_dice_iou_score, mode=metric, threshold=0.0, nan_score_on_empty=nan_score_on_empty, classes_of_interest=self.classes_of_interest, ) if self.mode == MULTILABEL_MODE: self.score_fn = partial( multilabel_dice_iou_score, mode=metric, threshold=0.5, nan_score_on_empty=nan_score_on_empty, classes_of_interest=self.classes_of_interest, ) def on_loader_start(self, state): self.scores = [] @torch.no_grad() def on_batch_end(self, state: RunnerState): outputs = state.output[self.output_key].detach() targets = state.input[self.input_key].detach() batch_size = targets.size(0) score_per_image = [] for image_index in range(batch_size): score_per_class = self.score_fn( y_pred=outputs[image_index], y_true=targets[image_index] ) score_per_image.append(score_per_class) mean_score = np.nanmean(score_per_image) state.metrics.add_batch_value(self.prefix, float(mean_score)) self.scores.extend(score_per_image) def on_loader_end(self, state): scores = np.array(self.scores) mean_score = np.nanmean(scores) state.metrics.epoch_values[state.loader_name][self.prefix] = float(mean_score) # Log additional IoU scores per class if self.mode in {MULTICLASS_MODE, MULTILABEL_MODE}: num_classes = scores.shape[1] class_names = self.class_names if class_names is None: class_names = [f"class_{i}" for i in range(num_classes)] scores_per_class = np.nanmean(scores, axis=0) for class_name, score_per_class in zip(class_names, scores_per_class): state.metrics.epoch_values[state.loader_name][ self.prefix + "_" + class_name ] = float(score_per_class)
apache-2.0
iconmix/skins-addons
script.iconmixtools/resources/lib/unidecode/x6d.py
252
4651
data = ( 'Zhou ', # 0x00 'Ji ', # 0x01 'Yi ', # 0x02 'Hui ', # 0x03 'Hui ', # 0x04 'Zui ', # 0x05 'Cheng ', # 0x06 'Yin ', # 0x07 'Wei ', # 0x08 'Hou ', # 0x09 'Jian ', # 0x0a 'Yang ', # 0x0b 'Lie ', # 0x0c 'Si ', # 0x0d 'Ji ', # 0x0e 'Er ', # 0x0f 'Xing ', # 0x10 'Fu ', # 0x11 'Sa ', # 0x12 'Suo ', # 0x13 'Zhi ', # 0x14 'Yin ', # 0x15 'Wu ', # 0x16 'Xi ', # 0x17 'Kao ', # 0x18 'Zhu ', # 0x19 'Jiang ', # 0x1a 'Luo ', # 0x1b '[?] ', # 0x1c 'An ', # 0x1d 'Dong ', # 0x1e 'Yi ', # 0x1f 'Mou ', # 0x20 'Lei ', # 0x21 'Yi ', # 0x22 'Mi ', # 0x23 'Quan ', # 0x24 'Jin ', # 0x25 'Mo ', # 0x26 'Wei ', # 0x27 'Xiao ', # 0x28 'Xie ', # 0x29 'Hong ', # 0x2a 'Xu ', # 0x2b 'Shuo ', # 0x2c 'Kuang ', # 0x2d 'Tao ', # 0x2e 'Qie ', # 0x2f 'Ju ', # 0x30 'Er ', # 0x31 'Zhou ', # 0x32 'Ru ', # 0x33 'Ping ', # 0x34 'Xun ', # 0x35 'Xiong ', # 0x36 'Zhi ', # 0x37 'Guang ', # 0x38 'Huan ', # 0x39 'Ming ', # 0x3a 'Huo ', # 0x3b 'Wa ', # 0x3c 'Qia ', # 0x3d 'Pai ', # 0x3e 'Wu ', # 0x3f 'Qu ', # 0x40 'Liu ', # 0x41 'Yi ', # 0x42 'Jia ', # 0x43 'Jing ', # 0x44 'Qian ', # 0x45 'Jiang ', # 0x46 'Jiao ', # 0x47 'Cheng ', # 0x48 'Shi ', # 0x49 'Zhuo ', # 0x4a 'Ce ', # 0x4b 'Pal ', # 0x4c 'Kuai ', # 0x4d 'Ji ', # 0x4e 'Liu ', # 0x4f 'Chan ', # 0x50 'Hun ', # 0x51 'Hu ', # 0x52 'Nong ', # 0x53 'Xun ', # 0x54 'Jin ', # 0x55 'Lie ', # 0x56 'Qiu ', # 0x57 'Wei ', # 0x58 'Zhe ', # 0x59 'Jun ', # 0x5a 'Han ', # 0x5b 'Bang ', # 0x5c 'Mang ', # 0x5d 'Zhuo ', # 0x5e 'You ', # 0x5f 'Xi ', # 0x60 'Bo ', # 0x61 'Dou ', # 0x62 'Wan ', # 0x63 'Hong ', # 0x64 'Yi ', # 0x65 'Pu ', # 0x66 'Ying ', # 0x67 'Lan ', # 0x68 'Hao ', # 0x69 'Lang ', # 0x6a 'Han ', # 0x6b 'Li ', # 0x6c 'Geng ', # 0x6d 'Fu ', # 0x6e 'Wu ', # 0x6f 'Lian ', # 0x70 'Chun ', # 0x71 'Feng ', # 0x72 'Yi ', # 0x73 'Yu ', # 0x74 'Tong ', # 0x75 'Lao ', # 0x76 'Hai ', # 0x77 'Jin ', # 0x78 'Jia ', # 0x79 'Chong ', # 0x7a 'Weng ', # 0x7b 'Mei ', # 0x7c 'Sui ', # 0x7d 'Cheng ', # 0x7e 'Pei ', # 0x7f 'Xian ', # 0x80 'Shen ', # 0x81 'Tu ', # 0x82 'Kun ', # 0x83 'Pin ', # 0x84 'Nie ', # 0x85 'Han ', # 0x86 'Jing ', # 0x87 'Xiao ', # 0x88 'She ', # 0x89 'Nian ', # 0x8a 'Tu ', # 0x8b 'Yong ', # 0x8c 'Xiao ', # 0x8d 'Xian ', # 0x8e 'Ting ', # 0x8f 'E ', # 0x90 'Su ', # 0x91 'Tun ', # 0x92 'Juan ', # 0x93 'Cen ', # 0x94 'Ti ', # 0x95 'Li ', # 0x96 'Shui ', # 0x97 'Si ', # 0x98 'Lei ', # 0x99 'Shui ', # 0x9a 'Tao ', # 0x9b 'Du ', # 0x9c 'Lao ', # 0x9d 'Lai ', # 0x9e 'Lian ', # 0x9f 'Wei ', # 0xa0 'Wo ', # 0xa1 'Yun ', # 0xa2 'Huan ', # 0xa3 'Di ', # 0xa4 '[?] ', # 0xa5 'Run ', # 0xa6 'Jian ', # 0xa7 'Zhang ', # 0xa8 'Se ', # 0xa9 'Fu ', # 0xaa 'Guan ', # 0xab 'Xing ', # 0xac 'Shou ', # 0xad 'Shuan ', # 0xae 'Ya ', # 0xaf 'Chuo ', # 0xb0 'Zhang ', # 0xb1 'Ye ', # 0xb2 'Kong ', # 0xb3 'Wo ', # 0xb4 'Han ', # 0xb5 'Tuo ', # 0xb6 'Dong ', # 0xb7 'He ', # 0xb8 'Wo ', # 0xb9 'Ju ', # 0xba 'Gan ', # 0xbb 'Liang ', # 0xbc 'Hun ', # 0xbd 'Ta ', # 0xbe 'Zhuo ', # 0xbf 'Dian ', # 0xc0 'Qie ', # 0xc1 'De ', # 0xc2 'Juan ', # 0xc3 'Zi ', # 0xc4 'Xi ', # 0xc5 'Yao ', # 0xc6 'Qi ', # 0xc7 'Gu ', # 0xc8 'Guo ', # 0xc9 'Han ', # 0xca 'Lin ', # 0xcb 'Tang ', # 0xcc 'Zhou ', # 0xcd 'Peng ', # 0xce 'Hao ', # 0xcf 'Chang ', # 0xd0 'Shu ', # 0xd1 'Qi ', # 0xd2 'Fang ', # 0xd3 'Chi ', # 0xd4 'Lu ', # 0xd5 'Nao ', # 0xd6 'Ju ', # 0xd7 'Tao ', # 0xd8 'Cong ', # 0xd9 'Lei ', # 0xda 'Zhi ', # 0xdb 'Peng ', # 0xdc 'Fei ', # 0xdd 'Song ', # 0xde 'Tian ', # 0xdf 'Pi ', # 0xe0 'Dan ', # 0xe1 'Yu ', # 0xe2 'Ni ', # 0xe3 'Yu ', # 0xe4 'Lu ', # 0xe5 'Gan ', # 0xe6 'Mi ', # 0xe7 'Jing ', # 0xe8 'Ling ', # 0xe9 'Lun ', # 0xea 'Yin ', # 0xeb 'Cui ', # 0xec 'Qu ', # 0xed 'Huai ', # 0xee 'Yu ', # 0xef 'Nian ', # 0xf0 'Shen ', # 0xf1 'Piao ', # 0xf2 'Chun ', # 0xf3 'Wa ', # 0xf4 'Yuan ', # 0xf5 'Lai ', # 0xf6 'Hun ', # 0xf7 'Qing ', # 0xf8 'Yan ', # 0xf9 'Qian ', # 0xfa 'Tian ', # 0xfb 'Miao ', # 0xfc 'Zhi ', # 0xfd 'Yin ', # 0xfe 'Mi ', # 0xff )
gpl-3.0
patrikpettersson/rest-engine
lib/aniso8601/tests/test_interval.py
3
6080
# -*- coding: utf-8 -*- # Copyright (c) 2014, Brandon Nielsen # All rights reserved. # # This software may be modified and distributed under the terms # of the BSD license. See the LICENSE file for details. import unittest import datetime from aniso8601.interval import parse_interval, parse_repeating_interval class TestIntervalFunctions(unittest.TestCase): def test_parse_interval(self): resultinterval = parse_interval('P1M/1981-04-05T01:01:00') self.assertEqual(resultinterval[0], datetime.datetime(year=1981, month=4, day=5, hour=1, minute=1)) self.assertEqual(resultinterval[1], datetime.datetime(year=1981, month=3, day=6, hour=1, minute=1)) resultinterval = parse_interval('P1M/1981-04-05') self.assertEqual(resultinterval[0], datetime.date(year=1981, month=4, day=5)) self.assertEqual(resultinterval[1], datetime.date(year=1981, month=3, day=6)) resultinterval = parse_interval('PT1H/2014-11-12') self.assertEqual(resultinterval[0], datetime.date(year=2014, month=11, day=12)) self.assertEqual(resultinterval[1], datetime.datetime(year=2014, month=11, day=11, hour=23)) resultinterval = parse_interval('PT4H54M6.5S/2014-11-12') self.assertEqual(resultinterval[0], datetime.date(year=2014, month=11, day=12)) self.assertEqual(resultinterval[1], datetime.datetime(year=2014, month=11, day=11, hour=19, minute=5, second=53, microsecond=500000)) resultinterval = parse_interval('1981-04-05T01:01:00/P1M1DT1M') self.assertEqual(resultinterval[0], datetime.datetime(year=1981, month=4, day=5, hour=1, minute=1)) self.assertEqual(resultinterval[1], datetime.datetime(year=1981, month=5, day=6, hour=1, minute=2)) resultinterval = parse_interval('1981-04-05/P1M1D') self.assertEqual(resultinterval[0], datetime.date(year=1981, month=4, day=5)) self.assertEqual(resultinterval[1], datetime.date(year=1981, month=5, day=6)) resultinterval = parse_interval('2014-11-12/PT1H') self.assertEqual(resultinterval[0], datetime.date(year=2014, month=11, day=12)) self.assertEqual(resultinterval[1], datetime.datetime(year=2014, month=11, day=12, hour=1, minute=0)) resultinterval = parse_interval('2014-11-12/PT4H54M6.5S') self.assertEqual(resultinterval[0], datetime.date(year=2014, month=11, day=12)) self.assertEqual(resultinterval[1], datetime.datetime(year=2014, month=11, day=12, hour=4, minute=54, second=6, microsecond=500000)) resultinterval = parse_interval('1980-03-05T01:01:00/1981-04-05T01:01:00') self.assertEqual(resultinterval[0], datetime.datetime(year=1980, month=3, day=5, hour=1, minute=1)) self.assertEqual(resultinterval[1], datetime.datetime(year=1981, month=4, day=5, hour=1, minute=1)) resultinterval = parse_interval('1980-03-05T01:01:00/1981-04-05') self.assertEqual(resultinterval[0], datetime.datetime(year=1980, month=3, day=5, hour=1, minute=1)) self.assertEqual(resultinterval[1], datetime.date(year=1981, month=4, day=5)) resultinterval = parse_interval('1980-03-05/1981-04-05T01:01:00') self.assertEqual(resultinterval[0], datetime.date(year=1980, month=3, day=5)) self.assertEqual(resultinterval[1], datetime.datetime(year=1981, month=4, day=5, hour=1, minute=1)) resultinterval = parse_interval('1980-03-05/1981-04-05') self.assertEqual(resultinterval[0], datetime.date(year=1980, month=3, day=5)) self.assertEqual(resultinterval[1], datetime.date(year=1981, month=4, day=5)) resultinterval = parse_interval('1981-04-05/1980-03-05') self.assertEqual(resultinterval[0], datetime.date(year=1981, month=4, day=5)) self.assertEqual(resultinterval[1], datetime.date(year=1980, month=3, day=5)) resultinterval = parse_interval('1980-03-05T01:01:00--1981-04-05T01:01:00', intervaldelimiter='--') self.assertEqual(resultinterval[0], datetime.datetime(year=1980, month=3, day=5, hour=1, minute=1)) self.assertEqual(resultinterval[1], datetime.datetime(year=1981, month=4, day=5, hour=1, minute=1)) resultinterval = parse_interval('1980-03-05 01:01:00/1981-04-05 01:01:00', datetimedelimiter=' ') self.assertEqual(resultinterval[0], datetime.datetime(year=1980, month=3, day=5, hour=1, minute=1)) self.assertEqual(resultinterval[1], datetime.datetime(year=1981, month=4, day=5, hour=1, minute=1)) def test_parse_repeating_interval(self): results = list(parse_repeating_interval('R3/1981-04-05/P1D')) self.assertEqual(results[0], datetime.date(year=1981, month=4, day=5)) self.assertEqual(results[1], datetime.date(year=1981, month=4, day=6)) self.assertEqual(results[2], datetime.date(year=1981, month=4, day=7)) results = list(parse_repeating_interval('R11/PT1H2M/1980-03-05T01:01:00')) for dateindex in range(0, 11): self.assertEqual(results[dateindex], datetime.datetime(year=1980, month=3, day=5, hour=1, minute=1) - dateindex * datetime.timedelta(hours=1, minutes=2)) results = list(parse_repeating_interval('R2--1980-03-05T01:01:00--1981-04-05T01:01:00', intervaldelimiter='--')) self.assertEqual(results[0], datetime.datetime(year=1980, month=3, day=5, hour=1, minute=1)) self.assertEqual(results[1], datetime.datetime(year=1981, month=4, day=5, hour=1, minute=1)) results = list(parse_repeating_interval('R2/1980-03-05 01:01:00/1981-04-05 01:01:00', datetimedelimiter=' ')) self.assertEqual(results[0], datetime.datetime(year=1980, month=3, day=5, hour=1, minute=1)) self.assertEqual(results[1], datetime.datetime(year=1981, month=4, day=5, hour=1, minute=1)) resultgenerator = parse_repeating_interval('R/PT1H2M/1980-03-05T01:01:00') for dateindex in range(0, 11): self.assertEqual(next(resultgenerator), datetime.datetime(year=1980, month=3, day=5, hour=1, minute=1) - dateindex * datetime.timedelta(hours=1, minutes=2))
mit
justinlulejian/fah-gae
lib/google/api/monitoring_pb2.py
17
4886
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/api/monitoring.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='google/api/monitoring.proto', package='google.api', syntax='proto3', serialized_pb=_b('\n\x1bgoogle/api/monitoring.proto\x12\ngoogle.api\x1a\x1cgoogle/api/annotations.proto\"\xec\x01\n\nMonitoring\x12K\n\x15producer_destinations\x18\x01 \x03(\x0b\x32,.google.api.Monitoring.MonitoringDestination\x12K\n\x15\x63onsumer_destinations\x18\x02 \x03(\x0b\x32,.google.api.Monitoring.MonitoringDestination\x1a\x44\n\x15MonitoringDestination\x12\x1a\n\x12monitored_resource\x18\x01 \x01(\t\x12\x0f\n\x07metrics\x18\x02 \x03(\tB*\n\x0e\x63om.google.apiB\x0fMonitoringProtoP\x01\xa2\x02\x04GAPIb\x06proto3') , dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,]) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _MONITORING_MONITORINGDESTINATION = _descriptor.Descriptor( name='MonitoringDestination', full_name='google.api.Monitoring.MonitoringDestination', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='monitored_resource', full_name='google.api.Monitoring.MonitoringDestination.monitored_resource', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='metrics', full_name='google.api.Monitoring.MonitoringDestination.metrics', index=1, number=2, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=242, serialized_end=310, ) _MONITORING = _descriptor.Descriptor( name='Monitoring', full_name='google.api.Monitoring', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='producer_destinations', full_name='google.api.Monitoring.producer_destinations', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='consumer_destinations', full_name='google.api.Monitoring.consumer_destinations', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[_MONITORING_MONITORINGDESTINATION, ], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=74, serialized_end=310, ) _MONITORING_MONITORINGDESTINATION.containing_type = _MONITORING _MONITORING.fields_by_name['producer_destinations'].message_type = _MONITORING_MONITORINGDESTINATION _MONITORING.fields_by_name['consumer_destinations'].message_type = _MONITORING_MONITORINGDESTINATION DESCRIPTOR.message_types_by_name['Monitoring'] = _MONITORING Monitoring = _reflection.GeneratedProtocolMessageType('Monitoring', (_message.Message,), dict( MonitoringDestination = _reflection.GeneratedProtocolMessageType('MonitoringDestination', (_message.Message,), dict( DESCRIPTOR = _MONITORING_MONITORINGDESTINATION, __module__ = 'google.api.monitoring_pb2' # @@protoc_insertion_point(class_scope:google.api.Monitoring.MonitoringDestination) )) , DESCRIPTOR = _MONITORING, __module__ = 'google.api.monitoring_pb2' # @@protoc_insertion_point(class_scope:google.api.Monitoring) )) _sym_db.RegisterMessage(Monitoring) _sym_db.RegisterMessage(Monitoring.MonitoringDestination) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\016com.google.apiB\017MonitoringProtoP\001\242\002\004GAPI')) # @@protoc_insertion_point(module_scope)
mit
UdeM-LBIT/GAPol
lib/ga/evolve/Statistics.py
1
3790
""" :mod:`Statistics` -- statistical structure module ========================================================================== This module have the class which is reponsible to keep statistics of each generation. This class is used by the adapters and other statistics dump objects. """ class Statistics(object): """ Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **rawMax, rawMin, rawAve** Maximum, minimum and average of raw scores **rawDev, rawVar** Standard Deviation and Variance of raw scores **fitMax, fitMin, fitAve** Maximum, mininum and average of fitness scores **rawTot, fitTot** The total (sum) of raw scores and the fitness scores Example: >>> stats = ga_engine.getStatistics() >>> st["rawMax"] 10.2 """ def __init__(self): """ The Statistics Class creator """ # 'fit' means 'fitness' self.internalDict = { "rawMax": [], "rawMin": [], "rawAve": [], "rawDev": [], "rawMed": [], "rawVar": [], "fitMax": 0.0, "fitMin": 0.0, "fitAve": 0.0 } self.descriptions = { "rawMax": "Maximum raw score for each evaluator", "rawMin": "Minimum raw score for evaluator", "rawAve": "Average of raw score for each evaluator", "rawDev": "Standard deviation of raw scores, for each evaluator", "rawVar": "Raw scores variance for each evaluator", "fitMax": "Maximum fitness", "fitMin": "Minimum fitness", "fitAve": "Fitness average", } def getRawScore(self, ind=0): rawdict = { "rawMax": self["rawMax"][ind], "rawMin": self["rawMin"][ind], "rawAve": self["rawAve"][ind], "rawDev": self["rawDev"][ind], "rawVar": self["rawVar"][ind] } return rawdict def __getitem__(self, key): """ Return the specific statistic by key """ return self.internalDict[key] def __setitem__(self, key, value): """ Set the statistic """ self.internalDict[key] = value def __len__(self): """ Return the length of internal stats dictionary """ return len(self.internalDict) def __repr__(self): """ Return a string representation of the statistics """ strBuff = "- Statistics\n" for k, v in self.internalDict.items(): if isinstance(v, list): v = "[" + ", ".join(["%.2f"%vv for vv in v]) + "]" else: v = "%.2f"%v strBuff += "\t%-45s = %s\n" % (self.descriptions.get(k, k), v) return strBuff def asTuple(self): """ Returns the stats as a python tuple """ return tuple(self.internalDict.values()) def clear(self): """ Set all statistics to zero """ for k,v in self.internalDict.items(): if isinstance(v, list): self.internalDict[k] = [] else: self.internalDict[k] = 0.0 def items(self): """ Return a tuple (name, value) for all stored statistics """ return self.internalDict.items() def clone(self): """ Instantiate a new Statistic class with the same contents """ clone_stat = Statistics() self.copy(clone_stat) return clone_stat def copy(self, obj): """ Copy the values to the obj variable of the same class :param obj: the Statistics object destination """ obj.internalDict = self.internalDict.copy() obj.descriptions = self.descriptions.copy()
gpl-3.0
RPI-OPENEDX/edx-platform
cms/djangoapps/course_creators/tests/test_admin.py
61
8201
""" Tests course_creators.admin.py. """ from django.test import TestCase from django.contrib.auth.models import User from django.contrib.admin.sites import AdminSite from django.http import HttpRequest import mock from course_creators.admin import CourseCreatorAdmin from course_creators.models import CourseCreator from django.core import mail from student.roles import CourseCreatorRole from student import auth def mock_render_to_string(template_name, context): """Return a string that encodes template_name and context""" return str((template_name, context)) class CourseCreatorAdminTest(TestCase): """ Tests for course creator admin. """ def setUp(self): """ Test case setup """ super(CourseCreatorAdminTest, self).setUp() self.user = User.objects.create_user('test_user', 'test_user+courses@edx.org', 'foo') self.table_entry = CourseCreator(user=self.user) self.table_entry.save() self.admin = User.objects.create_user('Mark', 'admin+courses@edx.org', 'foo') self.admin.is_staff = True self.request = HttpRequest() self.request.user = self.admin self.creator_admin = CourseCreatorAdmin(self.table_entry, AdminSite()) self.studio_request_email = 'mark@marky.mark' self.enable_creator_group_patch = { "ENABLE_CREATOR_GROUP": True, "STUDIO_REQUEST_EMAIL": self.studio_request_email } @mock.patch('course_creators.admin.render_to_string', mock.Mock(side_effect=mock_render_to_string, autospec=True)) @mock.patch('django.contrib.auth.models.User.email_user') def test_change_status(self, email_user): """ Tests that updates to state impact the creator group maintained in authz.py and that e-mails are sent. """ def change_state_and_verify_email(state, is_creator): """ Changes user state, verifies creator status, and verifies e-mail is sent based on transition """ self._change_state(state) self.assertEqual(is_creator, auth.user_has_role(self.user, CourseCreatorRole())) context = {'studio_request_email': self.studio_request_email} if state == CourseCreator.GRANTED: template = 'emails/course_creator_granted.txt' elif state == CourseCreator.DENIED: template = 'emails/course_creator_denied.txt' else: template = 'emails/course_creator_revoked.txt' email_user.assert_called_with( mock_render_to_string('emails/course_creator_subject.txt', context), mock_render_to_string(template, context), self.studio_request_email ) with mock.patch.dict('django.conf.settings.FEATURES', self.enable_creator_group_patch): # User is initially unrequested. self.assertFalse(auth.user_has_role(self.user, CourseCreatorRole())) change_state_and_verify_email(CourseCreator.GRANTED, True) change_state_and_verify_email(CourseCreator.DENIED, False) change_state_and_verify_email(CourseCreator.GRANTED, True) change_state_and_verify_email(CourseCreator.PENDING, False) change_state_and_verify_email(CourseCreator.GRANTED, True) change_state_and_verify_email(CourseCreator.UNREQUESTED, False) change_state_and_verify_email(CourseCreator.DENIED, False) @mock.patch('course_creators.admin.render_to_string', mock.Mock(side_effect=mock_render_to_string, autospec=True)) def test_mail_admin_on_pending(self): """ Tests that the admin account is notified when a user is in the 'pending' state. """ def check_admin_message_state(state, expect_sent_to_admin, expect_sent_to_user): """ Changes user state and verifies e-mail sent to admin address only when pending. """ mail.outbox = [] self._change_state(state) # If a message is sent to the user about course creator status change, it will be the first # message sent. Admin message will follow. base_num_emails = 1 if expect_sent_to_user else 0 if expect_sent_to_admin: context = {'user_name': "test_user", 'user_email': u'test_user+courses@edx.org'} self.assertEquals(base_num_emails + 1, len(mail.outbox), 'Expected admin message to be sent') sent_mail = mail.outbox[base_num_emails] self.assertEquals( mock_render_to_string('emails/course_creator_admin_subject.txt', context), sent_mail.subject ) self.assertEquals( mock_render_to_string('emails/course_creator_admin_user_pending.txt', context), sent_mail.body ) self.assertEquals(self.studio_request_email, sent_mail.from_email) self.assertEqual([self.studio_request_email], sent_mail.to) else: self.assertEquals(base_num_emails, len(mail.outbox)) with mock.patch.dict('django.conf.settings.FEATURES', self.enable_creator_group_patch): # E-mail message should be sent to admin only when new state is PENDING, regardless of what # previous state was (unless previous state was already PENDING). # E-mail message sent to user only on transition into and out of GRANTED state. check_admin_message_state(CourseCreator.UNREQUESTED, expect_sent_to_admin=False, expect_sent_to_user=False) check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=True, expect_sent_to_user=False) check_admin_message_state(CourseCreator.GRANTED, expect_sent_to_admin=False, expect_sent_to_user=True) check_admin_message_state(CourseCreator.DENIED, expect_sent_to_admin=False, expect_sent_to_user=True) check_admin_message_state(CourseCreator.GRANTED, expect_sent_to_admin=False, expect_sent_to_user=True) check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=True, expect_sent_to_user=True) check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=False, expect_sent_to_user=False) check_admin_message_state(CourseCreator.DENIED, expect_sent_to_admin=False, expect_sent_to_user=True) def _change_state(self, state): """ Helper method for changing state """ self.table_entry.state = state self.creator_admin.save_model(self.request, self.table_entry, None, True) def test_add_permission(self): """ Tests that staff cannot add entries """ self.assertFalse(self.creator_admin.has_add_permission(self.request)) def test_delete_permission(self): """ Tests that staff cannot delete entries """ self.assertFalse(self.creator_admin.has_delete_permission(self.request)) def test_change_permission(self): """ Tests that only staff can change entries """ self.assertTrue(self.creator_admin.has_change_permission(self.request)) self.request.user = self.user self.assertFalse(self.creator_admin.has_change_permission(self.request)) def test_rate_limit_login(self): with mock.patch.dict('django.conf.settings.FEATURES', {'ENABLE_CREATOR_GROUP': True}): post_params = {'username': self.user.username, 'password': 'wrong_password'} # try logging in 30 times, the default limit in the number of failed # login attempts in one 5 minute period before the rate gets limited for _ in xrange(30): response = self.client.post('/admin/login/', post_params) self.assertEquals(response.status_code, 200) response = self.client.post('/admin/login/', post_params) # Since we are using the default rate limit behavior, we are # expecting this to return a 403 error to indicate that there have # been too many attempts self.assertEquals(response.status_code, 403)
agpl-3.0
hakonsbm/nest-simulator
topology/pynest/tests/test_connection_with_elliptical_mask.py
5
13035
# -*- coding: utf-8 -*- # # test_connection_with_elliptical_mask.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # NEST is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NEST. If not, see <http://www.gnu.org/licenses/>. """ Tests ConnectLayer with elliptical mask. """ import unittest import nest import nest.topology as topo class ConnectWithEllipticalMask(unittest.TestCase): def setUp(self): nest.ResetKernel() def test_ConnectEllipticalMask(self): """Test connection with simple elliptical mask. We have: major_axis = 3.0 minor_axis = 2.0 Each source node should then connect to: - The node in the same position in target layer - The node to the left and right of that position - The nodes above and below. So, if we have sources: targets: 2 7 12 17 22 28 33 38 43 48 3 8 13 18 23 29 34 39 44 49 4 9 14 19 24 30 35 40 45 50 5 10 15 20 25 31 36 41 46 51 6 11 16 21 26 32 37 42 47 52 some example connections will be: 2 -> 28 33 29 39 14 -> 35 40 45 41 """ source = topo.CreateLayer({'rows': 5, 'columns': 5, 'extent': [5., 5.], 'elements': 'iaf_psc_alpha'}) target = topo.CreateLayer({'rows': 5, 'columns': 5, 'extent': [5., 5.], 'elements': 'iaf_psc_alpha'}) conndict = {'connection_type': 'divergent', 'mask': {'elliptical': {'major_axis': 3.0, 'minor_axis': 2.0}}} topo.ConnectLayers(source, target, conndict) ref = [[2, 28], [2, 29], [2, 33], [3, 28], [3, 29], [3, 30], [3, 34], [4, 29], [4, 30], [4, 31], [4, 35], [5, 30], [5, 31], [5, 32], [5, 36], [6, 31], [6, 32], [6, 37], [7, 28], [7, 33], [7, 34], [7, 38], [8, 29], [8, 33], [8, 34], [8, 35], [8, 39], [9, 30], [9, 34], [9, 35], [9, 36], [9, 40], [10, 31], [10, 35], [10, 36], [10, 37], [10, 41], [11, 32], [11, 36], [11, 37], [11, 42], [12, 33], [12, 38], [12, 39], [12, 43], [13, 34], [13, 38], [13, 39], [13, 40], [13, 44], [14, 35], [14, 39], [14, 40], [14, 41], [14, 45], [15, 36], [15, 40], [15, 41], [15, 42], [15, 46], [16, 37], [16, 41], [16, 42], [16, 47], [17, 38], [17, 43], [17, 44], [17, 48], [18, 39], [18, 43], [18, 44], [18, 45], [18, 49], [19, 40], [19, 44], [19, 45], [19, 46], [19, 50], [20, 41], [20, 45], [20, 46], [20, 47], [20, 51], [21, 42], [21, 46], [21, 47], [21, 52], [22, 43], [22, 48], [22, 49], [23, 44], [23, 48], [23, 49], [23, 50], [24, 45], [24, 49], [24, 50], [24, 51], [25, 46], [25, 50], [25, 51], [25, 52], [26, 47], [26, 51], [26, 52]] connections = [[conn[0], conn[1]] for conn in nest.GetConnections()] for conn, conn_ref in zip(sorted(connections), sorted(ref)): self.assertEqual(conn, conn_ref) def test_ConnectTiltedEllipticalMask(self): """Test connection with tilted elliptical mask. We have: major_axis = 3.0 minor_axis = 1.0 azimuth_angle = 45 degrees Each source node should then connect to: - The node in the same position in target layer - The node above the node to the right of that position - The node below the node to the left of the position. So, if we have sources: targets: 2 7 12 17 22 28 33 38 43 48 3 8 13 18 23 29 34 39 44 49 4 9 14 19 24 30 35 40 45 50 5 10 15 20 25 31 36 41 46 51 6 11 16 21 26 32 37 42 47 52 some example connections will be: 2 -> 28 44 14 -> 40 36 """ source = topo.CreateLayer({'rows': 5, 'columns': 5, 'extent': [5., 5.], 'elements': 'iaf_psc_alpha'}) target = topo.CreateLayer({'rows': 5, 'columns': 5, 'extent': [5., 5.], 'elements': 'iaf_psc_alpha'}) conndict = {'connection_type': 'divergent', 'mask': {'elliptical': {'major_axis': 3.0, 'minor_axis': 1.0, 'azimuth_angle': 45.}}} topo.ConnectLayers(source, target, conndict) ref = [[2, 28], [3, 29], [3, 33], [4, 30], [4, 34], [5, 31], [5, 35], [6, 32], [6, 36], [7, 29], [7, 33], [8, 30], [8, 34], [8, 38], [9, 31], [9, 35], [9, 39], [10, 32], [10, 36], [10, 40], [11, 37], [11, 41], [12, 34], [12, 38], [13, 35], [13, 39], [13, 43], [14, 36], [14, 40], [14, 44], [15, 37], [15, 41], [15, 45], [16, 42], [16, 46], [17, 39], [17, 43], [18, 40], [18, 44], [18, 48], [19, 41], [19, 45], [19, 49], [20, 42], [20, 46], [20, 50], [21, 47], [21, 51], [22, 44], [22, 48], [23, 45], [23, 49], [24, 46], [24, 50], [25, 47], [25, 51], [26, 52]] connections = [[conn[0], conn[1]] for conn in nest.GetConnections()] for conn, conn_ref in zip(sorted(connections), sorted(ref)): self.assertEqual(conn, conn_ref) def test_ConnectAnchoredEllipticalMask(self): """Test connection with anchored elliptical mask. We have: major_axis = 3.0 minor_axis = 2.0 anchor = [1.0, 0.0] (right edge of mask aligned with source) Each source node should then connect to: - The node in the same position in target layer - The two nodes to the right of that position - The nodes above and below the node to the right of the position. So, if we have sources: targets: 2 7 12 17 22 28 33 38 43 48 3 8 13 18 23 29 34 39 44 49 4 9 14 19 24 30 35 40 45 50 5 10 15 20 25 31 36 41 46 51 6 11 16 21 26 32 37 42 47 52 some example connections will be: 2 -> 28 33 38 34 44 14 -> 40 45 50 46 """ source = topo.CreateLayer({'rows': 5, 'columns': 5, 'extent': [5., 5.], 'elements': 'iaf_psc_alpha'}) target = topo.CreateLayer({'rows': 5, 'columns': 5, 'extent': [5., 5.], 'elements': 'iaf_psc_alpha'}) conndict = {'connection_type': 'divergent', 'mask': {'elliptical': {'major_axis': 3., 'minor_axis': 2., 'anchor': [1., 0.]}}} topo.ConnectLayers(source, target, conndict) ref = [[2, 28], [2, 33], [2, 34], [2, 38], [3, 29], [3, 33], [3, 34], [3, 35], [3, 39], [4, 30], [4, 34], [4, 35], [4, 36], [4, 40], [5, 31], [5, 35], [5, 36], [5, 37], [5, 41], [6, 32], [6, 36], [6, 37], [6, 42], [7, 33], [7, 38], [7, 39], [7, 43], [8, 34], [8, 38], [8, 39], [8, 40], [8, 44], [9, 35], [9, 39], [9, 40], [9, 41], [9, 45], [10, 36], [10, 40], [10, 41], [10, 42], [10, 46], [11, 37], [11, 41], [11, 42], [11, 47], [12, 38], [12, 43], [12, 44], [12, 48], [13, 39], [13, 43], [13, 44], [13, 45], [13, 49], [14, 40], [14, 44], [14, 45], [14, 46], [14, 50], [15, 41], [15, 45], [15, 46], [15, 47], [15, 51], [16, 42], [16, 46], [16, 47], [16, 52], [17, 43], [17, 48], [17, 49], [18, 44], [18, 48], [18, 49], [18, 50], [19, 45], [19, 49], [19, 50], [19, 51], [20, 46], [20, 50], [20, 51], [20, 52], [21, 47], [21, 51], [21, 52], [22, 48], [23, 49], [24, 50], [25, 51], [26, 52]] connections = [[conn[0], conn[1]] for conn in nest.GetConnections()] for conn, conn_ref in zip(sorted(connections), sorted(ref)): self.assertEqual(conn, conn_ref) def test_ConnectEllipticalMaskWithPeriodicBoundary(self): """Test connection with simple elliptical mask. We have: major_axis = 3.0 minor_axis = 2.0 Each source node should then connect to: - The node in the same position in target layer - The node to the left and right of that position - The nodes above and below - Nodes on the edges have connections on the other, corresponding edges. So, if we have sources: targets: 2 7 12 17 22 28 33 38 43 48 3 8 13 18 23 29 34 39 44 49 4 9 14 19 24 30 35 40 45 50 5 10 15 20 25 31 36 41 46 51 6 11 16 21 26 32 37 42 47 52 some example connections will be: 6 2 -> 48 28 33 29 39 14 -> 35 40 45 41 """ source = topo.CreateLayer({'rows': 5, 'columns': 5, 'extent': [5., 5.], 'elements': 'iaf_psc_alpha', 'edge_wrap': True}) target = topo.CreateLayer({'rows': 5, 'columns': 5, 'extent': [5., 5.], 'elements': 'iaf_psc_alpha', 'edge_wrap': True}) conndict = {'connection_type': 'divergent', 'mask': {'elliptical': {'major_axis': 3., 'minor_axis': 2.}}} topo.ConnectLayers(source, target, conndict) ref = [[2, 28], [2, 29], [2, 32], [2, 33], [2, 48], [3, 28], [3, 29], [3, 30], [3, 34], [3, 49], [4, 29], [4, 30], [4, 31], [4, 35], [4, 50], [5, 30], [5, 31], [5, 32], [5, 36], [5, 51], [6, 28], [6, 31], [6, 32], [6, 37], [6, 52], [7, 28], [7, 33], [7, 34], [7, 37], [7, 38], [8, 29], [8, 33], [8, 34], [8, 35], [8, 39], [9, 30], [9, 34], [9, 35], [9, 36], [9, 40], [10, 31], [10, 35], [10, 36], [10, 37], [10, 41], [11, 32], [11, 33], [11, 36], [11, 37], [11, 42], [12, 33], [12, 38], [12, 39], [12, 42], [12, 43], [13, 34], [13, 38], [13, 39], [13, 40], [13, 44], [14, 35], [14, 39], [14, 40], [14, 41], [14, 45], [15, 36], [15, 40], [15, 41], [15, 42], [15, 46], [16, 37], [16, 38], [16, 41], [16, 42], [16, 47], [17, 38], [17, 43], [17, 44], [17, 47], [17, 48], [18, 39], [18, 43], [18, 44], [18, 45], [18, 49], [19, 40], [19, 44], [19, 45], [19, 46], [19, 50], [20, 41], [20, 45], [20, 46], [20, 47], [20, 51], [21, 42], [21, 43], [21, 46], [21, 47], [21, 52], [22, 28], [22, 43], [22, 48], [22, 49], [22, 52], [23, 29], [23, 44], [23, 48], [23, 49], [23, 50], [24, 30], [24, 45], [24, 49], [24, 50], [24, 51], [25, 31], [25, 46], [25, 50], [25, 51], [25, 52], [26, 32], [26, 47], [26, 48], [26, 51], [26, 52]] connections = [[conn[0], conn[1]] for conn in nest.GetConnections()] for conn, conn_ref in zip(sorted(connections), sorted(ref)): self.assertEqual(conn, conn_ref) def suite(): suite = unittest.makeSuite(ConnectWithEllipticalMask, 'test') return suite if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity=2) runner.run(suite())
gpl-2.0
sv-dev1/odoo
addons/mrp/wizard/mrp_price.py
381
2132
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv class mrp_price(osv.osv_memory): _name = 'mrp.product_price' _description = 'Product Price' _columns = { 'number': fields.integer('Quantity', required=True, help="Specify quantity of products to produce or buy. Report of Cost structure will be displayed base on this quantity."), } _defaults = { 'number': 1, } def print_report(self, cr, uid, ids, context=None): """ To print the report of Product cost structure @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param context: A standard dictionary @return : Report """ if context is None: context = {} datas = {'ids' : context.get('active_ids',[])} res = self.read(cr, uid, ids, ['number']) res = res and res[0] or {} datas['form'] = res return { 'type' : 'ir.actions.report.xml', 'report_name':'product.price', 'datas' : datas, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
dmitriy0611/django
tests/utils_tests/test_decorators.py
11
3968
from django.http import HttpResponse from django.template import engines from django.template.response import TemplateResponse from django.test import RequestFactory, SimpleTestCase from django.utils.decorators import decorator_from_middleware class ProcessViewMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): pass process_view_dec = decorator_from_middleware(ProcessViewMiddleware) @process_view_dec def process_view(request): return HttpResponse() class ClassProcessView(object): def __call__(self, request): return HttpResponse() class_process_view = process_view_dec(ClassProcessView()) class FullMiddleware(object): def process_request(self, request): request.process_request_reached = True def process_view(self, request, view_func, view_args, view_kwargs): request.process_view_reached = True def process_template_response(self, request, response): request.process_template_response_reached = True return response def process_response(self, request, response): # This should never receive unrendered content. request.process_response_content = response.content request.process_response_reached = True return response full_dec = decorator_from_middleware(FullMiddleware) class DecoratorFromMiddlewareTests(SimpleTestCase): """ Tests for view decorators created using ``django.utils.decorators.decorator_from_middleware``. """ rf = RequestFactory() def test_process_view_middleware(self): """ Test a middleware that implements process_view. """ process_view(self.rf.get('/')) def test_callable_process_view_middleware(self): """ Test a middleware that implements process_view, operating on a callable class. """ class_process_view(self.rf.get('/')) def test_full_dec_normal(self): """ Test that all methods of middleware are called for normal HttpResponses """ @full_dec def normal_view(request): template = engines['django'].from_string("Hello world") return HttpResponse(template.render()) request = self.rf.get('/') normal_view(request) self.assertTrue(getattr(request, 'process_request_reached', False)) self.assertTrue(getattr(request, 'process_view_reached', False)) # process_template_response must not be called for HttpResponse self.assertFalse(getattr(request, 'process_template_response_reached', False)) self.assertTrue(getattr(request, 'process_response_reached', False)) def test_full_dec_templateresponse(self): """ Test that all methods of middleware are called for TemplateResponses in the right sequence. """ @full_dec def template_response_view(request): template = engines['django'].from_string("Hello world") return TemplateResponse(request, template) request = self.rf.get('/') response = template_response_view(request) self.assertTrue(getattr(request, 'process_request_reached', False)) self.assertTrue(getattr(request, 'process_view_reached', False)) self.assertTrue(getattr(request, 'process_template_response_reached', False)) # response must not be rendered yet. self.assertFalse(response._is_rendered) # process_response must not be called until after response is rendered, # otherwise some decorators like csrf_protect and gzip_page will not # work correctly. See #16004 self.assertFalse(getattr(request, 'process_response_reached', False)) response.render() self.assertTrue(getattr(request, 'process_response_reached', False)) # Check that process_response saw the rendered content self.assertEqual(request.process_response_content, b"Hello world")
bsd-3-clause
OpenLD/enigma2-wetek
lib/python/Components/Label.py
2
2938
from HTMLComponent import HTMLComponent from GUIComponent import GUIComponent from VariableText import VariableText from skin import parseColor from ConditionalWidget import ConditionalWidget, BlinkingWidget, BlinkingWidgetConditional from enigma import eLabel class Label(VariableText, HTMLComponent, GUIComponent): def __init__(self, text=""): GUIComponent.__init__(self) VariableText.__init__(self) self.setText(text) # fake Source methods: def connectDownstream(self, downstream): pass def checkSuspend(self): pass def disconnectDownstream(self, downstream): pass # html: def produceHTML(self): return self.getText() # GUI: GUI_WIDGET = eLabel def getSize(self): s = self.instance.calculateSize() return s.width(), s.height() class LabelConditional(Label, ConditionalWidget): def __init__(self, text = "", withTimer = True): ConditionalWidget.__init__(self, withTimer = withTimer) Label.__init__(self, text = text) class BlinkingLabel(Label, BlinkingWidget): def __init__(self, text = ""): Label.__init__(text = text) BlinkingWidget.__init__() class BlinkingLabelConditional(BlinkingWidgetConditional, LabelConditional): def __init__(self, text = ""): LabelConditional.__init__(self, text = text) BlinkingWidgetConditional.__init__(self) class MultiColorLabel(Label): def __init__(self, text=""): Label.__init__(self,text) self.foreColors = [] self.backColors = [] def applySkin(self, desktop, screen): if self.skinAttributes is not None: foregroundColor = None backgroundColor = None attribs = [ ] for (attrib, value) in self.skinAttributes: if attrib == "foregroundColors": colors = value.split(',') for color in colors: self.foreColors.append(parseColor(color)) if not foregroundColor: foregroundColor = colors[0] elif attrib == "backgroundColors": colors = value.split(',') for color in colors: self.backColors.append(parseColor(color)) if not backgroundColor: backgroundColor = colors[0] elif attrib == "backgroundColor": backgroundColor = value elif attrib == "foregroundColor": foregroundColor = value else: attribs.append((attrib,value)) if foregroundColor: attribs.append(("foregroundColor",foregroundColor)) if backgroundColor: attribs.append(("backgroundColor",backgroundColor)) self.skinAttributes = attribs return GUIComponent.applySkin(self, desktop, screen) def setForegroundColorNum(self, x): if self.instance: if len(self.foreColors) > x: self.instance.setForegroundColor(self.foreColors[x]) else: print "setForegroundColorNum(%d) failed! defined colors:" % x, self.foreColors def setBackgroundColorNum(self, x): if self.instance: if len(self.backColors) > x: self.instance.setBackgroundColor(self.backColors[x]) else: print "setBackgroundColorNum(%d) failed! defined colors:" % x, self.backColors
gpl-2.0
mwmuni/LIGGGHTS_GUI
networkx/algorithms/approximation/connectivity.py
31
13106
""" Fast approximation for node connectivity """ # Copyright (C) 2015 by # Jordi Torrents <jtorrents@milnou.net> # All rights reserved. # BSD license. import itertools from operator import itemgetter import networkx as nx __author__ = """\n""".join(['Jordi Torrents <jtorrents@milnou.net>']) __all__ = ['local_node_connectivity', 'node_connectivity', 'all_pairs_node_connectivity'] INF = float('inf') def local_node_connectivity(G, source, target, cutoff=None): """Compute node connectivity between source and target. Pairwise or local node connectivity between two distinct and nonadjacent nodes is the minimum number of nodes that must be removed (minimum separating cutset) to disconnect them. By Menger's theorem, this is equal to the number of node independent paths (paths that share no nodes other than source and target). Which is what we compute in this function. This algorithm is a fast approximation that gives an strict lower bound on the actual number of node independent paths between two nodes [1]_. It works for both directed and undirected graphs. Parameters ---------- G : NetworkX graph source : node Starting node for node connectivity target : node Ending node for node connectivity cutoff : integer Maximum node connectivity to consider. If None, the minimum degree of source or target is used as a cutoff. Default value None. Returns ------- k: integer pairwise node connectivity Examples -------- >>> # Platonic icosahedral graph has node connectivity 5 >>> # for each non adjacent node pair >>> from networkx.algorithms import approximation as approx >>> G = nx.icosahedral_graph() >>> approx.local_node_connectivity(G, 0, 6) 5 Notes ----- This algorithm [1]_ finds node independents paths between two nodes by computing their shortest path using BFS, marking the nodes of the path found as 'used' and then searching other shortest paths excluding the nodes marked as used until no more paths exist. It is not exact because a shortest path could use nodes that, if the path were longer, may belong to two different node independent paths. Thus it only guarantees an strict lower bound on node connectivity. Note that the authors propose a further refinement, losing accuracy and gaining speed, which is not implemented yet. See also -------- all_pairs_node_connectivity node_connectivity References ---------- .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035 http://eclectic.ss.uci.edu/~drwhite/working.pdf """ if target == source: raise nx.NetworkXError("source and target have to be different nodes.") # Maximum possible node independent paths if G.is_directed(): possible = min(G.out_degree(source), G.in_degree(target)) else: possible = min(G.degree(source), G.degree(target)) K = 0 if not possible: return K if cutoff is None: cutoff = INF exclude = set() for i in range(min(possible, cutoff)): try: path = _bidirectional_shortest_path(G, source, target, exclude) exclude.update(set(path)) K += 1 except nx.NetworkXNoPath: break return K def node_connectivity(G, s=None, t=None): r"""Returns an approximation for node connectivity for a graph or digraph G. Node connectivity is equal to the minimum number of nodes that must be removed to disconnect G or render it trivial. By Menger's theorem, this is equal to the number of node independent paths (paths that share no nodes other than source and target). If source and target nodes are provided, this function returns the local node connectivity: the minimum number of nodes that must be removed to break all paths from source to target in G. This algorithm is based on a fast approximation that gives an strict lower bound on the actual number of node independent paths between two nodes [1]_. It works for both directed and undirected graphs. Parameters ---------- G : NetworkX graph Undirected graph s : node Source node. Optional. Default value: None. t : node Target node. Optional. Default value: None. Returns ------- K : integer Node connectivity of G, or local node connectivity if source and target are provided. Examples -------- >>> # Platonic icosahedral graph is 5-node-connected >>> from networkx.algorithms import approximation as approx >>> G = nx.icosahedral_graph() >>> approx.node_connectivity(G) 5 Notes ----- This algorithm [1]_ finds node independents paths between two nodes by computing their shortest path using BFS, marking the nodes of the path found as 'used' and then searching other shortest paths excluding the nodes marked as used until no more paths exist. It is not exact because a shortest path could use nodes that, if the path were longer, may belong to two different node independent paths. Thus it only guarantees an strict lower bound on node connectivity. See also -------- all_pairs_node_connectivity local_node_connectivity References ---------- .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035 http://eclectic.ss.uci.edu/~drwhite/working.pdf """ if (s is not None and t is None) or (s is None and t is not None): raise nx.NetworkXError('Both source and target must be specified.') # Local node connectivity if s is not None and t is not None: if s not in G: raise nx.NetworkXError('node %s not in graph' % s) if t not in G: raise nx.NetworkXError('node %s not in graph' % t) return local_node_connectivity(G, s, t) # Global node connectivity if G.is_directed(): connected_func = nx.is_weakly_connected iter_func = itertools.permutations def neighbors(v): return itertools.chain.from_iterable([G.predecessors_iter(v), G.successors_iter(v)]) else: connected_func = nx.is_connected iter_func = itertools.combinations neighbors = G.neighbors_iter if not connected_func(G): return 0 # Choose a node with minimum degree v, minimum_degree = min(G.degree().items(), key=itemgetter(1)) # Node connectivity is bounded by minimum degree K = minimum_degree # compute local node connectivity with all non-neighbors nodes # and store the minimum for w in set(G) - set(neighbors(v)) - set([v]): K = min(K, local_node_connectivity(G, v, w, cutoff=K)) # Same for non adjacent pairs of neighbors of v for x, y in iter_func(neighbors(v), 2): if y not in G[x] and x != y: K = min(K, local_node_connectivity(G, x, y, cutoff=K)) return K def all_pairs_node_connectivity(G, nbunch=None, cutoff=None): """ Compute node connectivity between all pairs of nodes. Pairwise or local node connectivity between two distinct and nonadjacent nodes is the minimum number of nodes that must be removed (minimum separating cutset) to disconnect them. By Menger's theorem, this is equal to the number of node independent paths (paths that share no nodes other than source and target). Which is what we compute in this function. This algorithm is a fast approximation that gives an strict lower bound on the actual number of node independent paths between two nodes [1]_. It works for both directed and undirected graphs. Parameters ---------- G : NetworkX graph nbunch: container Container of nodes. If provided node connectivity will be computed only over pairs of nodes in nbunch. cutoff : integer Maximum node connectivity to consider. If None, the minimum degree of source or target is used as a cutoff in each pair of nodes. Default value None. Returns ------- K : dictionary Dictionary, keyed by source and target, of pairwise node connectivity See Also -------- local_node_connectivity all_pairs_node_connectivity References ---------- .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035 http://eclectic.ss.uci.edu/~drwhite/working.pdf """ if nbunch is None: nbunch = G else: nbunch = set(nbunch) directed = G.is_directed() if directed: iter_func = itertools.permutations else: iter_func = itertools.combinations all_pairs = {n: {} for n in nbunch} for u, v in iter_func(nbunch, 2): k = local_node_connectivity(G, u, v, cutoff=cutoff) all_pairs[u][v] = k if not directed: all_pairs[v][u] = k return all_pairs def _bidirectional_shortest_path(G, source, target, exclude): """Return shortest path between source and target ignoring nodes in the container 'exclude'. Parameters ---------- G : NetworkX graph source : node Starting node for path target : node Ending node for path exclude: container Container for nodes to exclude from the search for shortest paths Returns ------- path: list Shortest path between source and target ignoring nodes in 'exclude' Raises ------ NetworkXNoPath: exception If there is no path or if nodes are adjacent and have only one path between them Notes ----- This function and its helper are originaly from networkx.algorithms.shortest_paths.unweighted and are modified to accept the extra parameter 'exclude', which is a container for nodes already used in other paths that should be ignored. References ---------- .. [1] White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035 http://eclectic.ss.uci.edu/~drwhite/working.pdf """ # call helper to do the real work results = _bidirectional_pred_succ(G, source, target, exclude) pred, succ, w = results # build path from pred+w+succ path = [] # from source to w while w is not None: path.append(w) w = pred[w] path.reverse() # from w to target w = succ[path[-1]] while w is not None: path.append(w) w = succ[w] return path def _bidirectional_pred_succ(G, source, target, exclude): # does BFS from both source and target and meets in the middle # excludes nodes in the container "exclude" from the search if source is None or target is None: raise nx.NetworkXException(\ "Bidirectional shortest path called without source or target") if target == source: return ({target:None},{source:None},source) # handle either directed or undirected if G.is_directed(): Gpred = G.predecessors_iter Gsucc = G.successors_iter else: Gpred = G.neighbors_iter Gsucc = G.neighbors_iter # predecesssor and successors in search pred = {source: None} succ = {target: None} # initialize fringes, start with forward forward_fringe = [source] reverse_fringe = [target] level = 0 while forward_fringe and reverse_fringe: # Make sure that we iterate one step forward and one step backwards # thus source and target will only tigger "found path" when they are # adjacent and then they can be safely included in the container 'exclude' level += 1 if not level % 2 == 0: this_level = forward_fringe forward_fringe = [] for v in this_level: for w in Gsucc(v): if w in exclude: continue if w not in pred: forward_fringe.append(w) pred[w] = v if w in succ: return pred, succ, w # found path else: this_level = reverse_fringe reverse_fringe = [] for v in this_level: for w in Gpred(v): if w in exclude: continue if w not in succ: succ[w] = v reverse_fringe.append(w) if w in pred: return pred, succ, w # found path raise nx.NetworkXNoPath("No path between %s and %s." % (source, target))
gpl-3.0
liosha2007/temporary-groupdocs-python-sdk
groupdocs/models/GetJobDocumentsResponse.py
1
1163
#!/usr/bin/env python """ Copyright 2012 GroupDocs. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ class GetJobDocumentsResponse: """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" def __init__(self): self.swaggerTypes = { 'result': 'GetJobDocumentsResult', 'status': 'str', 'error_message': 'str', 'composedOn': 'long' } self.result = None # GetJobDocumentsResult self.status = None # str self.error_message = None # str self.composedOn = None # long
apache-2.0
hckiang/DBLite
boost_1_54_0/tools/build/v2/tools/types/lib.py
71
2703
# Status: ported # Base revision: 64456. # Copyright David Abrahams 2004. # Copyright Vladimir Prus 2010. # Distributed under the Boost # Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) import b2.build.type as type # The following naming scheme is used for libraries. # # On *nix: # libxxx.a static library # libxxx.so shared library # # On windows (msvc) # libxxx.lib static library # xxx.dll DLL # xxx.lib import library # # On windows (mingw): # libxxx.a static library # libxxx.dll DLL # libxxx.dll.a import library # # On cygwin i.e. <target-os>cygwin # libxxx.a static library # cygxxx.dll DLL # libxxx.dll.a import library # type.register('LIB') # FIXME: should not register both extensions on both platforms. type.register('STATIC_LIB', ['a', 'lib'], 'LIB') # The 'lib' prefix is used everywhere type.set_generated_target_prefix('STATIC_LIB', [], 'lib') # Use '.lib' suffix for windows type.set_generated_target_suffix('STATIC_LIB', ['<target-os>windows'], 'lib') # Except with gcc. type.set_generated_target_suffix('STATIC_LIB', ['<toolset>gcc', '<target-os>windows'], 'a') # Use xxx.lib for import libs type.register('IMPORT_LIB', [], 'STATIC_LIB') type.set_generated_target_prefix('IMPORT_LIB', [], '') type.set_generated_target_suffix('IMPORT_LIB', [], 'lib') # Except with gcc (mingw or cygwin), where use libxxx.dll.a type.set_generated_target_prefix('IMPORT_LIB', ['<toolset>gcc'], 'lib') type.set_generated_target_suffix('IMPORT_LIB', ['<toolset>gcc'], 'dll.a') type.register('SHARED_LIB', ['so', 'dll', 'dylib'], 'LIB') # Both mingw and cygwin use libxxx.dll naming scheme. # On Linux, use "lib" prefix type.set_generated_target_prefix('SHARED_LIB', [], 'lib') # But don't use it on windows type.set_generated_target_prefix('SHARED_LIB', ['<target-os>windows'], '') # But use it again on mingw type.set_generated_target_prefix('SHARED_LIB', ['<toolset>gcc', '<target-os>windows'], 'lib') # And use 'cyg' on cygwin type.set_generated_target_prefix('SHARED_LIB', ['<target-os>cygwin'], 'cyg') type.set_generated_target_suffix('SHARED_LIB', ['<target-os>windows'], 'dll') type.set_generated_target_suffix('SHARED_LIB', ['<target-os>cygwin'], 'dll') type.set_generated_target_suffix('SHARED_LIB', ['<target-os>darwin'], 'dylib') type.register('SEARCHED_LIB', [], 'LIB') # This is needed so that when we create a target of SEARCHED_LIB # type, there's no prefix or suffix automatically added. type.set_generated_target_prefix('SEARCHED_LIB', [], '') type.set_generated_target_suffix('SEARCHED_LIB', [], '')
gpl-3.0
wjsl/jaredcumulo
test/system/auto/simple/bulkFile.py
2
1090
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from JavaTest import JavaTest import unittest class BulkFileTest(JavaTest): "Test bulk import of different file types" order = 21 testClass="org.apache.accumulo.test.functional.BulkFileTest" def suite(): result = unittest.TestSuite() result.addTest(BulkFileTest()) return result
apache-2.0
Tejeshwarabm/Westwood
src/netanim/bindings/modulegen__gcc_LP64.py
354
264513
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) return True pybindgen.settings.error_handler = ErrorHandler() import sys def module_init(): root_module = Module('ns.netanim', cpp_namespace='::ns3') return root_module def register_types(module): root_module = module.get_root() ## log.h (module 'core'): ns3::LogLevel [enumeration] module.add_enum('LogLevel', ['LOG_NONE', 'LOG_ERROR', 'LOG_LEVEL_ERROR', 'LOG_WARN', 'LOG_LEVEL_WARN', 'LOG_DEBUG', 'LOG_LEVEL_DEBUG', 'LOG_INFO', 'LOG_LEVEL_INFO', 'LOG_FUNCTION', 'LOG_LEVEL_FUNCTION', 'LOG_LOGIC', 'LOG_LEVEL_LOGIC', 'LOG_ALL', 'LOG_LEVEL_ALL', 'LOG_PREFIX_FUNC', 'LOG_PREFIX_TIME', 'LOG_PREFIX_NODE'], import_from_module='ns.core') ## address.h (module 'network'): ns3::Address [class] module.add_class('Address', import_from_module='ns.network') ## address.h (module 'network'): ns3::Address::MaxSize_e [enumeration] module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network') ## animation-interface-helper.h (module 'netanim'): ns3::AnimPacketInfo [class] module.add_class('AnimPacketInfo') ## animation-interface-helper.h (module 'netanim'): ns3::AnimRxInfo [class] module.add_class('AnimRxInfo') ## animation-interface.h (module 'netanim'): ns3::AnimationInterface [class] module.add_class('AnimationInterface') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList [class] module.add_class('AttributeConstructionList', import_from_module='ns.core') ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item [struct] module.add_class('Item', import_from_module='ns.core', outer_class=root_module['ns3::AttributeConstructionList']) ## buffer.h (module 'network'): ns3::Buffer [class] module.add_class('Buffer', import_from_module='ns.network') ## buffer.h (module 'network'): ns3::Buffer::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::Buffer']) ## packet.h (module 'network'): ns3::ByteTagIterator [class] module.add_class('ByteTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::ByteTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagIterator']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList [class] module.add_class('ByteTagList', import_from_module='ns.network') ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator [class] module.add_class('Iterator', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList']) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::ByteTagList::Iterator']) ## callback.h (module 'core'): ns3::CallbackBase [class] module.add_class('CallbackBase', import_from_module='ns.core') ## event-id.h (module 'core'): ns3::EventId [class] module.add_class('EventId', import_from_module='ns.core') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] module.add_class('Ipv4Address', import_from_module='ns.network') ## ipv4-address.h (module 'network'): ns3::Ipv4Address [class] root_module['ns3::Ipv4Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask [class] module.add_class('Ipv4Mask', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] module.add_class('Ipv6Address', import_from_module='ns.network') ## ipv6-address.h (module 'network'): ns3::Ipv6Address [class] root_module['ns3::Ipv6Address'].implicitly_converts_to(root_module['ns3::Address']) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix [class] module.add_class('Ipv6Prefix', import_from_module='ns.network') ## log.h (module 'core'): ns3::LogComponent [class] module.add_class('LogComponent', import_from_module='ns.core') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] module.add_class('Mac48Address', import_from_module='ns.network') ## mac48-address.h (module 'network'): ns3::Mac48Address [class] root_module['ns3::Mac48Address'].implicitly_converts_to(root_module['ns3::Address']) ## node-container.h (module 'network'): ns3::NodeContainer [class] module.add_class('NodeContainer', import_from_module='ns.network') ## node-list.h (module 'network'): ns3::NodeList [class] module.add_class('NodeList', import_from_module='ns.network') ## object-base.h (module 'core'): ns3::ObjectBase [class] module.add_class('ObjectBase', allow_subclassing=True, import_from_module='ns.core') ## object.h (module 'core'): ns3::ObjectDeleter [struct] module.add_class('ObjectDeleter', import_from_module='ns.core') ## object-factory.h (module 'core'): ns3::ObjectFactory [class] module.add_class('ObjectFactory', import_from_module='ns.core') ## packet-metadata.h (module 'network'): ns3::PacketMetadata [class] module.add_class('PacketMetadata', import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [struct] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item [enumeration] module.add_enum('', ['PAYLOAD', 'HEADER', 'TRAILER'], outer_class=root_module['ns3::PacketMetadata::Item'], import_from_module='ns.network') ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator [class] module.add_class('ItemIterator', import_from_module='ns.network', outer_class=root_module['ns3::PacketMetadata']) ## packet.h (module 'network'): ns3::PacketTagIterator [class] module.add_class('PacketTagIterator', import_from_module='ns.network') ## packet.h (module 'network'): ns3::PacketTagIterator::Item [class] module.add_class('Item', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagIterator']) ## packet-tag-list.h (module 'network'): ns3::PacketTagList [class] module.add_class('PacketTagList', import_from_module='ns.network') ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData [struct] module.add_class('TagData', import_from_module='ns.network', outer_class=root_module['ns3::PacketTagList']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Object', 'ns3::ObjectBase', 'ns3::ObjectDeleter'], parent=root_module['ns3::ObjectBase'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simulator.h (module 'core'): ns3::Simulator [class] module.add_class('Simulator', destructor_visibility='private', import_from_module='ns.core') ## tag.h (module 'network'): ns3::Tag [class] module.add_class('Tag', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## tag-buffer.h (module 'network'): ns3::TagBuffer [class] module.add_class('TagBuffer', import_from_module='ns.network') ## type-id.h (module 'core'): ns3::TypeId [class] module.add_class('TypeId', import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeFlag [enumeration] module.add_enum('AttributeFlag', ['ATTR_GET', 'ATTR_SET', 'ATTR_CONSTRUCT', 'ATTR_SGC'], outer_class=root_module['ns3::TypeId'], import_from_module='ns.core') ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation [struct] module.add_class('AttributeInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation [struct] module.add_class('TraceSourceInformation', import_from_module='ns.core', outer_class=root_module['ns3::TypeId']) ## vector.h (module 'core'): ns3::Vector2D [class] module.add_class('Vector2D', import_from_module='ns.core') ## vector.h (module 'core'): ns3::Vector3D [class] module.add_class('Vector3D', import_from_module='ns.core') ## empty.h (module 'core'): ns3::empty [class] module.add_class('empty', import_from_module='ns.core') ## int64x64-double.h (module 'core'): ns3::int64x64_t [class] module.add_class('int64x64_t', import_from_module='ns.core') ## animation-interface.h (module 'netanim'): ns3::AnimByteTag [class] module.add_class('AnimByteTag', parent=root_module['ns3::Tag']) ## chunk.h (module 'network'): ns3::Chunk [class] module.add_class('Chunk', import_from_module='ns.network', parent=root_module['ns3::ObjectBase']) ## header.h (module 'network'): ns3::Header [class] module.add_class('Header', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## object.h (module 'core'): ns3::Object [class] module.add_class('Object', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) ## object.h (module 'core'): ns3::Object::AggregateIterator [class] module.add_class('AggregateIterator', import_from_module='ns.core', outer_class=root_module['ns3::Object']) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeChecker', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeChecker>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::AttributeValue', 'ns3::empty', 'ns3::DefaultDeleter<ns3::AttributeValue>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::CallbackImplBase', 'ns3::empty', 'ns3::DefaultDeleter<ns3::CallbackImplBase>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::EventImpl', 'ns3::empty', 'ns3::DefaultDeleter<ns3::EventImpl>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::NixVector', 'ns3::empty', 'ns3::DefaultDeleter<ns3::NixVector>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::Packet', 'ns3::empty', 'ns3::DefaultDeleter<ns3::Packet>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > [class] module.add_class('SimpleRefCount', automatic_type_narrowing=True, import_from_module='ns.core', template_parameters=['ns3::TraceSourceAccessor', 'ns3::empty', 'ns3::DefaultDeleter<ns3::TraceSourceAccessor>'], parent=root_module['ns3::empty'], memory_policy=cppclass.ReferenceCountingMethodsPolicy(incref_method='Ref', decref_method='Unref', peekref_method='GetReferenceCount')) ## nstime.h (module 'core'): ns3::Time [class] module.add_class('Time', import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time::Unit [enumeration] module.add_enum('Unit', ['S', 'MS', 'US', 'NS', 'PS', 'FS', 'LAST'], outer_class=root_module['ns3::Time'], import_from_module='ns.core') ## nstime.h (module 'core'): ns3::Time [class] root_module['ns3::Time'].implicitly_converts_to(root_module['ns3::int64x64_t']) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor [class] module.add_class('TraceSourceAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) ## trailer.h (module 'network'): ns3::Trailer [class] module.add_class('Trailer', import_from_module='ns.network', parent=root_module['ns3::Chunk']) ## attribute.h (module 'core'): ns3::AttributeAccessor [class] module.add_class('AttributeAccessor', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) ## attribute.h (module 'core'): ns3::AttributeChecker [class] module.add_class('AttributeChecker', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) ## attribute.h (module 'core'): ns3::AttributeValue [class] module.add_class('AttributeValue', allow_subclassing=False, automatic_type_narrowing=True, import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) ## callback.h (module 'core'): ns3::CallbackChecker [class] module.add_class('CallbackChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## callback.h (module 'core'): ns3::CallbackImplBase [class] module.add_class('CallbackImplBase', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) ## callback.h (module 'core'): ns3::CallbackValue [class] module.add_class('CallbackValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## attribute.h (module 'core'): ns3::EmptyAttributeValue [class] module.add_class('EmptyAttributeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## event-impl.h (module 'core'): ns3::EventImpl [class] module.add_class('EventImpl', import_from_module='ns.core', parent=root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker [class] module.add_class('Ipv4AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue [class] module.add_class('Ipv4AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker [class] module.add_class('Ipv4MaskChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue [class] module.add_class('Ipv4MaskValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker [class] module.add_class('Ipv6AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue [class] module.add_class('Ipv6AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker [class] module.add_class('Ipv6PrefixChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue [class] module.add_class('Ipv6PrefixValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker [class] module.add_class('Mac48AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue [class] module.add_class('Mac48AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) ## mobility-model.h (module 'mobility'): ns3::MobilityModel [class] module.add_class('MobilityModel', import_from_module='ns.mobility', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice [class] module.add_class('NetDevice', import_from_module='ns.network', parent=root_module['ns3::Object']) ## net-device.h (module 'network'): ns3::NetDevice::PacketType [enumeration] module.add_enum('PacketType', ['PACKET_HOST', 'NS3_PACKET_HOST', 'PACKET_BROADCAST', 'NS3_PACKET_BROADCAST', 'PACKET_MULTICAST', 'NS3_PACKET_MULTICAST', 'PACKET_OTHERHOST', 'NS3_PACKET_OTHERHOST'], outer_class=root_module['ns3::NetDevice'], import_from_module='ns.network') ## nix-vector.h (module 'network'): ns3::NixVector [class] module.add_class('NixVector', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) ## node.h (module 'network'): ns3::Node [class] module.add_class('Node', import_from_module='ns.network', parent=root_module['ns3::Object']) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker [class] module.add_class('ObjectFactoryChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue [class] module.add_class('ObjectFactoryValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## packet.h (module 'network'): ns3::Packet [class] module.add_class('Packet', import_from_module='ns.network', parent=root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) ## nstime.h (module 'core'): ns3::TimeChecker [class] module.add_class('TimeChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## nstime.h (module 'core'): ns3::TimeValue [class] module.add_class('TimeValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## type-id.h (module 'core'): ns3::TypeIdChecker [class] module.add_class('TypeIdChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## type-id.h (module 'core'): ns3::TypeIdValue [class] module.add_class('TypeIdValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## vector.h (module 'core'): ns3::Vector2DChecker [class] module.add_class('Vector2DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## vector.h (module 'core'): ns3::Vector2DValue [class] module.add_class('Vector2DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## vector.h (module 'core'): ns3::Vector3DChecker [class] module.add_class('Vector3DChecker', import_from_module='ns.core', parent=root_module['ns3::AttributeChecker']) ## vector.h (module 'core'): ns3::Vector3DValue [class] module.add_class('Vector3DValue', import_from_module='ns.core', parent=root_module['ns3::AttributeValue']) ## address.h (module 'network'): ns3::AddressChecker [class] module.add_class('AddressChecker', import_from_module='ns.network', parent=root_module['ns3::AttributeChecker']) ## address.h (module 'network'): ns3::AddressValue [class] module.add_class('AddressValue', import_from_module='ns.network', parent=root_module['ns3::AttributeValue']) module.add_container('std::map< unsigned int, ns3::AnimRxInfo >', ('unsigned int', 'ns3::AnimRxInfo'), container_type='map') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *', 'ns3::LogTimePrinter') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) **', 'ns3::LogTimePrinter*') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *&', 'ns3::LogTimePrinter&') typehandlers.add_type_alias('ns3::Vector3DValue', 'ns3::VectorValue') typehandlers.add_type_alias('ns3::Vector3DValue*', 'ns3::VectorValue*') typehandlers.add_type_alias('ns3::Vector3DValue&', 'ns3::VectorValue&') module.add_typedef(root_module['ns3::Vector3DValue'], 'VectorValue') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *', 'ns3::LogNodePrinter') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) **', 'ns3::LogNodePrinter*') typehandlers.add_type_alias('void ( * ) ( std::ostream & ) *&', 'ns3::LogNodePrinter&') typehandlers.add_type_alias('ns3::Vector3D', 'ns3::Vector') typehandlers.add_type_alias('ns3::Vector3D*', 'ns3::Vector*') typehandlers.add_type_alias('ns3::Vector3D&', 'ns3::Vector&') module.add_typedef(root_module['ns3::Vector3D'], 'Vector') typehandlers.add_type_alias('ns3::Vector3DChecker', 'ns3::VectorChecker') typehandlers.add_type_alias('ns3::Vector3DChecker*', 'ns3::VectorChecker*') typehandlers.add_type_alias('ns3::Vector3DChecker&', 'ns3::VectorChecker&') module.add_typedef(root_module['ns3::Vector3DChecker'], 'VectorChecker') ## Register a nested module for the namespace Config nested_module = module.add_cpp_namespace('Config') register_types_ns3_Config(nested_module) ## Register a nested module for the namespace FatalImpl nested_module = module.add_cpp_namespace('FatalImpl') register_types_ns3_FatalImpl(nested_module) def register_types_ns3_Config(module): root_module = module.get_root() ## config.h (module 'core'): ns3::Config::MatchContainer [class] module.add_class('MatchContainer', import_from_module='ns.core') module.add_container('std::vector< ns3::Ptr< ns3::Object > >', 'ns3::Ptr< ns3::Object >', container_type='vector') module.add_container('std::vector< std::string >', 'std::string', container_type='vector') def register_types_ns3_FatalImpl(module): root_module = module.get_root() def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AnimPacketInfo_methods(root_module, root_module['ns3::AnimPacketInfo']) register_Ns3AnimRxInfo_methods(root_module, root_module['ns3::AnimRxInfo']) register_Ns3AnimationInterface_methods(root_module, root_module['ns3::AnimationInterface']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstructionList']) register_Ns3AttributeConstructionListItem_methods(root_module, root_module['ns3::AttributeConstructionList::Item']) register_Ns3Buffer_methods(root_module, root_module['ns3::Buffer']) register_Ns3BufferIterator_methods(root_module, root_module['ns3::Buffer::Iterator']) register_Ns3ByteTagIterator_methods(root_module, root_module['ns3::ByteTagIterator']) register_Ns3ByteTagIteratorItem_methods(root_module, root_module['ns3::ByteTagIterator::Item']) register_Ns3ByteTagList_methods(root_module, root_module['ns3::ByteTagList']) register_Ns3ByteTagListIterator_methods(root_module, root_module['ns3::ByteTagList::Iterator']) register_Ns3ByteTagListIteratorItem_methods(root_module, root_module['ns3::ByteTagList::Iterator::Item']) register_Ns3CallbackBase_methods(root_module, root_module['ns3::CallbackBase']) register_Ns3EventId_methods(root_module, root_module['ns3::EventId']) register_Ns3Ipv4Address_methods(root_module, root_module['ns3::Ipv4Address']) register_Ns3Ipv4Mask_methods(root_module, root_module['ns3::Ipv4Mask']) register_Ns3Ipv6Address_methods(root_module, root_module['ns3::Ipv6Address']) register_Ns3Ipv6Prefix_methods(root_module, root_module['ns3::Ipv6Prefix']) register_Ns3LogComponent_methods(root_module, root_module['ns3::LogComponent']) register_Ns3Mac48Address_methods(root_module, root_module['ns3::Mac48Address']) register_Ns3NodeContainer_methods(root_module, root_module['ns3::NodeContainer']) register_Ns3NodeList_methods(root_module, root_module['ns3::NodeList']) register_Ns3ObjectBase_methods(root_module, root_module['ns3::ObjectBase']) register_Ns3ObjectDeleter_methods(root_module, root_module['ns3::ObjectDeleter']) register_Ns3ObjectFactory_methods(root_module, root_module['ns3::ObjectFactory']) register_Ns3PacketMetadata_methods(root_module, root_module['ns3::PacketMetadata']) register_Ns3PacketMetadataItem_methods(root_module, root_module['ns3::PacketMetadata::Item']) register_Ns3PacketMetadataItemIterator_methods(root_module, root_module['ns3::PacketMetadata::ItemIterator']) register_Ns3PacketTagIterator_methods(root_module, root_module['ns3::PacketTagIterator']) register_Ns3PacketTagIteratorItem_methods(root_module, root_module['ns3::PacketTagIterator::Item']) register_Ns3PacketTagList_methods(root_module, root_module['ns3::PacketTagList']) register_Ns3PacketTagListTagData_methods(root_module, root_module['ns3::PacketTagList::TagData']) register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, root_module['ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter >']) register_Ns3Simulator_methods(root_module, root_module['ns3::Simulator']) register_Ns3Tag_methods(root_module, root_module['ns3::Tag']) register_Ns3TagBuffer_methods(root_module, root_module['ns3::TagBuffer']) register_Ns3TypeId_methods(root_module, root_module['ns3::TypeId']) register_Ns3TypeIdAttributeInformation_methods(root_module, root_module['ns3::TypeId::AttributeInformation']) register_Ns3TypeIdTraceSourceInformation_methods(root_module, root_module['ns3::TypeId::TraceSourceInformation']) register_Ns3Vector2D_methods(root_module, root_module['ns3::Vector2D']) register_Ns3Vector3D_methods(root_module, root_module['ns3::Vector3D']) register_Ns3Empty_methods(root_module, root_module['ns3::empty']) register_Ns3Int64x64_t_methods(root_module, root_module['ns3::int64x64_t']) register_Ns3AnimByteTag_methods(root_module, root_module['ns3::AnimByteTag']) register_Ns3Chunk_methods(root_module, root_module['ns3::Chunk']) register_Ns3Header_methods(root_module, root_module['ns3::Header']) register_Ns3Object_methods(root_module, root_module['ns3::Object']) register_Ns3ObjectAggregateIterator_methods(root_module, root_module['ns3::Object::AggregateIterator']) register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >']) register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >']) register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >']) register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >']) register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >']) register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >']) register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >']) register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, root_module['ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >']) register_Ns3Time_methods(root_module, root_module['ns3::Time']) register_Ns3TraceSourceAccessor_methods(root_module, root_module['ns3::TraceSourceAccessor']) register_Ns3Trailer_methods(root_module, root_module['ns3::Trailer']) register_Ns3AttributeAccessor_methods(root_module, root_module['ns3::AttributeAccessor']) register_Ns3AttributeChecker_methods(root_module, root_module['ns3::AttributeChecker']) register_Ns3AttributeValue_methods(root_module, root_module['ns3::AttributeValue']) register_Ns3CallbackChecker_methods(root_module, root_module['ns3::CallbackChecker']) register_Ns3CallbackImplBase_methods(root_module, root_module['ns3::CallbackImplBase']) register_Ns3CallbackValue_methods(root_module, root_module['ns3::CallbackValue']) register_Ns3EmptyAttributeValue_methods(root_module, root_module['ns3::EmptyAttributeValue']) register_Ns3EventImpl_methods(root_module, root_module['ns3::EventImpl']) register_Ns3Ipv4AddressChecker_methods(root_module, root_module['ns3::Ipv4AddressChecker']) register_Ns3Ipv4AddressValue_methods(root_module, root_module['ns3::Ipv4AddressValue']) register_Ns3Ipv4MaskChecker_methods(root_module, root_module['ns3::Ipv4MaskChecker']) register_Ns3Ipv4MaskValue_methods(root_module, root_module['ns3::Ipv4MaskValue']) register_Ns3Ipv6AddressChecker_methods(root_module, root_module['ns3::Ipv6AddressChecker']) register_Ns3Ipv6AddressValue_methods(root_module, root_module['ns3::Ipv6AddressValue']) register_Ns3Ipv6PrefixChecker_methods(root_module, root_module['ns3::Ipv6PrefixChecker']) register_Ns3Ipv6PrefixValue_methods(root_module, root_module['ns3::Ipv6PrefixValue']) register_Ns3Mac48AddressChecker_methods(root_module, root_module['ns3::Mac48AddressChecker']) register_Ns3Mac48AddressValue_methods(root_module, root_module['ns3::Mac48AddressValue']) register_Ns3MobilityModel_methods(root_module, root_module['ns3::MobilityModel']) register_Ns3NetDevice_methods(root_module, root_module['ns3::NetDevice']) register_Ns3NixVector_methods(root_module, root_module['ns3::NixVector']) register_Ns3Node_methods(root_module, root_module['ns3::Node']) register_Ns3ObjectFactoryChecker_methods(root_module, root_module['ns3::ObjectFactoryChecker']) register_Ns3ObjectFactoryValue_methods(root_module, root_module['ns3::ObjectFactoryValue']) register_Ns3Packet_methods(root_module, root_module['ns3::Packet']) register_Ns3TimeChecker_methods(root_module, root_module['ns3::TimeChecker']) register_Ns3TimeValue_methods(root_module, root_module['ns3::TimeValue']) register_Ns3TypeIdChecker_methods(root_module, root_module['ns3::TypeIdChecker']) register_Ns3TypeIdValue_methods(root_module, root_module['ns3::TypeIdValue']) register_Ns3Vector2DChecker_methods(root_module, root_module['ns3::Vector2DChecker']) register_Ns3Vector2DValue_methods(root_module, root_module['ns3::Vector2DValue']) register_Ns3Vector3DChecker_methods(root_module, root_module['ns3::Vector3DChecker']) register_Ns3Vector3DValue_methods(root_module, root_module['ns3::Vector3DValue']) register_Ns3AddressChecker_methods(root_module, root_module['ns3::AddressChecker']) register_Ns3AddressValue_methods(root_module, root_module['ns3::AddressValue']) register_Ns3ConfigMatchContainer_methods(root_module, root_module['ns3::Config::MatchContainer']) return def register_Ns3Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## address.h (module 'network'): ns3::Address::Address() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::Address::Address(uint8_t type, uint8_t const * buffer, uint8_t len) [constructor] cls.add_constructor([param('uint8_t', 'type'), param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): ns3::Address::Address(ns3::Address const & address) [copy constructor] cls.add_constructor([param('ns3::Address const &', 'address')]) ## address.h (module 'network'): bool ns3::Address::CheckCompatible(uint8_t type, uint8_t len) const [member function] cls.add_method('CheckCompatible', 'bool', [param('uint8_t', 'type'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyAllFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyAllTo(uint8_t * buffer, uint8_t len) const [member function] cls.add_method('CopyAllTo', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint8_t', 'len')], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::CopyFrom(uint8_t const * buffer, uint8_t len) [member function] cls.add_method('CopyFrom', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint8_t', 'len')]) ## address.h (module 'network'): uint32_t ns3::Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'uint32_t', [param('uint8_t *', 'buffer')], is_const=True) ## address.h (module 'network'): void ns3::Address::Deserialize(ns3::TagBuffer buffer) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'buffer')]) ## address.h (module 'network'): uint8_t ns3::Address::GetLength() const [member function] cls.add_method('GetLength', 'uint8_t', [], is_const=True) ## address.h (module 'network'): uint32_t ns3::Address::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsInvalid() const [member function] cls.add_method('IsInvalid', 'bool', [], is_const=True) ## address.h (module 'network'): bool ns3::Address::IsMatchingType(uint8_t type) const [member function] cls.add_method('IsMatchingType', 'bool', [param('uint8_t', 'type')], is_const=True) ## address.h (module 'network'): static uint8_t ns3::Address::Register() [member function] cls.add_method('Register', 'uint8_t', [], is_static=True) ## address.h (module 'network'): void ns3::Address::Serialize(ns3::TagBuffer buffer) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'buffer')], is_const=True) return def register_Ns3AnimPacketInfo_methods(root_module, cls): ## animation-interface-helper.h (module 'netanim'): ns3::AnimPacketInfo::AnimPacketInfo(ns3::AnimPacketInfo const & arg0) [copy constructor] cls.add_constructor([param('ns3::AnimPacketInfo const &', 'arg0')]) ## animation-interface-helper.h (module 'netanim'): ns3::AnimPacketInfo::AnimPacketInfo() [constructor] cls.add_constructor([]) ## animation-interface-helper.h (module 'netanim'): ns3::AnimPacketInfo::AnimPacketInfo(ns3::Ptr<ns3::NetDevice const> tx_nd, ns3::Time const & fbTx, ns3::Time const & lbTx, ns3::Vector txLoc, uint32_t txNodeId=0) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::NetDevice const >', 'tx_nd'), param('ns3::Time const &', 'fbTx'), param('ns3::Time const &', 'lbTx'), param('ns3::Vector', 'txLoc'), param('uint32_t', 'txNodeId', default_value='0')]) ## animation-interface-helper.h (module 'netanim'): ns3::AnimRxInfo ns3::AnimPacketInfo::GetRxInfo(ns3::Ptr<ns3::NetDevice const> nd) [member function] cls.add_method('GetRxInfo', 'ns3::AnimRxInfo', [param('ns3::Ptr< ns3::NetDevice const >', 'nd')]) ## animation-interface-helper.h (module 'netanim'): void ns3::AnimPacketInfo::ProcessRxBegin(ns3::Ptr<ns3::NetDevice const> nd, ns3::Time const & fbRx) [member function] cls.add_method('ProcessRxBegin', 'void', [param('ns3::Ptr< ns3::NetDevice const >', 'nd'), param('ns3::Time const &', 'fbRx')]) ## animation-interface-helper.h (module 'netanim'): void ns3::AnimPacketInfo::ProcessRxDrop(ns3::Ptr<ns3::NetDevice const> nd) [member function] cls.add_method('ProcessRxDrop', 'void', [param('ns3::Ptr< ns3::NetDevice const >', 'nd')]) ## animation-interface-helper.h (module 'netanim'): bool ns3::AnimPacketInfo::ProcessRxEnd(ns3::Ptr<ns3::NetDevice const> nd, ns3::Time const & fbRx, ns3::Vector rxLoc) [member function] cls.add_method('ProcessRxEnd', 'bool', [param('ns3::Ptr< ns3::NetDevice const >', 'nd'), param('ns3::Time const &', 'fbRx'), param('ns3::Vector', 'rxLoc')]) ## animation-interface-helper.h (module 'netanim'): void ns3::AnimPacketInfo::RemoveRxInfo(ns3::Ptr<ns3::NetDevice const> nd) [member function] cls.add_method('RemoveRxInfo', 'void', [param('ns3::Ptr< ns3::NetDevice const >', 'nd')]) ## animation-interface-helper.h (module 'netanim'): ns3::AnimPacketInfo::firstlastbitDelta [variable] cls.add_instance_attribute('firstlastbitDelta', 'double', is_const=False) ## animation-interface-helper.h (module 'netanim'): ns3::AnimPacketInfo::m_fbTx [variable] cls.add_instance_attribute('m_fbTx', 'double', is_const=False) ## animation-interface-helper.h (module 'netanim'): ns3::AnimPacketInfo::m_lbTx [variable] cls.add_instance_attribute('m_lbTx', 'double', is_const=False) ## animation-interface-helper.h (module 'netanim'): ns3::AnimPacketInfo::m_rx [variable] cls.add_instance_attribute('m_rx', 'std::map< unsigned int, ns3::AnimRxInfo >', is_const=False) ## animation-interface-helper.h (module 'netanim'): ns3::AnimPacketInfo::m_txLoc [variable] cls.add_instance_attribute('m_txLoc', 'ns3::Vector', is_const=False) ## animation-interface-helper.h (module 'netanim'): ns3::AnimPacketInfo::m_txNodeId [variable] cls.add_instance_attribute('m_txNodeId', 'uint32_t', is_const=False) ## animation-interface-helper.h (module 'netanim'): ns3::AnimPacketInfo::m_txnd [variable] cls.add_instance_attribute('m_txnd', 'ns3::Ptr< ns3::NetDevice const >', is_const=False) return def register_Ns3AnimRxInfo_methods(root_module, cls): ## animation-interface-helper.h (module 'netanim'): ns3::AnimRxInfo::AnimRxInfo(ns3::AnimRxInfo const & arg0) [copy constructor] cls.add_constructor([param('ns3::AnimRxInfo const &', 'arg0')]) ## animation-interface-helper.h (module 'netanim'): ns3::AnimRxInfo::AnimRxInfo() [constructor] cls.add_constructor([]) ## animation-interface-helper.h (module 'netanim'): ns3::AnimRxInfo::AnimRxInfo(ns3::Time const & fbRx, ns3::Ptr<ns3::NetDevice const> nd, double rxRange) [constructor] cls.add_constructor([param('ns3::Time const &', 'fbRx'), param('ns3::Ptr< ns3::NetDevice const >', 'nd'), param('double', 'rxRange')]) ## animation-interface-helper.h (module 'netanim'): bool ns3::AnimRxInfo::IsPhyRxComplete() [member function] cls.add_method('IsPhyRxComplete', 'bool', []) ## animation-interface-helper.h (module 'netanim'): void ns3::AnimRxInfo::SetPhyRxComplete() [member function] cls.add_method('SetPhyRxComplete', 'void', []) ## animation-interface-helper.h (module 'netanim'): ns3::AnimRxInfo::m_fbRx [variable] cls.add_instance_attribute('m_fbRx', 'double', is_const=False) ## animation-interface-helper.h (module 'netanim'): ns3::AnimRxInfo::m_lbRx [variable] cls.add_instance_attribute('m_lbRx', 'double', is_const=False) ## animation-interface-helper.h (module 'netanim'): ns3::AnimRxInfo::m_rxnd [variable] cls.add_instance_attribute('m_rxnd', 'ns3::Ptr< ns3::NetDevice const >', is_const=False) ## animation-interface-helper.h (module 'netanim'): ns3::AnimRxInfo::rxRange [variable] cls.add_instance_attribute('rxRange', 'double', is_const=False) return def register_Ns3AnimationInterface_methods(root_module, cls): ## animation-interface.h (module 'netanim'): ns3::AnimationInterface::AnimationInterface(ns3::AnimationInterface const & arg0) [copy constructor] cls.add_constructor([param('ns3::AnimationInterface const &', 'arg0')]) ## animation-interface.h (module 'netanim'): ns3::AnimationInterface::AnimationInterface() [constructor] cls.add_constructor([]) ## animation-interface.h (module 'netanim'): ns3::AnimationInterface::AnimationInterface(std::string const filename, uint64_t maxPktsPerFile=100000, bool usingXML=true) [constructor] cls.add_constructor([param('std::string const', 'filename'), param('uint64_t', 'maxPktsPerFile', default_value='100000'), param('bool', 'usingXML', default_value='true')]) ## animation-interface.h (module 'netanim'): ns3::AnimationInterface::AnimationInterface(uint16_t port, bool usingXML=true) [constructor] cls.add_constructor([param('uint16_t', 'port'), param('bool', 'usingXML', default_value='true')]) ## animation-interface.h (module 'netanim'): void ns3::AnimationInterface::EnablePacketMetadata(bool enable) [member function] cls.add_method('EnablePacketMetadata', 'void', [param('bool', 'enable')]) ## animation-interface.h (module 'netanim'): uint64_t ns3::AnimationInterface::GetTracePktCount() [member function] cls.add_method('GetTracePktCount', 'uint64_t', []) ## animation-interface.h (module 'netanim'): static bool ns3::AnimationInterface::IsInitialized() [member function] cls.add_method('IsInitialized', 'bool', [], is_static=True) ## animation-interface.h (module 'netanim'): bool ns3::AnimationInterface::IsStarted() [member function] cls.add_method('IsStarted', 'bool', []) ## animation-interface.h (module 'netanim'): void ns3::AnimationInterface::ResetAnimWriteCallback() [member function] cls.add_method('ResetAnimWriteCallback', 'void', []) ## animation-interface.h (module 'netanim'): void ns3::AnimationInterface::SetAnimWriteCallback(void (*)( char const * ) * cb) [member function] cls.add_method('SetAnimWriteCallback', 'void', [param('void ( * ) ( char const * ) *', 'cb')]) ## animation-interface.h (module 'netanim'): static void ns3::AnimationInterface::SetConstantPosition(ns3::Ptr<ns3::Node> n, double x, double y, double z=0) [member function] cls.add_method('SetConstantPosition', 'void', [param('ns3::Ptr< ns3::Node >', 'n'), param('double', 'x'), param('double', 'y'), param('double', 'z', default_value='0')], is_static=True) ## animation-interface.h (module 'netanim'): void ns3::AnimationInterface::SetMobilityPollInterval(ns3::Time t) [member function] cls.add_method('SetMobilityPollInterval', 'void', [param('ns3::Time', 't')]) ## animation-interface.h (module 'netanim'): static void ns3::AnimationInterface::SetNodeDescription(ns3::Ptr<ns3::Node> n, std::string descr) [member function] cls.add_method('SetNodeDescription', 'void', [param('ns3::Ptr< ns3::Node >', 'n'), param('std::string', 'descr')], is_static=True) ## animation-interface.h (module 'netanim'): static void ns3::AnimationInterface::SetNodeDescription(ns3::NodeContainer nc, std::string descr) [member function] cls.add_method('SetNodeDescription', 'void', [param('ns3::NodeContainer', 'nc'), param('std::string', 'descr')], is_static=True) ## animation-interface.h (module 'netanim'): bool ns3::AnimationInterface::SetOutputFile(std::string const & fn) [member function] cls.add_method('SetOutputFile', 'bool', [param('std::string const &', 'fn')]) ## animation-interface.h (module 'netanim'): void ns3::AnimationInterface::SetRandomPosition(bool setRandPos) [member function] cls.add_method('SetRandomPosition', 'void', [param('bool', 'setRandPos')]) ## animation-interface.h (module 'netanim'): bool ns3::AnimationInterface::SetServerPort(uint16_t port) [member function] cls.add_method('SetServerPort', 'bool', [param('uint16_t', 'port')]) ## animation-interface.h (module 'netanim'): void ns3::AnimationInterface::SetStartTime(ns3::Time t) [member function] cls.add_method('SetStartTime', 'void', [param('ns3::Time', 't')]) ## animation-interface.h (module 'netanim'): void ns3::AnimationInterface::SetStopTime(ns3::Time t) [member function] cls.add_method('SetStopTime', 'void', [param('ns3::Time', 't')]) ## animation-interface.h (module 'netanim'): void ns3::AnimationInterface::SetXMLOutput() [member function] cls.add_method('SetXMLOutput', 'void', []) ## animation-interface.h (module 'netanim'): void ns3::AnimationInterface::ShowAll802_11(bool showAll) [member function] cls.add_method('ShowAll802_11', 'void', [param('bool', 'showAll')]) ## animation-interface.h (module 'netanim'): void ns3::AnimationInterface::StartAnimation(bool restart=false) [member function] cls.add_method('StartAnimation', 'void', [param('bool', 'restart', default_value='false')]) ## animation-interface.h (module 'netanim'): void ns3::AnimationInterface::StopAnimation() [member function] cls.add_method('StopAnimation', 'void', []) return def register_Ns3AttributeConstructionList_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList(ns3::AttributeConstructionList const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::AttributeConstructionList() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): void ns3::AttributeConstructionList::Add(std::string name, ns3::Ptr<ns3::AttributeChecker const> checker, ns3::Ptr<ns3::AttributeValue> value) [member function] cls.add_method('Add', 'void', [param('std::string', 'name'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker'), param('ns3::Ptr< ns3::AttributeValue >', 'value')]) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::Begin() const [member function] cls.add_method('Begin', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): std::_List_const_iterator<ns3::AttributeConstructionList::Item> ns3::AttributeConstructionList::End() const [member function] cls.add_method('End', 'std::_List_const_iterator< ns3::AttributeConstructionList::Item >', [], is_const=True) ## attribute-construction-list.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeConstructionList::Find(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('Find', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True) return def register_Ns3AttributeConstructionListItem_methods(root_module, cls): ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item() [constructor] cls.add_constructor([]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::Item(ns3::AttributeConstructionList::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeConstructionList::Item const &', 'arg0')]) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## attribute-construction-list.h (module 'core'): ns3::AttributeConstructionList::Item::value [variable] cls.add_instance_attribute('value', 'ns3::Ptr< ns3::AttributeValue >', is_const=False) return def register_Ns3Buffer_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Buffer() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(uint32_t dataSize, bool initialize) [constructor] cls.add_constructor([param('uint32_t', 'dataSize'), param('bool', 'initialize')]) ## buffer.h (module 'network'): ns3::Buffer::Buffer(ns3::Buffer const & o) [copy constructor] cls.add_constructor([param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtEnd(uint32_t end) [member function] cls.add_method('AddAtEnd', 'bool', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::AddAtEnd(ns3::Buffer const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Buffer const &', 'o')]) ## buffer.h (module 'network'): bool ns3::Buffer::AddAtStart(uint32_t start) [member function] cls.add_method('AddAtStart', 'bool', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::Begin() const [member function] cls.add_method('Begin', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Buffer', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## buffer.h (module 'network'): ns3::Buffer ns3::Buffer::CreateFullCopy() const [member function] cls.add_method('CreateFullCopy', 'ns3::Buffer', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator ns3::Buffer::End() const [member function] cls.add_method('End', 'ns3::Buffer::Iterator', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentEndOffset() const [member function] cls.add_method('GetCurrentEndOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): int32_t ns3::Buffer::GetCurrentStartOffset() const [member function] cls.add_method('GetCurrentStartOffset', 'int32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): uint8_t const * ns3::Buffer::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3BufferIterator_methods(root_module, cls): ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator(ns3::Buffer::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Buffer::Iterator const &', 'arg0')]) ## buffer.h (module 'network'): ns3::Buffer::Iterator::Iterator() [constructor] cls.add_constructor([]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::CalculateIpChecksum(uint16_t size, uint32_t initialChecksum) [member function] cls.add_method('CalculateIpChecksum', 'uint16_t', [param('uint16_t', 'size'), param('uint32_t', 'initialChecksum')]) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetDistanceFrom(ns3::Buffer::Iterator const & o) const [member function] cls.add_method('GetDistanceFrom', 'uint32_t', [param('ns3::Buffer::Iterator const &', 'o')], is_const=True) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsEnd() const [member function] cls.add_method('IsEnd', 'bool', [], is_const=True) ## buffer.h (module 'network'): bool ns3::Buffer::Iterator::IsStart() const [member function] cls.add_method('IsStart', 'bool', [], is_const=True) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next() [member function] cls.add_method('Next', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Next(uint32_t delta) [member function] cls.add_method('Next', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev() [member function] cls.add_method('Prev', 'void', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Prev(uint32_t delta) [member function] cls.add_method('Prev', 'void', [param('uint32_t', 'delta')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadLsbtohU16() [member function] cls.add_method('ReadLsbtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadLsbtohU32() [member function] cls.add_method('ReadLsbtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadLsbtohU64() [member function] cls.add_method('ReadLsbtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadNtohU16() [member function] cls.add_method('ReadNtohU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadNtohU32() [member function] cls.add_method('ReadNtohU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadNtohU64() [member function] cls.add_method('ReadNtohU64', 'uint64_t', []) ## buffer.h (module 'network'): uint16_t ns3::Buffer::Iterator::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## buffer.h (module 'network'): uint32_t ns3::Buffer::Iterator::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## buffer.h (module 'network'): uint64_t ns3::Buffer::Iterator::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## buffer.h (module 'network'): uint8_t ns3::Buffer::Iterator::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::Write(ns3::Buffer::Iterator start, ns3::Buffer::Iterator end) [member function] cls.add_method('Write', 'void', [param('ns3::Buffer::Iterator', 'start'), param('ns3::Buffer::Iterator', 'end')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU16(uint16_t data) [member function] cls.add_method('WriteHtolsbU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU32(uint32_t data) [member function] cls.add_method('WriteHtolsbU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtolsbU64(uint64_t data) [member function] cls.add_method('WriteHtolsbU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU16(uint16_t data) [member function] cls.add_method('WriteHtonU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU32(uint32_t data) [member function] cls.add_method('WriteHtonU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteHtonU64(uint64_t data) [member function] cls.add_method('WriteHtonU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU64(uint64_t data) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data')]) ## buffer.h (module 'network'): void ns3::Buffer::Iterator::WriteU8(uint8_t data, uint32_t len) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'data'), param('uint32_t', 'len')]) return def register_Ns3ByteTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::ByteTagIterator(ns3::ByteTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::ByteTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator::Item ns3::ByteTagIterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagIterator::Item', []) return def register_Ns3ByteTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::ByteTagIterator::Item::Item(ns3::ByteTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetEnd() const [member function] cls.add_method('GetEnd', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::ByteTagIterator::Item::GetStart() const [member function] cls.add_method('GetStart', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): void ns3::ByteTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::ByteTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3ByteTagList_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList() [constructor] cls.add_constructor([]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::ByteTagList(ns3::ByteTagList const & o) [copy constructor] cls.add_constructor([param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): ns3::TagBuffer ns3::ByteTagList::Add(ns3::TypeId tid, uint32_t bufferSize, int32_t start, int32_t end) [member function] cls.add_method('Add', 'ns3::TagBuffer', [param('ns3::TypeId', 'tid'), param('uint32_t', 'bufferSize'), param('int32_t', 'start'), param('int32_t', 'end')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::Add(ns3::ByteTagList const & o) [member function] cls.add_method('Add', 'void', [param('ns3::ByteTagList const &', 'o')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtEnd(int32_t adjustment, int32_t appendOffset) [member function] cls.add_method('AddAtEnd', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'appendOffset')]) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::AddAtStart(int32_t adjustment, int32_t prependOffset) [member function] cls.add_method('AddAtStart', 'void', [param('int32_t', 'adjustment'), param('int32_t', 'prependOffset')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator ns3::ByteTagList::Begin(int32_t offsetStart, int32_t offsetEnd) const [member function] cls.add_method('Begin', 'ns3::ByteTagList::Iterator', [param('int32_t', 'offsetStart'), param('int32_t', 'offsetEnd')], is_const=True) ## byte-tag-list.h (module 'network'): void ns3::ByteTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3ByteTagListIterator_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Iterator(ns3::ByteTagList::Iterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator const &', 'arg0')]) ## byte-tag-list.h (module 'network'): uint32_t ns3::ByteTagList::Iterator::GetOffsetStart() const [member function] cls.add_method('GetOffsetStart', 'uint32_t', [], is_const=True) ## byte-tag-list.h (module 'network'): bool ns3::ByteTagList::Iterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item ns3::ByteTagList::Iterator::Next() [member function] cls.add_method('Next', 'ns3::ByteTagList::Iterator::Item', []) return def register_Ns3ByteTagListIteratorItem_methods(root_module, cls): ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::ByteTagList::Iterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::ByteTagList::Iterator::Item const &', 'arg0')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::Item(ns3::TagBuffer buf) [constructor] cls.add_constructor([param('ns3::TagBuffer', 'buf')]) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::buf [variable] cls.add_instance_attribute('buf', 'ns3::TagBuffer', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::end [variable] cls.add_instance_attribute('end', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::size [variable] cls.add_instance_attribute('size', 'uint32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::start [variable] cls.add_instance_attribute('start', 'int32_t', is_const=False) ## byte-tag-list.h (module 'network'): ns3::ByteTagList::Iterator::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3CallbackBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::CallbackBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::Ptr<ns3::CallbackImplBase> ns3::CallbackBase::GetImpl() const [member function] cls.add_method('GetImpl', 'ns3::Ptr< ns3::CallbackImplBase >', [], is_const=True) ## callback.h (module 'core'): ns3::CallbackBase::CallbackBase(ns3::Ptr<ns3::CallbackImplBase> impl) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::CallbackImplBase >', 'impl')], visibility='protected') ## callback.h (module 'core'): static std::string ns3::CallbackBase::Demangle(std::string const & mangled) [member function] cls.add_method('Demangle', 'std::string', [param('std::string const &', 'mangled')], is_static=True, visibility='protected') return def register_Ns3EventId_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_binary_comparison_operator('==') ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::EventId const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventId const &', 'arg0')]) ## event-id.h (module 'core'): ns3::EventId::EventId() [constructor] cls.add_constructor([]) ## event-id.h (module 'core'): ns3::EventId::EventId(ns3::Ptr<ns3::EventImpl> const & impl, uint64_t ts, uint32_t context, uint32_t uid) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::EventImpl > const &', 'impl'), param('uint64_t', 'ts'), param('uint32_t', 'context'), param('uint32_t', 'uid')]) ## event-id.h (module 'core'): void ns3::EventId::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetContext() const [member function] cls.add_method('GetContext', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): uint64_t ns3::EventId::GetTs() const [member function] cls.add_method('GetTs', 'uint64_t', [], is_const=True) ## event-id.h (module 'core'): uint32_t ns3::EventId::GetUid() const [member function] cls.add_method('GetUid', 'uint32_t', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsExpired() const [member function] cls.add_method('IsExpired', 'bool', [], is_const=True) ## event-id.h (module 'core'): bool ns3::EventId::IsRunning() const [member function] cls.add_method('IsRunning', 'bool', [], is_const=True) ## event-id.h (module 'core'): ns3::EventImpl * ns3::EventId::PeekEventImpl() const [member function] cls.add_method('PeekEventImpl', 'ns3::EventImpl *', [], is_const=True) return def register_Ns3Ipv4Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(ns3::Ipv4Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(uint32_t address) [constructor] cls.add_constructor([param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address::Ipv4Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::CombineMask(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('CombineMask', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv4Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv4Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Address::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4Address::GetSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('GetSubnetDirectedBroadcast', 'ns3::Ipv4Address', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Address ns3::Ipv4Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Address', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsEqual(ns3::Ipv4Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Address const &', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsLocalMulticast() const [member function] cls.add_method('IsLocalMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): static bool ns3::Ipv4Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Address::IsSubnetDirectedBroadcast(ns3::Ipv4Mask const & mask) const [member function] cls.add_method('IsSubnetDirectedBroadcast', 'bool', [param('ns3::Ipv4Mask const &', 'mask')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(uint32_t address) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'address')]) ## ipv4-address.h (module 'network'): void ns3::Ipv4Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) return def register_Ns3Ipv4Mask_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(ns3::Ipv4Mask const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(uint32_t mask) [constructor] cls.add_constructor([param('uint32_t', 'mask')]) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask::Ipv4Mask(char const * mask) [constructor] cls.add_constructor([param('char const *', 'mask')]) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::Get() const [member function] cls.add_method('Get', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): uint32_t ns3::Ipv4Mask::GetInverse() const [member function] cls.add_method('GetInverse', 'uint32_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): uint16_t ns3::Ipv4Mask::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint16_t', [], is_const=True) ## ipv4-address.h (module 'network'): static ns3::Ipv4Mask ns3::Ipv4Mask::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv4Mask', [], is_static=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsEqual(ns3::Ipv4Mask other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv4Mask', 'other')], is_const=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4Mask::IsMatch(ns3::Ipv4Address a, ns3::Ipv4Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv4Address', 'a'), param('ns3::Ipv4Address', 'b')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4Mask::Set(uint32_t mask) [member function] cls.add_method('Set', 'void', [param('uint32_t', 'mask')]) return def register_Ns3Ipv6Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(char const * address) [constructor] cls.add_constructor([param('char const *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(uint8_t * address) [constructor] cls.add_constructor([param('uint8_t *', 'address')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const & addr) [copy constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address::Ipv6Address(ns3::Ipv6Address const * addr) [constructor] cls.add_constructor([param('ns3::Ipv6Address const *', 'addr')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6Address::CombinePrefix(ns3::Ipv6Prefix const & prefix) [member function] cls.add_method('CombinePrefix', 'ns3::Ipv6Address', [param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Ipv6Address', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::Deserialize(uint8_t const * buf) [member function] cls.add_method('Deserialize', 'ns3::Ipv6Address', [param('uint8_t const *', 'buf')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllHostsMulticast() [member function] cls.add_method('GetAllHostsMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllNodesMulticast() [member function] cls.add_method('GetAllNodesMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAllRoutersMulticast() [member function] cls.add_method('GetAllRoutersMulticast', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetAny() [member function] cls.add_method('GetAny', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv6Address::GetIpv4MappedAddress() const [member function] cls.add_method('GetIpv4MappedAddress', 'ns3::Ipv4Address', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Address', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllHostsMulticast() const [member function] cls.add_method('IsAllHostsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllNodesMulticast() const [member function] cls.add_method('IsAllNodesMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAllRoutersMulticast() const [member function] cls.add_method('IsAllRoutersMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsAny() const [member function] cls.add_method('IsAny', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsEqual(ns3::Ipv6Address const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Address const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsIpv4MappedAddress() [member function] cls.add_method('IsIpv4MappedAddress', 'bool', []) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocal() const [member function] cls.add_method('IsLinkLocal', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLinkLocalMulticast() const [member function] cls.add_method('IsLinkLocalMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsLocalhost() const [member function] cls.add_method('IsLocalhost', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static bool ns3::Ipv6Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Address::IsSolicitedMulticast() const [member function] cls.add_method('IsSolicitedMulticast', 'bool', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredAddress(ns3::Mac48Address addr, ns3::Ipv6Address prefix) [member function] cls.add_method('MakeAutoconfiguredAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'addr'), param('ns3::Ipv6Address', 'prefix')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeAutoconfiguredLinkLocalAddress(ns3::Mac48Address mac) [member function] cls.add_method('MakeAutoconfiguredLinkLocalAddress', 'ns3::Ipv6Address', [param('ns3::Mac48Address', 'mac')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeIpv4MappedAddress(ns3::Ipv4Address addr) [member function] cls.add_method('MakeIpv4MappedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv4Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Address ns3::Ipv6Address::MakeSolicitedAddress(ns3::Ipv6Address addr) [member function] cls.add_method('MakeSolicitedAddress', 'ns3::Ipv6Address', [param('ns3::Ipv6Address', 'addr')], is_static=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Serialize(uint8_t * buf) const [member function] cls.add_method('Serialize', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(char const * address) [member function] cls.add_method('Set', 'void', [param('char const *', 'address')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Address::Set(uint8_t * address) [member function] cls.add_method('Set', 'void', [param('uint8_t *', 'address')]) return def register_Ns3Ipv6Prefix_methods(root_module, cls): cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t * prefix) [constructor] cls.add_constructor([param('uint8_t *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(char const * prefix) [constructor] cls.add_constructor([param('char const *', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(uint8_t prefix) [constructor] cls.add_constructor([param('uint8_t', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const & prefix) [copy constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'prefix')]) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix::Ipv6Prefix(ns3::Ipv6Prefix const * prefix) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const *', 'prefix')]) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::GetBytes(uint8_t * buf) const [member function] cls.add_method('GetBytes', 'void', [param('uint8_t *', 'buf')], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetLoopback() [member function] cls.add_method('GetLoopback', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetOnes() [member function] cls.add_method('GetOnes', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): uint8_t ns3::Ipv6Prefix::GetPrefixLength() const [member function] cls.add_method('GetPrefixLength', 'uint8_t', [], is_const=True) ## ipv6-address.h (module 'network'): static ns3::Ipv6Prefix ns3::Ipv6Prefix::GetZero() [member function] cls.add_method('GetZero', 'ns3::Ipv6Prefix', [], is_static=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsEqual(ns3::Ipv6Prefix const & other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ipv6Prefix const &', 'other')], is_const=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6Prefix::IsMatch(ns3::Ipv6Address a, ns3::Ipv6Address b) const [member function] cls.add_method('IsMatch', 'bool', [param('ns3::Ipv6Address', 'a'), param('ns3::Ipv6Address', 'b')], is_const=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6Prefix::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) return def register_Ns3LogComponent_methods(root_module, cls): ## log.h (module 'core'): ns3::LogComponent::LogComponent(ns3::LogComponent const & arg0) [copy constructor] cls.add_constructor([param('ns3::LogComponent const &', 'arg0')]) ## log.h (module 'core'): ns3::LogComponent::LogComponent(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## log.h (module 'core'): void ns3::LogComponent::Disable(ns3::LogLevel level) [member function] cls.add_method('Disable', 'void', [param('ns3::LogLevel', 'level')]) ## log.h (module 'core'): void ns3::LogComponent::Enable(ns3::LogLevel level) [member function] cls.add_method('Enable', 'void', [param('ns3::LogLevel', 'level')]) ## log.h (module 'core'): void ns3::LogComponent::EnvVarCheck(char const * name) [member function] cls.add_method('EnvVarCheck', 'void', [param('char const *', 'name')]) ## log.h (module 'core'): bool ns3::LogComponent::IsEnabled(ns3::LogLevel level) const [member function] cls.add_method('IsEnabled', 'bool', [param('ns3::LogLevel', 'level')], is_const=True) ## log.h (module 'core'): bool ns3::LogComponent::IsNoneEnabled() const [member function] cls.add_method('IsNoneEnabled', 'bool', [], is_const=True) ## log.h (module 'core'): char const * ns3::LogComponent::Name() const [member function] cls.add_method('Name', 'char const *', [], is_const=True) return def register_Ns3Mac48Address_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(ns3::Mac48Address const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48Address::Mac48Address(char const * str) [constructor] cls.add_constructor([param('char const *', 'str')]) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::Allocate() [member function] cls.add_method('Allocate', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::ConvertFrom(ns3::Address const & address) [member function] cls.add_method('ConvertFrom', 'ns3::Mac48Address', [param('ns3::Address const &', 'address')], is_static=True) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyFrom(uint8_t const * buffer) [member function] cls.add_method('CopyFrom', 'void', [param('uint8_t const *', 'buffer')]) ## mac48-address.h (module 'network'): void ns3::Mac48Address::CopyTo(uint8_t * buffer) const [member function] cls.add_method('CopyTo', 'void', [param('uint8_t *', 'buffer')], is_const=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetBroadcast() [member function] cls.add_method('GetBroadcast', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv4Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv4Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast(ns3::Ipv6Address address) [member function] cls.add_method('GetMulticast', 'ns3::Mac48Address', [param('ns3::Ipv6Address', 'address')], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticast6Prefix() [member function] cls.add_method('GetMulticast6Prefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): static ns3::Mac48Address ns3::Mac48Address::GetMulticastPrefix() [member function] cls.add_method('GetMulticastPrefix', 'ns3::Mac48Address', [], is_static=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): bool ns3::Mac48Address::IsGroup() const [member function] cls.add_method('IsGroup', 'bool', [], is_const=True) ## mac48-address.h (module 'network'): static bool ns3::Mac48Address::IsMatchingType(ns3::Address const & address) [member function] cls.add_method('IsMatchingType', 'bool', [param('ns3::Address const &', 'address')], is_static=True) return def register_Ns3NodeContainer_methods(root_module, cls): ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'arg0')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer() [constructor] cls.add_constructor([]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::Ptr<ns3::Node> node) [constructor] cls.add_constructor([param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(std::string nodeName) [constructor] cls.add_constructor([param('std::string', 'nodeName')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd')]) ## node-container.h (module 'network'): ns3::NodeContainer::NodeContainer(ns3::NodeContainer const & a, ns3::NodeContainer const & b, ns3::NodeContainer const & c, ns3::NodeContainer const & d, ns3::NodeContainer const & e) [constructor] cls.add_constructor([param('ns3::NodeContainer const &', 'a'), param('ns3::NodeContainer const &', 'b'), param('ns3::NodeContainer const &', 'c'), param('ns3::NodeContainer const &', 'd'), param('ns3::NodeContainer const &', 'e')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::NodeContainer other) [member function] cls.add_method('Add', 'void', [param('ns3::NodeContainer', 'other')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Add(std::string nodeName) [member function] cls.add_method('Add', 'void', [param('std::string', 'nodeName')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n')]) ## node-container.h (module 'network'): void ns3::NodeContainer::Create(uint32_t n, uint32_t systemId) [member function] cls.add_method('Create', 'void', [param('uint32_t', 'n'), param('uint32_t', 'systemId')]) ## node-container.h (module 'network'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_const=True) ## node-container.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NodeContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'i')], is_const=True) ## node-container.h (module 'network'): static ns3::NodeContainer ns3::NodeContainer::GetGlobal() [member function] cls.add_method('GetGlobal', 'ns3::NodeContainer', [], is_static=True) ## node-container.h (module 'network'): uint32_t ns3::NodeContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) return def register_Ns3NodeList_methods(root_module, cls): ## node-list.h (module 'network'): ns3::NodeList::NodeList() [constructor] cls.add_constructor([]) ## node-list.h (module 'network'): ns3::NodeList::NodeList(ns3::NodeList const & arg0) [copy constructor] cls.add_constructor([param('ns3::NodeList const &', 'arg0')]) ## node-list.h (module 'network'): static uint32_t ns3::NodeList::Add(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('Add', 'uint32_t', [param('ns3::Ptr< ns3::Node >', 'node')], is_static=True) ## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::Begin() [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_static=True) ## node-list.h (module 'network'): static __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Node>*,std::vector<ns3::Ptr<ns3::Node>, std::allocator<ns3::Ptr<ns3::Node> > > > ns3::NodeList::End() [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Node > const, std::vector< ns3::Ptr< ns3::Node > > >', [], is_static=True) ## node-list.h (module 'network'): static uint32_t ns3::NodeList::GetNNodes() [member function] cls.add_method('GetNNodes', 'uint32_t', [], is_static=True) ## node-list.h (module 'network'): static ns3::Ptr<ns3::Node> ns3::NodeList::GetNode(uint32_t n) [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [param('uint32_t', 'n')], is_static=True) return def register_Ns3ObjectBase_methods(root_module, cls): ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase() [constructor] cls.add_constructor([]) ## object-base.h (module 'core'): ns3::ObjectBase::ObjectBase(ns3::ObjectBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectBase const &', 'arg0')]) ## object-base.h (module 'core'): void ns3::ObjectBase::GetAttribute(std::string name, ns3::AttributeValue & value) const [member function] cls.add_method('GetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue &', 'value')], is_const=True) ## object-base.h (module 'core'): bool ns3::ObjectBase::GetAttributeFailSafe(std::string name, ns3::AttributeValue & attribute) const [member function] cls.add_method('GetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue &', 'attribute')], is_const=True) ## object-base.h (module 'core'): ns3::TypeId ns3::ObjectBase::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## object-base.h (module 'core'): static ns3::TypeId ns3::ObjectBase::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object-base.h (module 'core'): void ns3::ObjectBase::SetAttribute(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttribute', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::SetAttributeFailSafe(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('SetAttributeFailSafe', 'bool', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceConnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnect(std::string name, std::string context, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnect', 'bool', [param('std::string', 'name'), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): bool ns3::ObjectBase::TraceDisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('TraceDisconnectWithoutContext', 'bool', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## object-base.h (module 'core'): void ns3::ObjectBase::ConstructSelf(ns3::AttributeConstructionList const & attributes) [member function] cls.add_method('ConstructSelf', 'void', [param('ns3::AttributeConstructionList const &', 'attributes')], visibility='protected') ## object-base.h (module 'core'): void ns3::ObjectBase::NotifyConstructionCompleted() [member function] cls.add_method('NotifyConstructionCompleted', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectDeleter_methods(root_module, cls): ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter() [constructor] cls.add_constructor([]) ## object.h (module 'core'): ns3::ObjectDeleter::ObjectDeleter(ns3::ObjectDeleter const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectDeleter const &', 'arg0')]) ## object.h (module 'core'): static void ns3::ObjectDeleter::Delete(ns3::Object * object) [member function] cls.add_method('Delete', 'void', [param('ns3::Object *', 'object')], is_static=True) return def register_Ns3ObjectFactory_methods(root_module, cls): cls.add_output_stream_operator() ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(ns3::ObjectFactory const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactory::ObjectFactory(std::string typeId) [constructor] cls.add_constructor([param('std::string', 'typeId')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::Object> ns3::ObjectFactory::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::Object >', [], is_const=True) ## object-factory.h (module 'core'): ns3::TypeId ns3::ObjectFactory::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) ## object-factory.h (module 'core'): void ns3::ObjectFactory::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(ns3::TypeId tid) [member function] cls.add_method('SetTypeId', 'void', [param('ns3::TypeId', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(char const * tid) [member function] cls.add_method('SetTypeId', 'void', [param('char const *', 'tid')]) ## object-factory.h (module 'core'): void ns3::ObjectFactory::SetTypeId(std::string tid) [member function] cls.add_method('SetTypeId', 'void', [param('std::string', 'tid')]) return def register_Ns3PacketMetadata_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(uint64_t uid, uint32_t size) [constructor] cls.add_constructor([param('uint64_t', 'uid'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::PacketMetadata(ns3::PacketMetadata const & o) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddAtEnd(ns3::PacketMetadata const & o) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::PacketMetadata const &', 'o')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddPaddingAtEnd(uint32_t end) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::AddTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::PacketMetadata::BeginItem(ns3::Buffer buffer) const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [param('ns3::Buffer', 'buffer')], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata ns3::PacketMetadata::CreateFragment(uint32_t start, uint32_t end) const [member function] cls.add_method('CreateFragment', 'ns3::PacketMetadata', [param('uint32_t', 'start'), param('uint32_t', 'end')], is_const=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Deserialize(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::Enable() [member function] cls.add_method('Enable', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): static void ns3::PacketMetadata::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet-metadata.h (module 'network'): uint64_t ns3::PacketMetadata::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtEnd(uint32_t end) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'end')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveAtStart(uint32_t start) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'start')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveHeader(ns3::Header const & header, uint32_t size) [member function] cls.add_method('RemoveHeader', 'void', [param('ns3::Header const &', 'header'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): void ns3::PacketMetadata::RemoveTrailer(ns3::Trailer const & trailer, uint32_t size) [member function] cls.add_method('RemoveTrailer', 'void', [param('ns3::Trailer const &', 'trailer'), param('uint32_t', 'size')]) ## packet-metadata.h (module 'network'): uint32_t ns3::PacketMetadata::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3PacketMetadataItem_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item() [constructor] cls.add_constructor([]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::Item(ns3::PacketMetadata::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::Item const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::current [variable] cls.add_instance_attribute('current', 'ns3::Buffer::Iterator', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentSize [variable] cls.add_instance_attribute('currentSize', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromEnd [variable] cls.add_instance_attribute('currentTrimedFromEnd', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::currentTrimedFromStart [variable] cls.add_instance_attribute('currentTrimedFromStart', 'uint32_t', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::isFragment [variable] cls.add_instance_attribute('isFragment', 'bool', is_const=False) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3PacketMetadataItemIterator_methods(root_module, cls): ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata::ItemIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketMetadata::ItemIterator const &', 'arg0')]) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::ItemIterator::ItemIterator(ns3::PacketMetadata const * metadata, ns3::Buffer buffer) [constructor] cls.add_constructor([param('ns3::PacketMetadata const *', 'metadata'), param('ns3::Buffer', 'buffer')]) ## packet-metadata.h (module 'network'): bool ns3::PacketMetadata::ItemIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet-metadata.h (module 'network'): ns3::PacketMetadata::Item ns3::PacketMetadata::ItemIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketMetadata::Item', []) return def register_Ns3PacketTagIterator_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::PacketTagIterator(ns3::PacketTagIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator const &', 'arg0')]) ## packet.h (module 'network'): bool ns3::PacketTagIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator::Item ns3::PacketTagIterator::Next() [member function] cls.add_method('Next', 'ns3::PacketTagIterator::Item', []) return def register_Ns3PacketTagIteratorItem_methods(root_module, cls): ## packet.h (module 'network'): ns3::PacketTagIterator::Item::Item(ns3::PacketTagIterator::Item const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagIterator::Item const &', 'arg0')]) ## packet.h (module 'network'): void ns3::PacketTagIterator::Item::GetTag(ns3::Tag & tag) const [member function] cls.add_method('GetTag', 'void', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::TypeId ns3::PacketTagIterator::Item::GetTypeId() const [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_const=True) return def register_Ns3PacketTagList_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::PacketTagList(ns3::PacketTagList const & o) [copy constructor] cls.add_constructor([param('ns3::PacketTagList const &', 'o')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::Add(ns3::Tag const & tag) const [member function] cls.add_method('Add', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData const * ns3::PacketTagList::Head() const [member function] cls.add_method('Head', 'ns3::PacketTagList::TagData const *', [], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Peek(ns3::Tag & tag) const [member function] cls.add_method('Peek', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet-tag-list.h (module 'network'): bool ns3::PacketTagList::Remove(ns3::Tag & tag) [member function] cls.add_method('Remove', 'bool', [param('ns3::Tag &', 'tag')]) ## packet-tag-list.h (module 'network'): void ns3::PacketTagList::RemoveAll() [member function] cls.add_method('RemoveAll', 'void', []) return def register_Ns3PacketTagListTagData_methods(root_module, cls): ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData() [constructor] cls.add_constructor([]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::TagData(ns3::PacketTagList::TagData const & arg0) [copy constructor] cls.add_constructor([param('ns3::PacketTagList::TagData const &', 'arg0')]) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::count [variable] cls.add_instance_attribute('count', 'uint32_t', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::data [variable] cls.add_instance_attribute('data', 'uint8_t [ 20 ]', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::next [variable] cls.add_instance_attribute('next', 'ns3::PacketTagList::TagData *', is_const=False) ## packet-tag-list.h (module 'network'): ns3::PacketTagList::TagData::tid [variable] cls.add_instance_attribute('tid', 'ns3::TypeId', is_const=False) return def register_Ns3SimpleRefCount__Ns3Object_Ns3ObjectBase_Ns3ObjectDeleter_methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::SimpleRefCount(ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter> const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Object, ns3::ObjectBase, ns3::ObjectDeleter>::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Simulator_methods(root_module, cls): ## simulator.h (module 'core'): ns3::Simulator::Simulator(ns3::Simulator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Simulator const &', 'arg0')]) ## simulator.h (module 'core'): static void ns3::Simulator::Cancel(ns3::EventId const & id) [member function] cls.add_method('Cancel', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Destroy() [member function] cls.add_method('Destroy', 'void', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetContext() [member function] cls.add_method('GetContext', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetDelayLeft(ns3::EventId const & id) [member function] cls.add_method('GetDelayLeft', 'ns3::Time', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static ns3::Ptr<ns3::SimulatorImpl> ns3::Simulator::GetImplementation() [member function] cls.add_method('GetImplementation', 'ns3::Ptr< ns3::SimulatorImpl >', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::GetMaximumSimulationTime() [member function] cls.add_method('GetMaximumSimulationTime', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static uint32_t ns3::Simulator::GetSystemId() [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsExpired(ns3::EventId const & id) [member function] cls.add_method('IsExpired', 'bool', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static bool ns3::Simulator::IsFinished() [member function] cls.add_method('IsFinished', 'bool', [], is_static=True) ## simulator.h (module 'core'): static ns3::Time ns3::Simulator::Now() [member function] cls.add_method('Now', 'ns3::Time', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Remove(ns3::EventId const & id) [member function] cls.add_method('Remove', 'void', [param('ns3::EventId const &', 'id')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetImplementation(ns3::Ptr<ns3::SimulatorImpl> impl) [member function] cls.add_method('SetImplementation', 'void', [param('ns3::Ptr< ns3::SimulatorImpl >', 'impl')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::SetScheduler(ns3::ObjectFactory schedulerFactory) [member function] cls.add_method('SetScheduler', 'void', [param('ns3::ObjectFactory', 'schedulerFactory')], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop() [member function] cls.add_method('Stop', 'void', [], is_static=True) ## simulator.h (module 'core'): static void ns3::Simulator::Stop(ns3::Time const & time) [member function] cls.add_method('Stop', 'void', [param('ns3::Time const &', 'time')], is_static=True) return def register_Ns3Tag_methods(root_module, cls): ## tag.h (module 'network'): ns3::Tag::Tag() [constructor] cls.add_constructor([]) ## tag.h (module 'network'): ns3::Tag::Tag(ns3::Tag const & arg0) [copy constructor] cls.add_constructor([param('ns3::Tag const &', 'arg0')]) ## tag.h (module 'network'): void ns3::Tag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_virtual=True) ## tag.h (module 'network'): uint32_t ns3::Tag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): static ns3::TypeId ns3::Tag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## tag.h (module 'network'): void ns3::Tag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## tag.h (module 'network'): void ns3::Tag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3TagBuffer_methods(root_module, cls): ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(ns3::TagBuffer const & arg0) [copy constructor] cls.add_constructor([param('ns3::TagBuffer const &', 'arg0')]) ## tag-buffer.h (module 'network'): ns3::TagBuffer::TagBuffer(uint8_t * start, uint8_t * end) [constructor] cls.add_constructor([param('uint8_t *', 'start'), param('uint8_t *', 'end')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::CopyFrom(ns3::TagBuffer o) [member function] cls.add_method('CopyFrom', 'void', [param('ns3::TagBuffer', 'o')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Read(uint8_t * buffer, uint32_t size) [member function] cls.add_method('Read', 'void', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): double ns3::TagBuffer::ReadDouble() [member function] cls.add_method('ReadDouble', 'double', []) ## tag-buffer.h (module 'network'): uint16_t ns3::TagBuffer::ReadU16() [member function] cls.add_method('ReadU16', 'uint16_t', []) ## tag-buffer.h (module 'network'): uint32_t ns3::TagBuffer::ReadU32() [member function] cls.add_method('ReadU32', 'uint32_t', []) ## tag-buffer.h (module 'network'): uint64_t ns3::TagBuffer::ReadU64() [member function] cls.add_method('ReadU64', 'uint64_t', []) ## tag-buffer.h (module 'network'): uint8_t ns3::TagBuffer::ReadU8() [member function] cls.add_method('ReadU8', 'uint8_t', []) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::TrimAtEnd(uint32_t trim) [member function] cls.add_method('TrimAtEnd', 'void', [param('uint32_t', 'trim')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::Write(uint8_t const * buffer, uint32_t size) [member function] cls.add_method('Write', 'void', [param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteDouble(double v) [member function] cls.add_method('WriteDouble', 'void', [param('double', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU16(uint16_t data) [member function] cls.add_method('WriteU16', 'void', [param('uint16_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU32(uint32_t data) [member function] cls.add_method('WriteU32', 'void', [param('uint32_t', 'data')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU64(uint64_t v) [member function] cls.add_method('WriteU64', 'void', [param('uint64_t', 'v')]) ## tag-buffer.h (module 'network'): void ns3::TagBuffer::WriteU8(uint8_t v) [member function] cls.add_method('WriteU8', 'void', [param('uint8_t', 'v')]) return def register_Ns3TypeId_methods(root_module, cls): cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('!=') cls.add_output_stream_operator() cls.add_binary_comparison_operator('==') ## type-id.h (module 'core'): ns3::TypeId::TypeId(char const * name) [constructor] cls.add_constructor([param('char const *', 'name')]) ## type-id.h (module 'core'): ns3::TypeId::TypeId() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TypeId(ns3::TypeId const & o) [copy constructor] cls.add_constructor([param('ns3::TypeId const &', 'o')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddAttribute(std::string name, std::string help, uint32_t flags, ns3::AttributeValue const & initialValue, ns3::Ptr<ns3::AttributeAccessor const> accessor, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('AddAttribute', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('uint32_t', 'flags'), param('ns3::AttributeValue const &', 'initialValue'), param('ns3::Ptr< ns3::AttributeAccessor const >', 'accessor'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::AddTraceSource(std::string name, std::string help, ns3::Ptr<ns3::TraceSourceAccessor const> accessor) [member function] cls.add_method('AddTraceSource', 'ns3::TypeId', [param('std::string', 'name'), param('std::string', 'help'), param('ns3::Ptr< ns3::TraceSourceAccessor const >', 'accessor')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation ns3::TypeId::GetAttribute(uint32_t i) const [member function] cls.add_method('GetAttribute', 'ns3::TypeId::AttributeInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetAttributeFullName(uint32_t i) const [member function] cls.add_method('GetAttributeFullName', 'std::string', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetAttributeN() const [member function] cls.add_method('GetAttributeN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): ns3::Callback<ns3::ObjectBase*,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> ns3::TypeId::GetConstructor() const [member function] cls.add_method('GetConstructor', 'ns3::Callback< ns3::ObjectBase *, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetGroupName() const [member function] cls.add_method('GetGroupName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeId::GetName() const [member function] cls.add_method('GetName', 'std::string', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::GetParent() const [member function] cls.add_method('GetParent', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::GetRegistered(uint32_t i) [member function] cls.add_method('GetRegistered', 'ns3::TypeId', [param('uint32_t', 'i')], is_static=True) ## type-id.h (module 'core'): static uint32_t ns3::TypeId::GetRegisteredN() [member function] cls.add_method('GetRegisteredN', 'uint32_t', [], is_static=True) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation ns3::TypeId::GetTraceSource(uint32_t i) const [member function] cls.add_method('GetTraceSource', 'ns3::TypeId::TraceSourceInformation', [param('uint32_t', 'i')], is_const=True) ## type-id.h (module 'core'): uint32_t ns3::TypeId::GetTraceSourceN() const [member function] cls.add_method('GetTraceSourceN', 'uint32_t', [], is_const=True) ## type-id.h (module 'core'): uint16_t ns3::TypeId::GetUid() const [member function] cls.add_method('GetUid', 'uint16_t', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasConstructor() const [member function] cls.add_method('HasConstructor', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::HasParent() const [member function] cls.add_method('HasParent', 'bool', [], is_const=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::HideFromDocumentation() [member function] cls.add_method('HideFromDocumentation', 'ns3::TypeId', []) ## type-id.h (module 'core'): bool ns3::TypeId::IsChildOf(ns3::TypeId other) const [member function] cls.add_method('IsChildOf', 'bool', [param('ns3::TypeId', 'other')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::LookupAttributeByName(std::string name, ns3::TypeId::AttributeInformation * info) const [member function] cls.add_method('LookupAttributeByName', 'bool', [param('std::string', 'name'), param('ns3::TypeId::AttributeInformation *', 'info', transfer_ownership=False)], is_const=True) ## type-id.h (module 'core'): static ns3::TypeId ns3::TypeId::LookupByName(std::string name) [member function] cls.add_method('LookupByName', 'ns3::TypeId', [param('std::string', 'name')], is_static=True) ## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string name) const [member function] cls.add_method('LookupTraceSourceByName', 'ns3::Ptr< ns3::TraceSourceAccessor const >', [param('std::string', 'name')], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::MustHideFromDocumentation() const [member function] cls.add_method('MustHideFromDocumentation', 'bool', [], is_const=True) ## type-id.h (module 'core'): bool ns3::TypeId::SetAttributeInitialValue(uint32_t i, ns3::Ptr<ns3::AttributeValue const> initialValue) [member function] cls.add_method('SetAttributeInitialValue', 'bool', [param('uint32_t', 'i'), param('ns3::Ptr< ns3::AttributeValue const >', 'initialValue')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetGroupName(std::string groupName) [member function] cls.add_method('SetGroupName', 'ns3::TypeId', [param('std::string', 'groupName')]) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeId::SetParent(ns3::TypeId tid) [member function] cls.add_method('SetParent', 'ns3::TypeId', [param('ns3::TypeId', 'tid')]) ## type-id.h (module 'core'): void ns3::TypeId::SetUid(uint16_t tid) [member function] cls.add_method('SetUid', 'void', [param('uint16_t', 'tid')]) return def register_Ns3TypeIdAttributeInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::AttributeInformation(ns3::TypeId::AttributeInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::AttributeInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::AttributeAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::checker [variable] cls.add_instance_attribute('checker', 'ns3::Ptr< ns3::AttributeChecker const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::flags [variable] cls.add_instance_attribute('flags', 'uint32_t', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::initialValue [variable] cls.add_instance_attribute('initialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::AttributeInformation::originalInitialValue [variable] cls.add_instance_attribute('originalInitialValue', 'ns3::Ptr< ns3::AttributeValue const >', is_const=False) return def register_Ns3TypeIdTraceSourceInformation_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable] cls.add_instance_attribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable] cls.add_instance_attribute('help', 'std::string', is_const=False) ## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [variable] cls.add_instance_attribute('name', 'std::string', is_const=False) return def register_Ns3Vector2D_methods(root_module, cls): cls.add_output_stream_operator() ## vector.h (module 'core'): ns3::Vector2D::Vector2D(ns3::Vector2D const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2D const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector2D::Vector2D(double _x, double _y) [constructor] cls.add_constructor([param('double', '_x'), param('double', '_y')]) ## vector.h (module 'core'): ns3::Vector2D::Vector2D() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2D::x [variable] cls.add_instance_attribute('x', 'double', is_const=False) ## vector.h (module 'core'): ns3::Vector2D::y [variable] cls.add_instance_attribute('y', 'double', is_const=False) return def register_Ns3Vector3D_methods(root_module, cls): cls.add_output_stream_operator() ## vector.h (module 'core'): ns3::Vector3D::Vector3D(ns3::Vector3D const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3D const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector3D::Vector3D(double _x, double _y, double _z) [constructor] cls.add_constructor([param('double', '_x'), param('double', '_y'), param('double', '_z')]) ## vector.h (module 'core'): ns3::Vector3D::Vector3D() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3D::x [variable] cls.add_instance_attribute('x', 'double', is_const=False) ## vector.h (module 'core'): ns3::Vector3D::y [variable] cls.add_instance_attribute('y', 'double', is_const=False) ## vector.h (module 'core'): ns3::Vector3D::z [variable] cls.add_instance_attribute('z', 'double', is_const=False) return def register_Ns3Empty_methods(root_module, cls): ## empty.h (module 'core'): ns3::empty::empty() [constructor] cls.add_constructor([]) ## empty.h (module 'core'): ns3::empty::empty(ns3::empty const & arg0) [copy constructor] cls.add_constructor([param('ns3::empty const &', 'arg0')]) return def register_Ns3Int64x64_t_methods(root_module, cls): cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('*', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('+', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_unary_numeric_operator('-') cls.add_binary_numeric_operator('-', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short unsigned int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('unsigned char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('long int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('short int const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('signed char const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('double const', 'right')) cls.add_binary_numeric_operator('/', root_module['ns3::int64x64_t'], root_module['ns3::int64x64_t'], param('ns3::int64x64_t const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('*=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('+=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::int64x64_t const &', 'right')) cls.add_inplace_numeric_operator('/=', param('ns3::int64x64_t const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t() [constructor] cls.add_constructor([]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(int64_t hi, uint64_t lo) [constructor] cls.add_constructor([param('int64_t', 'hi'), param('uint64_t', 'lo')]) ## int64x64-double.h (module 'core'): ns3::int64x64_t::int64x64_t(ns3::int64x64_t const & o) [copy constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'o')]) ## int64x64-double.h (module 'core'): double ns3::int64x64_t::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## int64x64-double.h (module 'core'): int64_t ns3::int64x64_t::GetHigh() const [member function] cls.add_method('GetHigh', 'int64_t', [], is_const=True) ## int64x64-double.h (module 'core'): uint64_t ns3::int64x64_t::GetLow() const [member function] cls.add_method('GetLow', 'uint64_t', [], is_const=True) ## int64x64-double.h (module 'core'): static ns3::int64x64_t ns3::int64x64_t::Invert(uint64_t v) [member function] cls.add_method('Invert', 'ns3::int64x64_t', [param('uint64_t', 'v')], is_static=True) ## int64x64-double.h (module 'core'): void ns3::int64x64_t::MulByInvert(ns3::int64x64_t const & o) [member function] cls.add_method('MulByInvert', 'void', [param('ns3::int64x64_t const &', 'o')]) return def register_Ns3AnimByteTag_methods(root_module, cls): ## animation-interface.h (module 'netanim'): ns3::AnimByteTag::AnimByteTag() [constructor] cls.add_constructor([]) ## animation-interface.h (module 'netanim'): ns3::AnimByteTag::AnimByteTag(ns3::AnimByteTag const & arg0) [copy constructor] cls.add_constructor([param('ns3::AnimByteTag const &', 'arg0')]) ## animation-interface.h (module 'netanim'): void ns3::AnimByteTag::Deserialize(ns3::TagBuffer i) [member function] cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) ## animation-interface.h (module 'netanim'): uint64_t ns3::AnimByteTag::Get() const [member function] cls.add_method('Get', 'uint64_t', [], is_const=True) ## animation-interface.h (module 'netanim'): ns3::TypeId ns3::AnimByteTag::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## animation-interface.h (module 'netanim'): uint32_t ns3::AnimByteTag::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True, is_virtual=True) ## animation-interface.h (module 'netanim'): static ns3::TypeId ns3::AnimByteTag::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## animation-interface.h (module 'netanim'): void ns3::AnimByteTag::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True, is_virtual=True) ## animation-interface.h (module 'netanim'): void ns3::AnimByteTag::Serialize(ns3::TagBuffer i) const [member function] cls.add_method('Serialize', 'void', [param('ns3::TagBuffer', 'i')], is_const=True, is_virtual=True) ## animation-interface.h (module 'netanim'): void ns3::AnimByteTag::Set(uint64_t AnimUid) [member function] cls.add_method('Set', 'void', [param('uint64_t', 'AnimUid')]) return def register_Ns3Chunk_methods(root_module, cls): ## chunk.h (module 'network'): ns3::Chunk::Chunk() [constructor] cls.add_constructor([]) ## chunk.h (module 'network'): ns3::Chunk::Chunk(ns3::Chunk const & arg0) [copy constructor] cls.add_constructor([param('ns3::Chunk const &', 'arg0')]) ## chunk.h (module 'network'): uint32_t ns3::Chunk::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## chunk.h (module 'network'): static ns3::TypeId ns3::Chunk::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## chunk.h (module 'network'): void ns3::Chunk::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Header_methods(root_module, cls): cls.add_output_stream_operator() ## header.h (module 'network'): ns3::Header::Header() [constructor] cls.add_constructor([]) ## header.h (module 'network'): ns3::Header::Header(ns3::Header const & arg0) [copy constructor] cls.add_constructor([param('ns3::Header const &', 'arg0')]) ## header.h (module 'network'): uint32_t ns3::Header::Deserialize(ns3::Buffer::Iterator start) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_virtual=True) ## header.h (module 'network'): uint32_t ns3::Header::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): static ns3::TypeId ns3::Header::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## header.h (module 'network'): void ns3::Header::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## header.h (module 'network'): void ns3::Header::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Object_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::Object() [constructor] cls.add_constructor([]) ## object.h (module 'core'): void ns3::Object::AggregateObject(ns3::Ptr<ns3::Object> other) [member function] cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) ## object.h (module 'core'): void ns3::Object::Dispose() [member function] cls.add_method('Dispose', 'void', []) ## object.h (module 'core'): ns3::Object::AggregateIterator ns3::Object::GetAggregateIterator() const [member function] cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) ## object.h (module 'core'): ns3::TypeId ns3::Object::GetInstanceTypeId() const [member function] cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtual=True) ## object.h (module 'core'): static ns3::TypeId ns3::Object::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## object.h (module 'core'): void ns3::Object::Start() [member function] cls.add_method('Start', 'void', []) ## object.h (module 'core'): ns3::Object::Object(ns3::Object const & o) [copy constructor] cls.add_constructor([param('ns3::Object const &', 'o')], visibility='protected') ## object.h (module 'core'): void ns3::Object::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='protected', is_virtual=True) ## object.h (module 'core'): void ns3::Object::NotifyNewAggregate() [member function] cls.add_method('NotifyNewAggregate', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectAggregateIterator_methods(root_module, cls): ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator(ns3::Object::AggregateIterator const & arg0) [copy constructor] cls.add_constructor([param('ns3::Object::AggregateIterator const &', 'arg0')]) ## object.h (module 'core'): ns3::Object::AggregateIterator::AggregateIterator() [constructor] cls.add_constructor([]) ## object.h (module 'core'): bool ns3::Object::AggregateIterator::HasNext() const [member function] cls.add_method('HasNext', 'bool', [], is_const=True) ## object.h (module 'core'): ns3::Ptr<ns3::Object const> ns3::Object::AggregateIterator::Next() [member function] cls.add_method('Next', 'ns3::Ptr< ns3::Object const >', []) return def register_Ns3SimpleRefCount__Ns3AttributeAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter< ns3::AttributeAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeAccessor, ns3::empty, ns3::DefaultDeleter<ns3::AttributeAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeChecker_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeChecker__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter< ns3::AttributeChecker > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeChecker, ns3::empty, ns3::DefaultDeleter<ns3::AttributeChecker> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3AttributeValue_Ns3Empty_Ns3DefaultDeleter__lt__ns3AttributeValue__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::SimpleRefCount(ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter< ns3::AttributeValue > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::AttributeValue, ns3::empty, ns3::DefaultDeleter<ns3::AttributeValue> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3CallbackImplBase_Ns3Empty_Ns3DefaultDeleter__lt__ns3CallbackImplBase__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::SimpleRefCount(ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter< ns3::CallbackImplBase > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::CallbackImplBase, ns3::empty, ns3::DefaultDeleter<ns3::CallbackImplBase> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::SimpleRefCount(ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::EventImpl, ns3::empty, ns3::DefaultDeleter<ns3::EventImpl> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3NixVector_Ns3Empty_Ns3DefaultDeleter__lt__ns3NixVector__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::SimpleRefCount(ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::NixVector, ns3::empty, ns3::DefaultDeleter< ns3::NixVector > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::NixVector, ns3::empty, ns3::DefaultDeleter<ns3::NixVector> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3Packet_Ns3Empty_Ns3DefaultDeleter__lt__ns3Packet__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::SimpleRefCount(ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::Packet, ns3::empty, ns3::DefaultDeleter< ns3::Packet > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::Packet, ns3::empty, ns3::DefaultDeleter<ns3::Packet> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3SimpleRefCount__Ns3TraceSourceAccessor_Ns3Empty_Ns3DefaultDeleter__lt__ns3TraceSourceAccessor__gt___methods(root_module, cls): ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount() [constructor] cls.add_constructor([]) ## simple-ref-count.h (module 'core'): ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::SimpleRefCount(ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> > const & o) [copy constructor] cls.add_constructor([param('ns3::SimpleRefCount< ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter< ns3::TraceSourceAccessor > > const &', 'o')]) ## simple-ref-count.h (module 'core'): static void ns3::SimpleRefCount<ns3::TraceSourceAccessor, ns3::empty, ns3::DefaultDeleter<ns3::TraceSourceAccessor> >::Cleanup() [member function] cls.add_method('Cleanup', 'void', [], is_static=True) return def register_Ns3Time_methods(root_module, cls): cls.add_binary_numeric_operator('+', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_numeric_operator('-', root_module['ns3::Time'], root_module['ns3::Time'], param('ns3::Time const &', 'right')) cls.add_binary_comparison_operator('<') cls.add_binary_comparison_operator('>') cls.add_binary_comparison_operator('!=') cls.add_inplace_numeric_operator('+=', param('ns3::Time const &', 'right')) cls.add_inplace_numeric_operator('-=', param('ns3::Time const &', 'right')) cls.add_output_stream_operator() cls.add_binary_comparison_operator('<=') cls.add_binary_comparison_operator('==') cls.add_binary_comparison_operator('>=') ## nstime.h (module 'core'): ns3::Time::Time() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::Time const & o) [copy constructor] cls.add_constructor([param('ns3::Time const &', 'o')]) ## nstime.h (module 'core'): ns3::Time::Time(double v) [constructor] cls.add_constructor([param('double', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(int v) [constructor] cls.add_constructor([param('int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long int v) [constructor] cls.add_constructor([param('long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long int v) [constructor] cls.add_constructor([param('long long int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(unsigned int v) [constructor] cls.add_constructor([param('unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long unsigned int v) [constructor] cls.add_constructor([param('long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(long long unsigned int v) [constructor] cls.add_constructor([param('long long unsigned int', 'v')]) ## nstime.h (module 'core'): ns3::Time::Time(std::string const & s) [constructor] cls.add_constructor([param('std::string const &', 's')]) ## nstime.h (module 'core'): ns3::Time::Time(ns3::int64x64_t const & value) [constructor] cls.add_constructor([param('ns3::int64x64_t const &', 'value')]) ## nstime.h (module 'core'): int ns3::Time::Compare(ns3::Time const & o) const [member function] cls.add_method('Compare', 'int', [param('ns3::Time const &', 'o')], is_const=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & from, ns3::Time::Unit timeUnit) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'from'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::From(ns3::int64x64_t const & value) [member function] cls.add_method('From', 'ns3::Time', [param('ns3::int64x64_t const &', 'value')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromDouble(double value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromDouble', 'ns3::Time', [param('double', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): static ns3::Time ns3::Time::FromInteger(uint64_t value, ns3::Time::Unit timeUnit) [member function] cls.add_method('FromInteger', 'ns3::Time', [param('uint64_t', 'value'), param('ns3::Time::Unit', 'timeUnit')], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetDouble() const [member function] cls.add_method('GetDouble', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetFemtoSeconds() const [member function] cls.add_method('GetFemtoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetInteger() const [member function] cls.add_method('GetInteger', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMicroSeconds() const [member function] cls.add_method('GetMicroSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetMilliSeconds() const [member function] cls.add_method('GetMilliSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetNanoSeconds() const [member function] cls.add_method('GetNanoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetPicoSeconds() const [member function] cls.add_method('GetPicoSeconds', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): static ns3::Time::Unit ns3::Time::GetResolution() [member function] cls.add_method('GetResolution', 'ns3::Time::Unit', [], is_static=True) ## nstime.h (module 'core'): double ns3::Time::GetSeconds() const [member function] cls.add_method('GetSeconds', 'double', [], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::GetTimeStep() const [member function] cls.add_method('GetTimeStep', 'int64_t', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsNegative() const [member function] cls.add_method('IsNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsPositive() const [member function] cls.add_method('IsPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyNegative() const [member function] cls.add_method('IsStrictlyNegative', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsStrictlyPositive() const [member function] cls.add_method('IsStrictlyPositive', 'bool', [], is_const=True) ## nstime.h (module 'core'): bool ns3::Time::IsZero() const [member function] cls.add_method('IsZero', 'bool', [], is_const=True) ## nstime.h (module 'core'): static void ns3::Time::SetResolution(ns3::Time::Unit resolution) [member function] cls.add_method('SetResolution', 'void', [param('ns3::Time::Unit', 'resolution')], is_static=True) ## nstime.h (module 'core'): ns3::int64x64_t ns3::Time::To(ns3::Time::Unit timeUnit) const [member function] cls.add_method('To', 'ns3::int64x64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): double ns3::Time::ToDouble(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToDouble', 'double', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) ## nstime.h (module 'core'): int64_t ns3::Time::ToInteger(ns3::Time::Unit timeUnit) const [member function] cls.add_method('ToInteger', 'int64_t', [param('ns3::Time::Unit', 'timeUnit')], is_const=True) return def register_Ns3TraceSourceAccessor_methods(root_module, cls): ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor(ns3::TraceSourceAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::TraceSourceAccessor const &', 'arg0')]) ## trace-source-accessor.h (module 'core'): ns3::TraceSourceAccessor::TraceSourceAccessor() [constructor] cls.add_constructor([]) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Connect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Connect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::ConnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('ConnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::Disconnect(ns3::ObjectBase * obj, std::string context, ns3::CallbackBase const & cb) const [member function] cls.add_method('Disconnect', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('std::string', 'context'), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trace-source-accessor.h (module 'core'): bool ns3::TraceSourceAccessor::DisconnectWithoutContext(ns3::ObjectBase * obj, ns3::CallbackBase const & cb) const [member function] cls.add_method('DisconnectWithoutContext', 'bool', [param('ns3::ObjectBase *', 'obj', transfer_ownership=False), param('ns3::CallbackBase const &', 'cb')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3Trailer_methods(root_module, cls): cls.add_output_stream_operator() ## trailer.h (module 'network'): ns3::Trailer::Trailer() [constructor] cls.add_constructor([]) ## trailer.h (module 'network'): ns3::Trailer::Trailer(ns3::Trailer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Trailer const &', 'arg0')]) ## trailer.h (module 'network'): uint32_t ns3::Trailer::Deserialize(ns3::Buffer::Iterator end) [member function] cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'end')], is_pure_virtual=True, is_virtual=True) ## trailer.h (module 'network'): uint32_t ns3::Trailer::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): static ns3::TypeId ns3::Trailer::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## trailer.h (module 'network'): void ns3::Trailer::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_pure_virtual=True, is_const=True, is_virtual=True) ## trailer.h (module 'network'): void ns3::Trailer::Serialize(ns3::Buffer::Iterator start) const [member function] cls.add_method('Serialize', 'void', [param('ns3::Buffer::Iterator', 'start')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeAccessor_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor(ns3::AttributeAccessor const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeAccessor const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeAccessor::AttributeAccessor() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Get(ns3::ObjectBase const * object, ns3::AttributeValue & attribute) const [member function] cls.add_method('Get', 'bool', [param('ns3::ObjectBase const *', 'object'), param('ns3::AttributeValue &', 'attribute')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasGetter() const [member function] cls.add_method('HasGetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::HasSetter() const [member function] cls.add_method('HasSetter', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeAccessor::Set(ns3::ObjectBase * object, ns3::AttributeValue const & value) const [member function] cls.add_method('Set', 'bool', [param('ns3::ObjectBase *', 'object', transfer_ownership=False), param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeChecker_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker(ns3::AttributeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeChecker const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeChecker::AttributeChecker() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Check(ns3::AttributeValue const & value) const [member function] cls.add_method('Check', 'bool', [param('ns3::AttributeValue const &', 'value')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::Copy(ns3::AttributeValue const & source, ns3::AttributeValue & destination) const [member function] cls.add_method('Copy', 'bool', [param('ns3::AttributeValue const &', 'source'), param('ns3::AttributeValue &', 'destination')], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::Create() const [member function] cls.add_method('Create', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeChecker::CreateValidValue(ns3::AttributeValue const & value) const [member function] cls.add_method('CreateValidValue', 'ns3::Ptr< ns3::AttributeValue >', [param('ns3::AttributeValue const &', 'value')], is_const=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetUnderlyingTypeInformation() const [member function] cls.add_method('GetUnderlyingTypeInformation', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeChecker::GetValueTypeName() const [member function] cls.add_method('GetValueTypeName', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeChecker::HasUnderlyingTypeInformation() const [member function] cls.add_method('HasUnderlyingTypeInformation', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3AttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue(ns3::AttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::AttributeValue::AttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::AttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## attribute.h (module 'core'): bool ns3::AttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_virtual=True) ## attribute.h (module 'core'): std::string ns3::AttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackChecker_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackChecker::CallbackChecker(ns3::CallbackChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackChecker const &', 'arg0')]) return def register_Ns3CallbackImplBase_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackImplBase::CallbackImplBase(ns3::CallbackImplBase const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) ## callback.h (module 'core'): bool ns3::CallbackImplBase::IsEqual(ns3::Ptr<ns3::CallbackImplBase const> other) const [member function] cls.add_method('IsEqual', 'bool', [param('ns3::Ptr< ns3::CallbackImplBase const >', 'other')], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3CallbackValue_methods(root_module, cls): ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::CallbackValue const &', 'arg0')]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue() [constructor] cls.add_constructor([]) ## callback.h (module 'core'): ns3::CallbackValue::CallbackValue(ns3::CallbackBase const & base) [constructor] cls.add_constructor([param('ns3::CallbackBase const &', 'base')]) ## callback.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::CallbackValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## callback.h (module 'core'): bool ns3::CallbackValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## callback.h (module 'core'): std::string ns3::CallbackValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## callback.h (module 'core'): void ns3::CallbackValue::Set(ns3::CallbackBase base) [member function] cls.add_method('Set', 'void', [param('ns3::CallbackBase', 'base')]) return def register_Ns3EmptyAttributeValue_methods(root_module, cls): ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue(ns3::EmptyAttributeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::EmptyAttributeValue const &', 'arg0')]) ## attribute.h (module 'core'): ns3::EmptyAttributeValue::EmptyAttributeValue() [constructor] cls.add_constructor([]) ## attribute.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::EmptyAttributeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, visibility='private', is_virtual=True) ## attribute.h (module 'core'): bool ns3::EmptyAttributeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], visibility='private', is_virtual=True) ## attribute.h (module 'core'): std::string ns3::EmptyAttributeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, visibility='private', is_virtual=True) return def register_Ns3EventImpl_methods(root_module, cls): ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] cls.add_constructor([]) ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] cls.add_method('Cancel', 'void', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] cls.add_method('Invoke', 'void', []) ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] cls.add_method('IsCancelled', 'bool', []) ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] cls.add_method('Notify', 'void', [], is_pure_virtual=True, visibility='protected', is_virtual=True) return def register_Ns3Ipv4AddressChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) return def register_Ns3Ipv4AddressValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Address', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Address const &', 'value')]) return def register_Ns3Ipv4MaskChecker_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) return def register_Ns3Ipv4MaskValue_methods(root_module, cls): ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] cls.add_constructor([]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) ## ipv4-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv4MaskValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv4Mask', [], is_const=True) ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv4Mask const &', 'value')]) return def register_Ns3Ipv6AddressChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) return def register_Ns3Ipv6AddressValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Address', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Address const &', 'value')]) return def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) return def register_Ns3Ipv6PrefixValue_methods(root_module, cls): ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] cls.add_constructor([]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) ## ipv6-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Ipv6PrefixValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] cls.add_method('Get', 'ns3::Ipv6Prefix', [], is_const=True) ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Ipv6Prefix const &', 'value')]) return def register_Ns3Mac48AddressChecker_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressChecker::Mac48AddressChecker(ns3::Mac48AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressChecker const &', 'arg0')]) return def register_Ns3Mac48AddressValue_methods(root_module, cls): ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue() [constructor] cls.add_constructor([]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) ## mac48-address.h (module 'network'): ns3::Mac48AddressValue::Mac48AddressValue(ns3::Mac48Address const & value) [constructor] cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) ## mac48-address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::Mac48AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): bool ns3::Mac48AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## mac48-address.h (module 'network'): ns3::Mac48Address ns3::Mac48AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Mac48Address', [], is_const=True) ## mac48-address.h (module 'network'): std::string ns3::Mac48AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## mac48-address.h (module 'network'): void ns3::Mac48AddressValue::Set(ns3::Mac48Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Mac48Address const &', 'value')]) return def register_Ns3MobilityModel_methods(root_module, cls): ## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel(ns3::MobilityModel const & arg0) [copy constructor] cls.add_constructor([param('ns3::MobilityModel const &', 'arg0')]) ## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel() [constructor] cls.add_constructor([]) ## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetDistanceFrom(ns3::Ptr<const ns3::MobilityModel> position) const [member function] cls.add_method('GetDistanceFrom', 'double', [param('ns3::Ptr< ns3::MobilityModel const >', 'position')], is_const=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetPosition() const [member function] cls.add_method('GetPosition', 'ns3::Vector', [], is_const=True) ## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetRelativeSpeed(ns3::Ptr<const ns3::MobilityModel> other) const [member function] cls.add_method('GetRelativeSpeed', 'double', [param('ns3::Ptr< ns3::MobilityModel const >', 'other')], is_const=True) ## mobility-model.h (module 'mobility'): static ns3::TypeId ns3::MobilityModel::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetVelocity() const [member function] cls.add_method('GetVelocity', 'ns3::Vector', [], is_const=True) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::SetPosition(ns3::Vector const & position) [member function] cls.add_method('SetPosition', 'void', [param('ns3::Vector const &', 'position')]) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::NotifyCourseChange() const [member function] cls.add_method('NotifyCourseChange', 'void', [], is_const=True, visibility='protected') ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetPosition() const [member function] cls.add_method('DoGetPosition', 'ns3::Vector', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetVelocity() const [member function] cls.add_method('DoGetVelocity', 'ns3::Vector', [], is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::DoSetPosition(ns3::Vector const & position) [member function] cls.add_method('DoSetPosition', 'void', [param('ns3::Vector const &', 'position')], is_pure_virtual=True, visibility='private', is_virtual=True) return def register_Ns3NetDevice_methods(root_module, cls): ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] cls.add_constructor([]) ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback<void,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> callback) [member function] cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] cls.add_method('GetAddress', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] cls.add_method('GetBroadcast', 'ns3::Address', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Channel> ns3::NetDevice::GetChannel() const [member function] cls.add_method('GetChannel', 'ns3::Ptr< ns3::Channel >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] cls.add_method('GetIfIndex', 'uint32_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] cls.add_method('GetMtu', 'uint16_t', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv4Address', 'multicastGroup')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] cls.add_method('GetMulticast', 'ns3::Address', [param('ns3::Ipv6Address', 'addr')], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): ns3::Ptr<ns3::Node> ns3::NetDevice::GetNode() const [member function] cls.add_method('GetNode', 'ns3::Ptr< ns3::Node >', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] cls.add_method('IsBridge', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] cls.add_method('IsBroadcast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] cls.add_method('IsLinkUp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] cls.add_method('IsMulticast', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] cls.add_method('IsPointToPoint', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] cls.add_method('NeedsArp', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr<ns3::Packet> packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('Send', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr<ns3::Packet> packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] cls.add_method('SendFrom', 'bool', [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] cls.add_method('SetAddress', 'void', [param('ns3::Address', 'address')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] cls.add_method('SetIfIndex', 'void', [param('uint32_t const', 'index')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] cls.add_method('SetMtu', 'bool', [param('uint16_t const', 'mtu')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr<ns3::Node> node) [member function] cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetPromiscReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback<bool,ns3::Ptr<ns3::NetDevice>,ns3::Ptr<const ns3::Packet>,short unsigned int,const ns3::Address&,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> cb) [member function] cls.add_method('SetReceiveCallback', 'void', [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], is_pure_virtual=True, is_virtual=True) ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] cls.add_method('SupportsSendFrom', 'bool', [], is_pure_virtual=True, is_const=True, is_virtual=True) return def register_Ns3NixVector_methods(root_module, cls): cls.add_output_stream_operator() ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] cls.add_constructor([]) ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] cls.add_constructor([param('ns3::NixVector const &', 'o')]) ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] cls.add_method('AddNeighborIndex', 'void', [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] cls.add_method('BitCount', 'uint32_t', [param('uint32_t', 'numberOfNeighbors')], is_const=True) ## nix-vector.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::NixVector::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] cls.add_method('Deserialize', 'uint32_t', [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] cls.add_method('ExtractNeighborIndex', 'uint32_t', [param('uint32_t', 'numberOfBits')]) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] cls.add_method('GetRemainingBits', 'uint32_t', []) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) return def register_Ns3Node_methods(root_module, cls): ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] cls.add_constructor([param('ns3::Node const &', 'arg0')]) ## node.h (module 'network'): ns3::Node::Node() [constructor] cls.add_constructor([]) ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] cls.add_constructor([param('uint32_t', 'systemId')]) ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr<ns3::Application> application) [member function] cls.add_method('AddApplication', 'uint32_t', [param('ns3::Ptr< ns3::Application >', 'application')]) ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr<ns3::NetDevice> device) [member function] cls.add_method('AddDevice', 'uint32_t', [param('ns3::Ptr< ns3::NetDevice >', 'device')]) ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] cls.add_method('ChecksumEnabled', 'bool', [], is_static=True) ## node.h (module 'network'): ns3::Ptr<ns3::Application> ns3::Node::GetApplication(uint32_t index) const [member function] cls.add_method('GetApplication', 'ns3::Ptr< ns3::Application >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): ns3::Ptr<ns3::NetDevice> ns3::Node::GetDevice(uint32_t index) const [member function] cls.add_method('GetDevice', 'ns3::Ptr< ns3::NetDevice >', [param('uint32_t', 'index')], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] cls.add_method('GetId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] cls.add_method('GetNApplications', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] cls.add_method('GetNDevices', 'uint32_t', [], is_const=True) ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] cls.add_method('GetSystemId', 'uint32_t', [], is_const=True) ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('RegisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr<ns3::NetDevice> device, bool promiscuous=false) [member function] cls.add_method('RegisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback<void,ns3::Ptr<ns3::NetDevice>,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] cls.add_method('UnregisterDeviceAdditionListener', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback<void, ns3::Ptr<ns3::NetDevice>, ns3::Ptr<ns3::Packet const>, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] cls.add_method('UnregisterProtocolHandler', 'void', [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] cls.add_method('DoDispose', 'void', [], visibility='protected', is_virtual=True) ## node.h (module 'network'): void ns3::Node::DoStart() [member function] cls.add_method('DoStart', 'void', [], visibility='protected', is_virtual=True) return def register_Ns3ObjectFactoryChecker_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) return def register_Ns3ObjectFactoryValue_methods(root_module, cls): ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] cls.add_constructor([]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) ## object-factory.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::ObjectFactoryValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] cls.add_method('Get', 'ns3::ObjectFactory', [], is_const=True) ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] cls.add_method('Set', 'void', [param('ns3::ObjectFactory const &', 'value')]) return def register_Ns3Packet_methods(root_module, cls): cls.add_output_stream_operator() ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] cls.add_constructor([]) ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] cls.add_constructor([param('ns3::Packet const &', 'o')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] cls.add_constructor([param('uint32_t', 'size')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr<const ns3::Packet> packet) [member function] cls.add_method('AddAtEnd', 'void', [param('ns3::Ptr< ns3::Packet const >', 'packet')]) ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] cls.add_method('AddByteTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] cls.add_method('AddHeader', 'void', [param('ns3::Header const &', 'header')]) ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] cls.add_method('AddPacketTag', 'void', [param('ns3::Tag const &', 'tag')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] cls.add_method('AddPaddingAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] cls.add_method('AddTrailer', 'void', [param('ns3::Trailer const &', 'trailer')]) ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] cls.add_method('BeginItem', 'ns3::PacketMetadata::ItemIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::Packet >', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] cls.add_method('CopyData', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] cls.add_method('CopyData', 'void', [param('std::ostream *', 'os'), param('uint32_t', 'size')], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::Packet> ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] cls.add_method('CreateFragment', 'ns3::Ptr< ns3::Packet >', [param('uint32_t', 'start'), param('uint32_t', 'length')], is_const=True) ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] cls.add_method('EnableChecking', 'void', [], is_static=True) ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] cls.add_method('EnablePrinting', 'void', [], is_static=True) ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] cls.add_method('FindFirstMatchingByteTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] cls.add_method('GetByteTagIterator', 'ns3::ByteTagIterator', [], is_const=True) ## packet.h (module 'network'): ns3::Ptr<ns3::NixVector> ns3::Packet::GetNixVector() const [member function] cls.add_method('GetNixVector', 'ns3::Ptr< ns3::NixVector >', [], is_const=True) ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] cls.add_method('GetPacketTagIterator', 'ns3::PacketTagIterator', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] cls.add_method('GetSerializedSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] cls.add_method('GetSize', 'uint32_t', [], is_const=True) ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] cls.add_method('GetUid', 'uint64_t', [], is_const=True) ## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function] cls.add_method('PeekData', 'uint8_t const *', [], deprecated=True, is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] cls.add_method('PeekHeader', 'uint32_t', [param('ns3::Header &', 'header')], is_const=True) ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] cls.add_method('PeekPacketTag', 'bool', [param('ns3::Tag &', 'tag')], is_const=True) ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] cls.add_method('PeekTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] cls.add_method('Print', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] cls.add_method('PrintByteTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] cls.add_method('PrintPacketTags', 'void', [param('std::ostream &', 'os')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] cls.add_method('RemoveAllByteTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] cls.add_method('RemoveAllPacketTags', 'void', []) ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] cls.add_method('RemoveAtEnd', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] cls.add_method('RemoveAtStart', 'void', [param('uint32_t', 'size')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] cls.add_method('RemoveHeader', 'uint32_t', [param('ns3::Header &', 'header')]) ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] cls.add_method('RemovePacketTag', 'bool', [param('ns3::Tag &', 'tag')]) ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] cls.add_method('RemoveTrailer', 'uint32_t', [param('ns3::Trailer &', 'trailer')]) ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] cls.add_method('Serialize', 'uint32_t', [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], is_const=True) ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr<ns3::NixVector> arg0) [member function] cls.add_method('SetNixVector', 'void', [param('ns3::Ptr< ns3::NixVector >', 'arg0')]) return def register_Ns3TimeChecker_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker(ns3::TimeChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeChecker const &', 'arg0')]) return def register_Ns3TimeValue_methods(root_module, cls): ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] cls.add_constructor([]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] cls.add_constructor([param('ns3::Time const &', 'value')]) ## nstime.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TimeValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] cls.add_method('Get', 'ns3::Time', [], is_const=True) ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Time const &', 'value')]) return def register_Ns3TypeIdChecker_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) return def register_Ns3TypeIdValue_methods(root_module, cls): ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] cls.add_constructor([]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] cls.add_constructor([param('ns3::TypeId const &', 'value')]) ## type-id.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::TypeIdValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] cls.add_method('Get', 'ns3::TypeId', [], is_const=True) ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] cls.add_method('Set', 'void', [param('ns3::TypeId const &', 'value')]) return def register_Ns3Vector2DChecker_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker(ns3::Vector2DChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2DChecker const &', 'arg0')]) return def register_Ns3Vector2DValue_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2DValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector2DValue const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2D const & value) [constructor] cls.add_constructor([param('ns3::Vector2D const &', 'value')]) ## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector2DValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## vector.h (module 'core'): bool ns3::Vector2DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## vector.h (module 'core'): ns3::Vector2D ns3::Vector2DValue::Get() const [member function] cls.add_method('Get', 'ns3::Vector2D', [], is_const=True) ## vector.h (module 'core'): std::string ns3::Vector2DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## vector.h (module 'core'): void ns3::Vector2DValue::Set(ns3::Vector2D const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Vector2D const &', 'value')]) return def register_Ns3Vector3DChecker_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker(ns3::Vector3DChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3DChecker const &', 'arg0')]) return def register_Ns3Vector3DValue_methods(root_module, cls): ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue() [constructor] cls.add_constructor([]) ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3DValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::Vector3DValue const &', 'arg0')]) ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3D const & value) [constructor] cls.add_constructor([param('ns3::Vector3D const &', 'value')]) ## vector.h (module 'core'): ns3::Ptr<ns3::AttributeValue> ns3::Vector3DValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## vector.h (module 'core'): bool ns3::Vector3DValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## vector.h (module 'core'): ns3::Vector3D ns3::Vector3DValue::Get() const [member function] cls.add_method('Get', 'ns3::Vector3D', [], is_const=True) ## vector.h (module 'core'): std::string ns3::Vector3DValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## vector.h (module 'core'): void ns3::Vector3DValue::Set(ns3::Vector3D const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Vector3D const &', 'value')]) return def register_Ns3AddressChecker_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) return def register_Ns3AddressValue_methods(root_module, cls): ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] cls.add_constructor([]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] cls.add_constructor([param('ns3::Address const &', 'value')]) ## address.h (module 'network'): ns3::Ptr<ns3::AttributeValue> ns3::AddressValue::Copy() const [member function] cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_virtual=True) ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr<ns3::AttributeChecker const> checker) [member function] cls.add_method('DeserializeFromString', 'bool', [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_virtual=True) ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] cls.add_method('Get', 'ns3::Address', [], is_const=True) ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr<ns3::AttributeChecker const> checker) const [member function] cls.add_method('SerializeToString', 'std::string', [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], is_const=True, is_virtual=True) ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] cls.add_method('Set', 'void', [param('ns3::Address const &', 'value')]) return def register_Ns3ConfigMatchContainer_methods(root_module, cls): ## config.h (module 'core'): ns3::Config::MatchContainer::MatchContainer(ns3::Config::MatchContainer const & arg0) [copy constructor] cls.add_constructor([param('ns3::Config::MatchContainer const &', 'arg0')]) ## config.h (module 'core'): ns3::Config::MatchContainer::MatchContainer() [constructor] cls.add_constructor([]) ## config.h (module 'core'): ns3::Config::MatchContainer::MatchContainer(std::vector<ns3::Ptr<ns3::Object>, std::allocator<ns3::Ptr<ns3::Object> > > const & objects, std::vector<std::string, std::allocator<std::string> > const & contexts, std::string path) [constructor] cls.add_constructor([param('std::vector< ns3::Ptr< ns3::Object > > const &', 'objects'), param('std::vector< std::string > const &', 'contexts'), param('std::string', 'path')]) ## config.h (module 'core'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Object>*,std::vector<ns3::Ptr<ns3::Object>, std::allocator<ns3::Ptr<ns3::Object> > > > ns3::Config::MatchContainer::Begin() const [member function] cls.add_method('Begin', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Object > const, std::vector< ns3::Ptr< ns3::Object > > >', [], is_const=True) ## config.h (module 'core'): void ns3::Config::MatchContainer::Connect(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('Connect', 'void', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## config.h (module 'core'): void ns3::Config::MatchContainer::ConnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('ConnectWithoutContext', 'void', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## config.h (module 'core'): void ns3::Config::MatchContainer::Disconnect(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('Disconnect', 'void', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## config.h (module 'core'): void ns3::Config::MatchContainer::DisconnectWithoutContext(std::string name, ns3::CallbackBase const & cb) [member function] cls.add_method('DisconnectWithoutContext', 'void', [param('std::string', 'name'), param('ns3::CallbackBase const &', 'cb')]) ## config.h (module 'core'): __gnu_cxx::__normal_iterator<const ns3::Ptr<ns3::Object>*,std::vector<ns3::Ptr<ns3::Object>, std::allocator<ns3::Ptr<ns3::Object> > > > ns3::Config::MatchContainer::End() const [member function] cls.add_method('End', '__gnu_cxx::__normal_iterator< ns3::Ptr< ns3::Object > const, std::vector< ns3::Ptr< ns3::Object > > >', [], is_const=True) ## config.h (module 'core'): ns3::Ptr<ns3::Object> ns3::Config::MatchContainer::Get(uint32_t i) const [member function] cls.add_method('Get', 'ns3::Ptr< ns3::Object >', [param('uint32_t', 'i')], is_const=True) ## config.h (module 'core'): std::string ns3::Config::MatchContainer::GetMatchedPath(uint32_t i) const [member function] cls.add_method('GetMatchedPath', 'std::string', [param('uint32_t', 'i')], is_const=True) ## config.h (module 'core'): uint32_t ns3::Config::MatchContainer::GetN() const [member function] cls.add_method('GetN', 'uint32_t', [], is_const=True) ## config.h (module 'core'): std::string ns3::Config::MatchContainer::GetPath() const [member function] cls.add_method('GetPath', 'std::string', [], is_const=True) ## config.h (module 'core'): void ns3::Config::MatchContainer::Set(std::string name, ns3::AttributeValue const & value) [member function] cls.add_method('Set', 'void', [param('std::string', 'name'), param('ns3::AttributeValue const &', 'value')]) return def register_functions(root_module): module = root_module register_functions_ns3_Config(module.get_submodule('Config'), root_module) register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) return def register_functions_ns3_Config(module, root_module): return def register_functions_ns3_FatalImpl(module, root_module): return def main(): out = FileCodeSink(sys.stdout) root_module = module_init() register_types(root_module) register_methods(root_module) register_functions(root_module) root_module.generate(out) if __name__ == '__main__': main()
gpl-2.0
willemneal/Docky
lib/pygments/lexers/foxpro.py
134
26236
# -*- coding: utf-8 -*- """ pygments.lexers.foxpro ~~~~~~~~~~~~~~~~~~~~~~ Simple lexer for Microsoft Visual FoxPro source code. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer from pygments.token import Punctuation, Text, Comment, Operator, Keyword, \ Name, String __all__ = ['FoxProLexer'] class FoxProLexer(RegexLexer): """Lexer for Microsoft Visual FoxPro language. FoxPro syntax allows to shorten all keywords and function names to 4 characters. Shortened forms are not recognized by this lexer. .. versionadded:: 1.6 """ name = 'FoxPro' aliases = ['foxpro', 'vfp', 'clipper', 'xbase'] filenames = ['*.PRG', '*.prg'] mimetype = [] flags = re.IGNORECASE | re.MULTILINE tokens = { 'root': [ (r';\s*\n', Punctuation), # consume newline (r'(^|\n)\s*', Text, 'newline'), # Square brackets may be used for array indices # and for string literal. Look for arrays # before matching string literals. (r'(?<=\w)\[[0-9, ]+\]', Text), (r'\'[^\'\n]*\'|"[^"\n]*"|\[[^]*]\]', String), (r'(^\s*\*|&&|&amp;&amp;).*?\n', Comment.Single), (r'(ABS|ACLASS|ACOPY|ACOS|ADATABASES|ADBOBJECTS|ADDBS|' r'ADDPROPERTY|ADEL|ADIR|ADLLS|ADOCKSTATE|AELEMENT|AERROR|' r'AEVENTS|AFIELDS|AFONT|AGETCLASS|AGETFILEVERSION|AINS|' r'AINSTANCE|ALANGUAGE|ALEN|ALIAS|ALINES|ALLTRIM|' r'AMEMBERS|AMOUSEOBJ|ANETRESOURCES|APRINTERS|APROCINFO|' r'ASC|ASCAN|ASELOBJ|ASESSIONS|ASIN|ASORT|ASQLHANDLES|' r'ASTACKINFO|ASUBSCRIPT|AT|AT_C|ATAGINFO|ATAN|ATC|ATCC|' r'ATCLINE|ATLINE|ATN2|AUSED|AVCXCLASSES|BAR|BARCOUNT|' r'BARPROMPT|BETWEEN|BINDEVENT|BINTOC|BITAND|BITCLEAR|' r'BITLSHIFT|BITNOT|BITOR|BITRSHIFT|BITSET|BITTEST|BITXOR|' r'BOF|CANDIDATE|CAPSLOCK|CAST|CDOW|CDX|CEILING|CHR|CHRSAW|' r'CHRTRAN|CHRTRANC|CLEARRESULTSET|CMONTH|CNTBAR|CNTPAD|COL|' r'COM|Functions|COMARRAY|COMCLASSINFO|COMPOBJ|COMPROP|' r'COMRETURNERROR|COS|CPCONVERT|CPCURRENT|CPDBF|CREATEBINARY|' r'CREATEOBJECT|CREATEOBJECTEX|CREATEOFFLINE|CTOBIN|CTOD|' r'CTOT|CURDIR|CURSORGETPROP|CURSORSETPROP|CURSORTOXML|' r'CURVAL|DATE|DATETIME|DAY|DBC|DBF|DBGETPROP|DBSETPROP|' r'DBUSED|DDEAbortTrans|DDEAdvise|DDEEnabled|DDEExecute|' r'DDEInitiate|DDELastError|DDEPoke|DDERequest|DDESetOption|' r'DDESetService|DDESetTopic|DDETerminate|DEFAULTEXT|' r'DELETED|DESCENDING|DIFFERENCE|DIRECTORY|DISKSPACE|' r'DisplayPath|DMY|DODEFAULT|DOW|DRIVETYPE|DROPOFFLINE|' r'DTOC|DTOR|DTOS|DTOT|EDITSOURCE|EMPTY|EOF|ERROR|EVAL(UATE)?|' r'EVENTHANDLER|EVL|EXECSCRIPT|EXP|FCHSIZE|FCLOSE|FCOUNT|' r'FCREATE|FDATE|FEOF|FERROR|FFLUSH|FGETS|FIELD|FILE|' r'FILETOSTR|FILTER|FKLABEL|FKMAX|FLDLIST|FLOCK|FLOOR|' r'FONTMETRIC|FOPEN|FOR|FORCEEXT|FORCEPATH|FOUND|FPUTS|' r'FREAD|FSEEK|FSIZE|FTIME|FULLPATH|FV|FWRITE|' r'GETAUTOINCVALUE|GETBAR|GETCOLOR|GETCP|GETDIR|GETENV|' r'GETFILE|GETFLDSTATE|GETFONT|GETINTERFACE|' r'GETNEXTMODIFIED|GETOBJECT|GETPAD|GETPEM|GETPICT|' r'GETPRINTER|GETRESULTSET|GETWORDCOUNT|GETWORDNUM|' r'GETCURSORADAPTER|GOMONTH|HEADER|HOME|HOUR|ICASE|' r'IDXCOLLATE|IIF|IMESTATUS|INDBC|INDEXSEEK|INKEY|INLIST|' r'INPUTBOX|INSMODE|INT|ISALPHA|ISBLANK|ISCOLOR|ISDIGIT|' r'ISEXCLUSIVE|ISFLOCKED|ISLEADBYTE|ISLOWER|ISMEMOFETCHED|' r'ISMOUSE|ISNULL|ISPEN|ISREADONLY|ISRLOCKED|' r'ISTRANSACTABLE|ISUPPER|JUSTDRIVE|JUSTEXT|JUSTFNAME|' r'JUSTPATH|JUSTSTEM|KEY|KEYMATCH|LASTKEY|LEFT|LEFTC|LEN|' r'LENC|LIKE|LIKEC|LINENO|LOADPICTURE|LOCFILE|LOCK|LOG|' r'LOG10|LOOKUP|LOWER|LTRIM|LUPDATE|MAKETRANSACTABLE|MAX|' r'MCOL|MDOWN|MDX|MDY|MEMLINES|MEMORY|MENU|MESSAGE|' r'MESSAGEBOX|MIN|MINUTE|MLINE|MOD|MONTH|MRKBAR|MRKPAD|' r'MROW|MTON|MWINDOW|NDX|NEWOBJECT|NORMALIZE|NTOM|NUMLOCK|' r'NVL|OBJNUM|OBJTOCLIENT|OBJVAR|OCCURS|OEMTOANSI|OLDVAL|' r'ON|ORDER|OS|PAD|PADL|PARAMETERS|PAYMENT|PCOL|PCOUNT|' r'PEMSTATUS|PI|POPUP|PRIMARY|PRINTSTATUS|PRMBAR|PRMPAD|' r'PROGRAM|PROMPT|PROPER|PROW|PRTINFO|PUTFILE|PV|QUARTER|' r'RAISEEVENT|RAND|RAT|RATC|RATLINE|RDLEVEL|READKEY|RECCOUNT|' r'RECNO|RECSIZE|REFRESH|RELATION|REPLICATE|REQUERY|RGB|' r'RGBSCHEME|RIGHT|RIGHTC|RLOCK|ROUND|ROW|RTOD|RTRIM|' r'SAVEPICTURE|SCHEME|SCOLS|SEC|SECONDS|SEEK|SELECT|SET|' r'SETFLDSTATE|SETRESULTSET|SIGN|SIN|SKPBAR|SKPPAD|SOUNDEX|' r'SPACE|SQLCANCEL|SQLCOLUMNS|SQLCOMMIT|SQLCONNECT|' r'SQLDISCONNECT|SQLEXEC|SQLGETPROP|SQLIDLEDISCONNECT|' r'SQLMORERESULTS|SQLPREPARE|SQLROLLBACK|SQLSETPROP|' r'SQLSTRINGCONNECT|SQLTABLES|SQRT|SROWS|STR|STRCONV|' r'STREXTRACT|STRTOFILE|STRTRAN|STUFF|STUFFC|SUBSTR|' r'SUBSTRC|SYS|SYSMETRIC|TABLEREVERT|TABLEUPDATE|TAG|' r'TAGCOUNT|TAGNO|TAN|TARGET|TEXTMERGE|TIME|TRANSFORM|' r'TRIM|TTOC|TTOD|TXNLEVEL|TXTWIDTH|TYPE|UNBINDEVENTS|' r'UNIQUE|UPDATED|UPPER|USED|VAL|VARREAD|VARTYPE|VERSION|' r'WBORDER|WCHILD|WCOLS|WDOCKABLE|WEEK|WEXIST|WFONT|WLAST|' r'WLCOL|WLROW|WMAXIMUM|WMINIMUM|WONTOP|WOUTPUT|WPARENT|' r'WREAD|WROWS|WTITLE|WVISIBLE|XMLTOCURSOR|XMLUPDATEGRAM|' r'YEAR)(?=\s*\()', Name.Function), (r'_ALIGNMENT|_ASCIICOLS|_ASCIIROWS|_ASSIST|_BEAUTIFY|_BOX|' r'_BROWSER|_BUILDER|_CALCMEM|_CALCVALUE|_CLIPTEXT|_CONVERTER|' r'_COVERAGE|_CUROBJ|_DBLCLICK|_DIARYDATE|_DOS|_FOXDOC|_FOXREF|' r'_GALLERY|_GENGRAPH|_GENHTML|_GENMENU|_GENPD|_GENSCRN|' r'_GENXTAB|_GETEXPR|_INCLUDE|_INCSEEK|_INDENT|_LMARGIN|_MAC|' r'_MENUDESIGNER|_MLINE|_PADVANCE|_PAGENO|_PAGETOTAL|_PBPAGE|' r'_PCOLNO|_PCOPIES|_PDRIVER|_PDSETUP|_PECODE|_PEJECT|_PEPAGE|' r'_PLENGTH|_PLINENO|_PLOFFSET|_PPITCH|_PQUALITY|_PRETEXT|' r'_PSCODE|_PSPACING|_PWAIT|_RMARGIN|_REPORTBUILDER|' r'_REPORTOUTPUT|_REPORTPREVIEW|_SAMPLES|_SCCTEXT|_SCREEN|' r'_SHELL|_SPELLCHK|_STARTUP|_TABS|_TALLY|_TASKPANE|_TEXT|' r'_THROTTLE|_TOOLBOX|_TOOLTIPTIMEOUT|_TRANSPORT|_TRIGGERLEVEL|' r'_UNIX|_VFP|_WINDOWS|_WIZARD|_WRAP', Keyword.Pseudo), (r'THISFORMSET|THISFORM|THIS', Name.Builtin), (r'Application|CheckBox|Collection|Column|ComboBox|' r'CommandButton|CommandGroup|Container|Control|CursorAdapter|' r'Cursor|Custom|DataEnvironment|DataObject|EditBox|' r'Empty|Exception|Fields|Files|File|FormSet|Form|FoxCode|' r'Grid|Header|Hyperlink|Image|Label|Line|ListBox|Objects|' r'OptionButton|OptionGroup|PageFrame|Page|ProjectHook|Projects|' r'Project|Relation|ReportListener|Separator|Servers|Server|' r'Session|Shape|Spinner|Tables|TextBox|Timer|ToolBar|' r'XMLAdapter|XMLField|XMLTable', Name.Class), (r'm\.[a-z_]\w*', Name.Variable), (r'\.(F|T|AND|OR|NOT|NULL)\.|\b(AND|OR|NOT|NULL)\b', Operator.Word), (r'\.(ActiveColumn|ActiveControl|ActiveForm|ActivePage|' r'ActiveProject|ActiveRow|AddLineFeeds|ADOCodePage|Alias|' r'Alignment|Align|AllowAddNew|AllowAutoColumnFit|' r'AllowCellSelection|AllowDelete|AllowHeaderSizing|' r'AllowInsert|AllowModalMessages|AllowOutput|AllowRowSizing|' r'AllowSimultaneousFetch|AllowTabs|AllowUpdate|' r'AlwaysOnBottom|AlwaysOnTop|Anchor|Application|' r'AutoActivate|AutoCenter|AutoCloseTables|AutoComplete|' r'AutoCompSource|AutoCompTable|AutoHideScrollBar|' r'AutoIncrement|AutoOpenTables|AutoRelease|AutoSize|' r'AutoVerbMenu|AutoYield|BackColor|ForeColor|BackStyle|' r'BaseClass|BatchUpdateCount|BindControls|BorderColor|' r'BorderStyle|BorderWidth|BoundColumn|BoundTo|Bound|' r'BreakOnError|BufferModeOverride|BufferMode|' r'BuildDateTime|ButtonCount|Buttons|Cancel|Caption|' r'Centered|Century|ChildAlias|ChildOrder|ChildTable|' r'ClassLibrary|Class|ClipControls|Closable|CLSID|CodePage|' r'ColorScheme|ColorSource|ColumnCount|ColumnLines|' r'ColumnOrder|Columns|ColumnWidths|CommandClauses|' r'Comment|CompareMemo|ConflictCheckCmd|ConflictCheckType|' r'ContinuousScroll|ControlBox|ControlCount|Controls|' r'ControlSource|ConversionFunc|Count|CurrentControl|' r'CurrentDataSession|CurrentPass|CurrentX|CurrentY|' r'CursorSchema|CursorSource|CursorStatus|Curvature|' r'Database|DataSessionID|DataSession|DataSourceType|' r'DataSource|DataType|DateFormat|DateMark|Debug|' r'DeclareXMLPrefix|DEClassLibrary|DEClass|DefaultFilePath|' r'Default|DefOLELCID|DeleteCmdDataSourceType|DeleteCmdDataSource|' r'DeleteCmd|DeleteMark|Description|Desktop|' r'Details|DisabledBackColor|DisabledForeColor|' r'DisabledItemBackColor|DisabledItemForeColor|' r'DisabledPicture|DisableEncode|DisplayCount|' r'DisplayValue|Dockable|Docked|DockPosition|' r'DocumentFile|DownPicture|DragIcon|DragMode|DrawMode|' r'DrawStyle|DrawWidth|DynamicAlignment|DynamicBackColor|' r'DynamicForeColor|DynamicCurrentControl|DynamicFontBold|' r'DynamicFontItalic|DynamicFontStrikethru|' r'DynamicFontUnderline|DynamicFontName|DynamicFontOutline|' r'DynamicFontShadow|DynamicFontSize|DynamicInputMask|' r'DynamicLineHeight|EditorOptions|Enabled|' r'EnableHyperlinks|Encrypted|ErrorNo|Exclude|Exclusive|' r'FetchAsNeeded|FetchMemoCmdList|FetchMemoDataSourceType|' r'FetchMemoDataSource|FetchMemo|FetchSize|' r'FileClassLibrary|FileClass|FillColor|FillStyle|Filter|' r'FirstElement|FirstNestedTable|Flags|FontBold|FontItalic|' r'FontStrikethru|FontUnderline|FontCharSet|FontCondense|' r'FontExtend|FontName|FontOutline|FontShadow|FontSize|' r'ForceCloseTag|Format|FormCount|FormattedOutput|Forms|' r'FractionDigits|FRXDataSession|FullName|GDIPlusGraphics|' r'GridLineColor|GridLines|GridLineWidth|HalfHeightCaption|' r'HeaderClassLibrary|HeaderClass|HeaderHeight|Height|' r'HelpContextID|HideSelection|HighlightBackColor|' r'HighlightForeColor|HighlightStyle|HighlightRowLineWidth|' r'HighlightRow|Highlight|HomeDir|Hours|HostName|' r'HScrollSmallChange|hWnd|Icon|IncrementalSearch|Increment|' r'InitialSelectedAlias|InputMask|InsertCmdDataSourceType|' r'InsertCmdDataSource|InsertCmdRefreshCmd|' r'InsertCmdRefreshFieldList|InsertCmdRefreshKeyFieldList|' r'InsertCmd|Instancing|IntegralHeight|' r'Interval|IMEMode|IsAttribute|IsBase64|IsBinary|IsNull|' r'IsDiffGram|IsLoaded|ItemBackColor,|ItemData|ItemIDData|' r'ItemTips|IXMLDOMElement|KeyboardHighValue|KeyboardLowValue|' r'Keyfield|KeyFieldList|KeyPreview|KeySort|LanguageOptions|' r'LeftColumn|Left|LineContents|LineNo|LineSlant|LinkMaster|' r'ListCount|ListenerType|ListIndex|ListItemID|ListItem|' r'List|LockColumnsLeft|LockColumns|LockScreen|MacDesktop|' r'MainFile|MapN19_4ToCurrency|MapBinary|MapVarchar|Margin|' r'MaxButton|MaxHeight|MaxLeft|MaxLength|MaxRecords|MaxTop|' r'MaxWidth|MDIForm|MemberClassLibrary|MemberClass|' r'MemoWindow|Message|MinButton|MinHeight|MinWidth|' r'MouseIcon|MousePointer|Movable|MoverBars|MultiSelect|' r'Name|NestedInto|NewIndex|NewItemID|NextSiblingTable|' r'NoCpTrans|NoDataOnLoad|NoData|NullDisplay|' r'NumberOfElements|Object|OLEClass|OLEDragMode|' r'OLEDragPicture|OLEDropEffects|OLEDropHasData|' r'OLEDropMode|OLEDropTextInsertion|OLELCID|' r'OLERequestPendingTimeout|OLEServerBusyRaiseError|' r'OLEServerBusyTimeout|OLETypeAllowed|OneToMany|' r'OpenViews|OpenWindow|Optimize|OrderDirection|Order|' r'OutputPageCount|OutputType|PageCount|PageHeight|' r'PageNo|PageOrder|Pages|PageTotal|PageWidth|' r'PanelLink|Panel|ParentAlias|ParentClass|ParentTable|' r'Parent|Partition|PasswordChar|PictureMargin|' r'PicturePosition|PictureSpacing|PictureSelectionDisplay|' r'PictureVal|Picture|Prepared|' r'PolyPoints|PreserveWhiteSpace|PreviewContainer|' r'PrintJobName|Procedure|PROCESSID|ProgID|ProjectHookClass|' r'ProjectHookLibrary|ProjectHook|QuietMode|' r'ReadCycle|ReadLock|ReadMouse|ReadObject|ReadOnly|' r'ReadSave|ReadTimeout|RecordMark|RecordSourceType|' r'RecordSource|RefreshAlias|' r'RefreshCmdDataSourceType|RefreshCmdDataSource|RefreshCmd|' r'RefreshIgnoreFieldList|RefreshTimeStamp|RelationalExpr|' r'RelativeColumn|RelativeRow|ReleaseType|Resizable|' r'RespectCursorCP|RespectNesting|RightToLeft|RotateFlip|' r'Rotation|RowColChange|RowHeight|RowSourceType|' r'RowSource|ScaleMode|SCCProvider|SCCStatus|ScrollBars|' r'Seconds|SelectCmd|SelectedID|' r'SelectedItemBackColor|SelectedItemForeColor|Selected|' r'SelectionNamespaces|SelectOnEntry|SelLength|SelStart|' r'SelText|SendGDIPlusImage|SendUpdates|ServerClassLibrary|' r'ServerClass|ServerHelpFile|ServerName|' r'ServerProject|ShowTips|ShowInTaskbar|ShowWindow|' r'Sizable|SizeBox|SOM|Sorted|Sparse|SpecialEffect|' r'SpinnerHighValue|SpinnerLowValue|SplitBar|StackLevel|' r'StartMode|StatusBarText|StatusBar|Stretch|StrictDateEntry|' r'Style|TabIndex|Tables|TabOrientation|Tabs|TabStop|' r'TabStretch|TabStyle|Tag|TerminateRead|Text|Themes|' r'ThreadID|TimestampFieldList|TitleBar|ToolTipText|' r'TopIndex|TopItemID|Top|TwoPassProcess|TypeLibCLSID|' r'TypeLibDesc|TypeLibName|Type|Unicode|UpdatableFieldList|' r'UpdateCmdDataSourceType|UpdateCmdDataSource|' r'UpdateCmdRefreshCmd|UpdateCmdRefreshFieldList|' r'UpdateCmdRefreshKeyFieldList|UpdateCmd|' r'UpdateGramSchemaLocation|UpdateGram|UpdateNameList|UpdateType|' r'UseCodePage|UseCursorSchema|UseDeDataSource|UseMemoSize|' r'UserValue|UseTransactions|UTF8Encoded|Value|VersionComments|' r'VersionCompany|VersionCopyright|VersionDescription|' r'VersionNumber|VersionProduct|VersionTrademarks|Version|' r'VFPXMLProgID|ViewPortHeight|ViewPortLeft|' r'ViewPortTop|ViewPortWidth|VScrollSmallChange|View|Visible|' r'VisualEffect|WhatsThisButton|WhatsThisHelpID|WhatsThisHelp|' r'WhereType|Width|WindowList|WindowState|WindowType|WordWrap|' r'WrapCharInCDATA|WrapInCDATA|WrapMemoInCDATA|XMLAdapter|' r'XMLConstraints|XMLNameIsXPath|XMLNamespace|XMLName|' r'XMLPrefix|XMLSchemaLocation|XMLTable|XMLType|' r'XSDfractionDigits|XSDmaxLength|XSDtotalDigits|' r'XSDtype|ZoomBox)', Name.Attribute), (r'\.(ActivateCell|AddColumn|AddItem|AddListItem|AddObject|' r'AddProperty|AddTableSchema|AddToSCC|Add|' r'ApplyDiffgram|Attach|AutoFit|AutoOpen|Box|Build|' r'CancelReport|ChangesToCursor|CheckIn|CheckOut|Circle|' r'CleanUp|ClearData|ClearStatus|Clear|CloneObject|CloseTables|' r'Close|Cls|CursorAttach|CursorDetach|CursorFill|' r'CursorRefresh|DataToClip|DelayedMemoFetch|DeleteColumn|' r'Dock|DoMessage|DoScroll|DoStatus|DoVerb|Drag|Draw|Eval|' r'GetData|GetDockState|GetFormat|GetKey|GetLatestVersion|' r'GetPageHeight|GetPageWidth|Help|Hide|IncludePageInOutput|' r'IndexToItemID|ItemIDToIndex|Item|LoadXML|Line|Modify|' r'MoveItem|Move|Nest|OLEDrag|OnPreviewClose|OutputPage|' r'Point|Print|PSet|Quit|ReadExpression|ReadMethod|' r'RecordRefresh|Refresh|ReleaseXML|Release|RemoveFromSCC|' r'RemoveItem|RemoveListItem|RemoveObject|Remove|' r'Render|Requery|RequestData|ResetToDefault|Reset|Run|' r'SaveAsClass|SaveAs|SetAll|SetData|SetFocus|SetFormat|' r'SetMain|SetVar|SetViewPort|ShowWhatsThis|Show|' r'SupportsListenerType|TextHeight|TextWidth|ToCursor|' r'ToXML|UndoCheckOut|Unnest|UpdateStatus|WhatsThisMode|' r'WriteExpression|WriteMethod|ZOrder)', Name.Function), (r'\.(Activate|AdjustObjectSize|AfterBand|AfterBuild|' r'AfterCloseTables|AfterCursorAttach|AfterCursorClose|' r'AfterCursorDetach|AfterCursorFill|AfterCursorRefresh|' r'AfterCursorUpdate|AfterDelete|AfterInsert|' r'AfterRecordRefresh|AfterUpdate|AfterDock|AfterReport|' r'AfterRowColChange|BeforeBand|BeforeCursorAttach|' r'BeforeCursorClose|BeforeCursorDetach|BeforeCursorFill|' r'BeforeCursorRefresh|BeforeCursorUpdate|BeforeDelete|' r'BeforeInsert|BeforeDock|BeforeOpenTables|' r'BeforeRecordRefresh|BeforeReport|BeforeRowColChange|' r'BeforeUpdate|Click|dbc_Activate|dbc_AfterAddTable|' r'dbc_AfterAppendProc|dbc_AfterCloseTable|dbc_AfterCopyProc|' r'dbc_AfterCreateConnection|dbc_AfterCreateOffline|' r'dbc_AfterCreateTable|dbc_AfterCreateView|dbc_AfterDBGetProp|' r'dbc_AfterDBSetProp|dbc_AfterDeleteConnection|' r'dbc_AfterDropOffline|dbc_AfterDropTable|' r'dbc_AfterModifyConnection|dbc_AfterModifyProc|' r'dbc_AfterModifyTable|dbc_AfterModifyView|dbc_AfterOpenTable|' r'dbc_AfterRemoveTable|dbc_AfterRenameConnection|' r'dbc_AfterRenameTable|dbc_AfterRenameView|' r'dbc_AfterValidateData|dbc_BeforeAddTable|' r'dbc_BeforeAppendProc|dbc_BeforeCloseTable|' r'dbc_BeforeCopyProc|dbc_BeforeCreateConnection|' r'dbc_BeforeCreateOffline|dbc_BeforeCreateTable|' r'dbc_BeforeCreateView|dbc_BeforeDBGetProp|' r'dbc_BeforeDBSetProp|dbc_BeforeDeleteConnection|' r'dbc_BeforeDropOffline|dbc_BeforeDropTable|' r'dbc_BeforeModifyConnection|dbc_BeforeModifyProc|' r'dbc_BeforeModifyTable|dbc_BeforeModifyView|' r'dbc_BeforeOpenTable|dbc_BeforeRemoveTable|' r'dbc_BeforeRenameConnection|dbc_BeforeRenameTable|' r'dbc_BeforeRenameView|dbc_BeforeValidateData|' r'dbc_CloseData|dbc_Deactivate|dbc_ModifyData|dbc_OpenData|' r'dbc_PackData|DblClick|Deactivate|Deleted|Destroy|DoCmd|' r'DownClick|DragDrop|DragOver|DropDown|ErrorMessage|Error|' r'EvaluateContents|GotFocus|Init|InteractiveChange|KeyPress|' r'LoadReport|Load|LostFocus|Message|MiddleClick|MouseDown|' r'MouseEnter|MouseLeave|MouseMove|MouseUp|MouseWheel|Moved|' r'OLECompleteDrag|OLEDragOver|OLEGiveFeedback|OLESetData|' r'OLEStartDrag|OnMoveItem|Paint|ProgrammaticChange|' r'QueryAddFile|QueryModifyFile|QueryNewFile|QueryRemoveFile|' r'QueryRunFile|QueryUnload|RangeHigh|RangeLow|ReadActivate|' r'ReadDeactivate|ReadShow|ReadValid|ReadWhen|Resize|' r'RightClick|SCCInit|SCCDestroy|Scrolled|Timer|UIEnable|' r'UnDock|UnloadReport|Unload|UpClick|Valid|When)', Name.Function), (r'\s+', Text), # everything else is not colored (r'.', Text), ], 'newline': [ (r'\*.*?$', Comment.Single, '#pop'), (r'(ACCEPT|ACTIVATE\s*MENU|ACTIVATE\s*POPUP|ACTIVATE\s*SCREEN|' r'ACTIVATE\s*WINDOW|APPEND|APPEND\s*FROM|APPEND\s*FROM\s*ARRAY|' r'APPEND\s*GENERAL|APPEND\s*MEMO|ASSIST|AVERAGE|BLANK|BROWSE|' r'BUILD\s*APP|BUILD\s*EXE|BUILD\s*PROJECT|CALCULATE|CALL|' r'CANCEL|CHANGE|CLEAR|CLOSE|CLOSE\s*MEMO|COMPILE|CONTINUE|' r'COPY\s*FILE|COPY\s*INDEXES|COPY\s*MEMO|COPY\s*STRUCTURE|' r'COPY\s*STRUCTURE\s*EXTENDED|COPY\s*TAG|COPY\s*TO|' r'COPY\s*TO\s*ARRAY|COUNT|CREATE|CREATE\s*COLOR\s*SET|' r'CREATE\s*CURSOR|CREATE\s*FROM|CREATE\s*LABEL|CREATE\s*MENU|' r'CREATE\s*PROJECT|CREATE\s*QUERY|CREATE\s*REPORT|' r'CREATE\s*SCREEN|CREATE\s*TABLE|CREATE\s*VIEW|DDE|' r'DEACTIVATE\s*MENU|DEACTIVATE\s*POPUP|DEACTIVATE\s*WINDOW|' r'DECLARE|DEFINE\s*BAR|DEFINE\s*BOX|DEFINE\s*MENU|' r'DEFINE\s*PAD|DEFINE\s*POPUP|DEFINE\s*WINDOW|DELETE|' r'DELETE\s*FILE|DELETE\s*TAG|DIMENSION|DIRECTORY|DISPLAY|' r'DISPLAY\s*FILES|DISPLAY\s*MEMORY|DISPLAY\s*STATUS|' r'DISPLAY\s*STRUCTURE|DO|EDIT|EJECT|EJECT\s*PAGE|ERASE|' r'EXIT|EXPORT|EXTERNAL|FILER|FIND|FLUSH|FUNCTION|GATHER|' r'GETEXPR|GO|GOTO|HELP|HIDE\s*MENU|HIDE\s*POPUP|' r'HIDE\s*WINDOW|IMPORT|INDEX|INPUT|INSERT|JOIN|KEYBOARD|' r'LABEL|LIST|LOAD|LOCATE|LOOP|MENU|MENU\s*TO|MODIFY\s*COMMAND|' r'MODIFY\s*FILE|MODIFY\s*GENERAL|MODIFY\s*LABEL|MODIFY\s*MEMO|' r'MODIFY\s*MENU|MODIFY\s*PROJECT|MODIFY\s*QUERY|' r'MODIFY\s*REPORT|MODIFY\s*SCREEN|MODIFY\s*STRUCTURE|' r'MODIFY\s*WINDOW|MOVE\s*POPUP|MOVE\s*WINDOW|NOTE|' r'ON\s*APLABOUT|ON\s*BAR|ON\s*ERROR|ON\s*ESCAPE|' r'ON\s*EXIT\s*BAR|ON\s*EXIT\s*MENU|ON\s*EXIT\s*PAD|' r'ON\s*EXIT\s*POPUP|ON\s*KEY|ON\s*KEY\s*=|ON\s*KEY\s*LABEL|' r'ON\s*MACHELP|ON\s*PAD|ON\s*PAGE|ON\s*READERROR|' r'ON\s*SELECTION\s*BAR|ON\s*SELECTION\s*MENU|' r'ON\s*SELECTION\s*PAD|ON\s*SELECTION\s*POPUP|ON\s*SHUTDOWN|' r'PACK|PARAMETERS|PLAY\s*MACRO|POP\s*KEY|POP\s*MENU|' r'POP\s*POPUP|PRIVATE|PROCEDURE|PUBLIC|PUSH\s*KEY|' r'PUSH\s*MENU|PUSH\s*POPUP|QUIT|READ|READ\s*MENU|RECALL|' r'REINDEX|RELEASE|RELEASE\s*MODULE|RENAME|REPLACE|' r'REPLACE\s*FROM\s*ARRAY|REPORT|RESTORE\s*FROM|' r'RESTORE\s*MACROS|RESTORE\s*SCREEN|RESTORE\s*WINDOW|' r'RESUME|RETRY|RETURN|RUN|RUN\s*\/N"|RUNSCRIPT|' r'SAVE\s*MACROS|SAVE\s*SCREEN|SAVE\s*TO|SAVE\s*WINDOWS|' r'SCATTER|SCROLL|SEEK|SELECT|SET|SET\s*ALTERNATE|' r'SET\s*ANSI|SET\s*APLABOUT|SET\s*AUTOSAVE|SET\s*BELL|' r'SET\s*BLINK|SET\s*BLOCKSIZE|SET\s*BORDER|SET\s*BRSTATUS|' r'SET\s*CARRY|SET\s*CENTURY|SET\s*CLEAR|SET\s*CLOCK|' r'SET\s*COLLATE|SET\s*COLOR\s*OF|SET\s*COLOR\s*OF\s*SCHEME|' r'SET\s*COLOR\s*SET|SET\s*COLOR\s*TO|SET\s*COMPATIBLE|' r'SET\s*CONFIRM|SET\s*CONSOLE|SET\s*CURRENCY|SET\s*CURSOR|' r'SET\s*DATE|SET\s*DEBUG|SET\s*DECIMALS|SET\s*DEFAULT|' r'SET\s*DELETED|SET\s*DELIMITERS|SET\s*DEVELOPMENT|' r'SET\s*DEVICE|SET\s*DISPLAY|SET\s*DOHISTORY|SET\s*ECHO|' r'SET\s*ESCAPE|SET\s*EXACT|SET\s*EXCLUSIVE|SET\s*FIELDS|' r'SET\s*FILTER|SET\s*FIXED|SET\s*FORMAT|SET\s*FULLPATH|' r'SET\s*FUNCTION|SET\s*HEADINGS|SET\s*HELP|SET\s*HELPFILTER|' r'SET\s*HOURS|SET\s*INDEX|SET\s*INTENSITY|SET\s*KEY|' r'SET\s*KEYCOMP|SET\s*LIBRARY|SET\s*LOCK|SET\s*LOGERRORS|' r'SET\s*MACDESKTOP|SET\s*MACHELP|SET\s*MACKEY|SET\s*MARGIN|' r'SET\s*MARK\s*OF|SET\s*MARK\s*TO|SET\s*MEMOWIDTH|' r'SET\s*MESSAGE|SET\s*MOUSE|SET\s*MULTILOCKS|SET\s*NEAR|' r'SET\s*NOCPTRANS|SET\s*NOTIFY|SET\s*ODOMETER|SET\s*OPTIMIZE|' r'SET\s*ORDER|SET\s*PALETTE|SET\s*PATH|SET\s*PDSETUP|' r'SET\s*POINT|SET\s*PRINTER|SET\s*PROCEDURE|SET\s*READBORDER|' r'SET\s*REFRESH|SET\s*RELATION|SET\s*RELATION\s*OFF|' r'SET\s*REPROCESS|SET\s*RESOURCE|SET\s*SAFETY|SET\s*SCOREBOARD|' r'SET\s*SEPARATOR|SET\s*SHADOWS|SET\s*SKIP|SET\s*SKIP\s*OF|' r'SET\s*SPACE|SET\s*STATUS|SET\s*STATUS\s*BAR|SET\s*STEP|' r'SET\s*STICKY|SET\s*SYSMENU|SET\s*TALK|SET\s*TEXTMERGE|' r'SET\s*TEXTMERGE\s*DELIMITERS|SET\s*TOPIC|SET\s*TRBETWEEN|' r'SET\s*TYPEAHEAD|SET\s*UDFPARMS|SET\s*UNIQUE|SET\s*VIEW|' r'SET\s*VOLUME|SET\s*WINDOW\s*OF\s*MEMO|SET\s*XCMDFILE|' r'SHOW\s*GET|SHOW\s*GETS|SHOW\s*MENU|SHOW\s*OBJECT|' r'SHOW\s*POPUP|SHOW\s*WINDOW|SIZE\s*POPUP|SKIP|SORT|' r'STORE|SUM|SUSPEND|TOTAL|TYPE|UNLOCK|UPDATE|USE|WAIT|' r'ZAP|ZOOM\s*WINDOW|DO\s*CASE|CASE|OTHERWISE|ENDCASE|' r'DO\s*WHILE|ENDDO|FOR|ENDFOR|NEXT|IF|ELSE|ENDIF|PRINTJOB|' r'ENDPRINTJOB|SCAN|ENDSCAN|TEXT|ENDTEXT|=)', Keyword.Reserved, '#pop'), (r'#\s*(IF|ELIF|ELSE|ENDIF|DEFINE|IFDEF|IFNDEF|INCLUDE)', Comment.Preproc, '#pop'), (r'(m\.)?[a-z_]\w*', Name.Variable, '#pop'), (r'.', Text, '#pop'), ], }
mit
destinmoulton/squabble
pythonclient/venv/lib/python2.7/site-packages/setuptools/command/easy_install.py
109
74243
#!/usr/bin/env python """ Easy Install ------------ A tool for doing automatic download/extract/build of distutils-based Python packages. For detailed documentation, see the accompanying EasyInstall.txt file, or visit the `EasyInstall home page`__. __ https://pythonhosted.org/setuptools/easy_install.html """ import sys import os import zipimport import shutil import tempfile import zipfile import re import stat import random import platform import textwrap import warnings import site import struct from glob import glob from distutils import log, dir_util from distutils.command.build_scripts import first_line_re import pkg_resources from setuptools import Command, _dont_write_bytecode from setuptools.sandbox import run_setup from setuptools.py31compat import get_path, get_config_vars from distutils.util import get_platform from distutils.util import convert_path, subst_vars from distutils.errors import DistutilsArgError, DistutilsOptionError, \ DistutilsError, DistutilsPlatformError from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS from setuptools.command import setopt from setuptools.archive_util import unpack_archive from setuptools.package_index import PackageIndex from setuptools.package_index import URL_SCHEME from setuptools.command import bdist_egg, egg_info from setuptools.compat import (iteritems, maxsize, basestring, unicode, reraise) from pkg_resources import ( yield_lines, normalize_path, resource_string, ensure_directory, get_distribution, find_distributions, Environment, Requirement, Distribution, PathMetadata, EggMetadata, WorkingSet, DistributionNotFound, VersionConflict, DEVELOP_DIST, ) sys_executable = os.environ.get('__PYVENV_LAUNCHER__', os.path.normpath(sys.executable)) __all__ = [ 'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg', 'main', 'get_exe_prefixes', ] def is_64bit(): return struct.calcsize("P") == 8 def samefile(p1, p2): both_exist = os.path.exists(p1) and os.path.exists(p2) use_samefile = hasattr(os.path, 'samefile') and both_exist if use_samefile: return os.path.samefile(p1, p2) norm_p1 = os.path.normpath(os.path.normcase(p1)) norm_p2 = os.path.normpath(os.path.normcase(p2)) return norm_p1 == norm_p2 if sys.version_info <= (3,): def _to_ascii(s): return s def isascii(s): try: unicode(s, 'ascii') return True except UnicodeError: return False else: def _to_ascii(s): return s.encode('ascii') def isascii(s): try: s.encode('ascii') return True except UnicodeError: return False class easy_install(Command): """Manage a download/build/install process""" description = "Find/get/install Python packages" command_consumes_arguments = True user_options = [ ('prefix=', None, "installation prefix"), ("zip-ok", "z", "install package as a zipfile"), ("multi-version", "m", "make apps have to require() a version"), ("upgrade", "U", "force upgrade (searches PyPI for latest versions)"), ("install-dir=", "d", "install package to DIR"), ("script-dir=", "s", "install scripts to DIR"), ("exclude-scripts", "x", "Don't install scripts"), ("always-copy", "a", "Copy all needed packages to install dir"), ("index-url=", "i", "base URL of Python Package Index"), ("find-links=", "f", "additional URL(s) to search for packages"), ("build-directory=", "b", "download/extract/build in DIR; keep the results"), ('optimize=', 'O', "also compile with optimization: -O1 for \"python -O\", " "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"), ('record=', None, "filename in which to record list of installed files"), ('always-unzip', 'Z', "don't install as a zipfile, no matter what"), ('site-dirs=','S',"list of directories where .pth files work"), ('editable', 'e', "Install specified packages in editable form"), ('no-deps', 'N', "don't install dependencies"), ('allow-hosts=', 'H', "pattern(s) that hostnames must match"), ('local-snapshots-ok', 'l', "allow building eggs from local checkouts"), ('version', None, "print version information and exit"), ('no-find-links', None, "Don't load find-links defined in packages being installed") ] boolean_options = [ 'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy', 'editable', 'no-deps', 'local-snapshots-ok', 'version' ] if site.ENABLE_USER_SITE: help_msg = "install in user site-package '%s'" % site.USER_SITE user_options.append(('user', None, help_msg)) boolean_options.append('user') negative_opt = {'always-unzip': 'zip-ok'} create_index = PackageIndex def initialize_options(self): if site.ENABLE_USER_SITE: whereami = os.path.abspath(__file__) self.user = whereami.startswith(site.USER_SITE) else: self.user = 0 self.zip_ok = self.local_snapshots_ok = None self.install_dir = self.script_dir = self.exclude_scripts = None self.index_url = None self.find_links = None self.build_directory = None self.args = None self.optimize = self.record = None self.upgrade = self.always_copy = self.multi_version = None self.editable = self.no_deps = self.allow_hosts = None self.root = self.prefix = self.no_report = None self.version = None self.install_purelib = None # for pure module distributions self.install_platlib = None # non-pure (dists w/ extensions) self.install_headers = None # for C/C++ headers self.install_lib = None # set to either purelib or platlib self.install_scripts = None self.install_data = None self.install_base = None self.install_platbase = None if site.ENABLE_USER_SITE: self.install_userbase = site.USER_BASE self.install_usersite = site.USER_SITE else: self.install_userbase = None self.install_usersite = None self.no_find_links = None # Options not specifiable via command line self.package_index = None self.pth_file = self.always_copy_from = None self.site_dirs = None self.installed_projects = {} self.sitepy_installed = False # Always read easy_install options, even if we are subclassed, or have # an independent instance created. This ensures that defaults will # always come from the standard configuration file(s)' "easy_install" # section, even if this is a "develop" or "install" command, or some # other embedding. self._dry_run = None self.verbose = self.distribution.verbose self.distribution._set_command_options( self, self.distribution.get_option_dict('easy_install') ) def delete_blockers(self, blockers): for filename in blockers: if os.path.exists(filename) or os.path.islink(filename): log.info("Deleting %s", filename) if not self.dry_run: if os.path.isdir(filename) and not os.path.islink(filename): rmtree(filename) else: os.unlink(filename) def finalize_options(self): if self.version: print('setuptools %s' % get_distribution('setuptools').version) sys.exit() py_version = sys.version.split()[0] prefix, exec_prefix = get_config_vars('prefix', 'exec_prefix') self.config_vars = { 'dist_name': self.distribution.get_name(), 'dist_version': self.distribution.get_version(), 'dist_fullname': self.distribution.get_fullname(), 'py_version': py_version, 'py_version_short': py_version[0:3], 'py_version_nodot': py_version[0] + py_version[2], 'sys_prefix': prefix, 'prefix': prefix, 'sys_exec_prefix': exec_prefix, 'exec_prefix': exec_prefix, # Only python 3.2+ has abiflags 'abiflags': getattr(sys, 'abiflags', ''), } if site.ENABLE_USER_SITE: self.config_vars['userbase'] = self.install_userbase self.config_vars['usersite'] = self.install_usersite # fix the install_dir if "--user" was used #XXX: duplicate of the code in the setup command if self.user and site.ENABLE_USER_SITE: self.create_home_path() if self.install_userbase is None: raise DistutilsPlatformError( "User base directory is not specified") self.install_base = self.install_platbase = self.install_userbase if os.name == 'posix': self.select_scheme("unix_user") else: self.select_scheme(os.name + "_user") self.expand_basedirs() self.expand_dirs() self._expand('install_dir','script_dir','build_directory','site_dirs') # If a non-default installation directory was specified, default the # script directory to match it. if self.script_dir is None: self.script_dir = self.install_dir if self.no_find_links is None: self.no_find_links = False # Let install_dir get set by install_lib command, which in turn # gets its info from the install command, and takes into account # --prefix and --home and all that other crud. self.set_undefined_options('install_lib', ('install_dir','install_dir') ) # Likewise, set default script_dir from 'install_scripts.install_dir' self.set_undefined_options('install_scripts', ('install_dir', 'script_dir') ) if self.user and self.install_purelib: self.install_dir = self.install_purelib self.script_dir = self.install_scripts # default --record from the install command self.set_undefined_options('install', ('record', 'record')) # Should this be moved to the if statement below? It's not used # elsewhere normpath = map(normalize_path, sys.path) self.all_site_dirs = get_site_dirs() if self.site_dirs is not None: site_dirs = [ os.path.expanduser(s.strip()) for s in self.site_dirs.split(',') ] for d in site_dirs: if not os.path.isdir(d): log.warn("%s (in --site-dirs) does not exist", d) elif normalize_path(d) not in normpath: raise DistutilsOptionError( d+" (in --site-dirs) is not on sys.path" ) else: self.all_site_dirs.append(normalize_path(d)) if not self.editable: self.check_site_dir() self.index_url = self.index_url or "https://pypi.python.org/simple" self.shadow_path = self.all_site_dirs[:] for path_item in self.install_dir, normalize_path(self.script_dir): if path_item not in self.shadow_path: self.shadow_path.insert(0, path_item) if self.allow_hosts is not None: hosts = [s.strip() for s in self.allow_hosts.split(',')] else: hosts = ['*'] if self.package_index is None: self.package_index = self.create_index( self.index_url, search_path = self.shadow_path, hosts=hosts, ) self.local_index = Environment(self.shadow_path+sys.path) if self.find_links is not None: if isinstance(self.find_links, basestring): self.find_links = self.find_links.split() else: self.find_links = [] if self.local_snapshots_ok: self.package_index.scan_egg_links(self.shadow_path+sys.path) if not self.no_find_links: self.package_index.add_find_links(self.find_links) self.set_undefined_options('install_lib', ('optimize','optimize')) if not isinstance(self.optimize,int): try: self.optimize = int(self.optimize) if not (0 <= self.optimize <= 2): raise ValueError except ValueError: raise DistutilsOptionError("--optimize must be 0, 1, or 2") if self.editable and not self.build_directory: raise DistutilsArgError( "Must specify a build directory (-b) when using --editable" ) if not self.args: raise DistutilsArgError( "No urls, filenames, or requirements specified (see --help)") self.outputs = [] def _expand_attrs(self, attrs): for attr in attrs: val = getattr(self, attr) if val is not None: if os.name == 'posix' or os.name == 'nt': val = os.path.expanduser(val) val = subst_vars(val, self.config_vars) setattr(self, attr, val) def expand_basedirs(self): """Calls `os.path.expanduser` on install_base, install_platbase and root.""" self._expand_attrs(['install_base', 'install_platbase', 'root']) def expand_dirs(self): """Calls `os.path.expanduser` on install dirs.""" self._expand_attrs(['install_purelib', 'install_platlib', 'install_lib', 'install_headers', 'install_scripts', 'install_data',]) def run(self): if self.verbose != self.distribution.verbose: log.set_verbosity(self.verbose) try: for spec in self.args: self.easy_install(spec, not self.no_deps) if self.record: outputs = self.outputs if self.root: # strip any package prefix root_len = len(self.root) for counter in range(len(outputs)): outputs[counter] = outputs[counter][root_len:] from distutils import file_util self.execute( file_util.write_file, (self.record, outputs), "writing list of installed files to '%s'" % self.record ) self.warn_deprecated_options() finally: log.set_verbosity(self.distribution.verbose) def pseudo_tempname(self): """Return a pseudo-tempname base in the install directory. This code is intentionally naive; if a malicious party can write to the target directory you're already in deep doodoo. """ try: pid = os.getpid() except: pid = random.randint(0, maxsize) return os.path.join(self.install_dir, "test-easy-install-%s" % pid) def warn_deprecated_options(self): pass def check_site_dir(self): """Verify that self.install_dir is .pth-capable dir, if needed""" instdir = normalize_path(self.install_dir) pth_file = os.path.join(instdir,'easy-install.pth') # Is it a configured, PYTHONPATH, implicit, or explicit site dir? is_site_dir = instdir in self.all_site_dirs if not is_site_dir and not self.multi_version: # No? Then directly test whether it does .pth file processing is_site_dir = self.check_pth_processing() else: # make sure we can write to target dir testfile = self.pseudo_tempname()+'.write-test' test_exists = os.path.exists(testfile) try: if test_exists: os.unlink(testfile) open(testfile,'w').close() os.unlink(testfile) except (OSError,IOError): self.cant_write_to_target() if not is_site_dir and not self.multi_version: # Can't install non-multi to non-site dir raise DistutilsError(self.no_default_version_msg()) if is_site_dir: if self.pth_file is None: self.pth_file = PthDistributions(pth_file, self.all_site_dirs) else: self.pth_file = None PYTHONPATH = os.environ.get('PYTHONPATH','').split(os.pathsep) if instdir not in map(normalize_path, [_f for _f in PYTHONPATH if _f]): # only PYTHONPATH dirs need a site.py, so pretend it's there self.sitepy_installed = True elif self.multi_version and not os.path.exists(pth_file): self.sitepy_installed = True # don't need site.py in this case self.pth_file = None # and don't create a .pth file self.install_dir = instdir def cant_write_to_target(self): template = """can't create or remove files in install directory The following error occurred while trying to add or remove files in the installation directory: %s The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: %s """ msg = template % (sys.exc_info()[1], self.install_dir,) if not os.path.exists(self.install_dir): msg += """ This directory does not currently exist. Please create it and try again, or choose a different installation directory (using the -d or --install-dir option). """ else: msg += """ Perhaps your account does not have write access to this directory? If the installation directory is a system-owned directory, you may need to sign in as the administrator or "root" account. If you do not have administrative access to this machine, you may wish to choose a different installation directory, preferably one that is listed in your PYTHONPATH environment variable. For information on other options, you may wish to consult the documentation at: https://pythonhosted.org/setuptools/easy_install.html Please make the appropriate changes for your system and try again. """ raise DistutilsError(msg) def check_pth_processing(self): """Empirically verify whether .pth files are supported in inst. dir""" instdir = self.install_dir log.info("Checking .pth file support in %s", instdir) pth_file = self.pseudo_tempname()+".pth" ok_file = pth_file+'.ok' ok_exists = os.path.exists(ok_file) try: if ok_exists: os.unlink(ok_file) dirname = os.path.dirname(ok_file) if not os.path.exists(dirname): os.makedirs(dirname) f = open(pth_file,'w') except (OSError,IOError): self.cant_write_to_target() else: try: f.write("import os; f = open(%r, 'w'); f.write('OK'); f.close()\n" % (ok_file,)) f.close() f=None executable = sys.executable if os.name=='nt': dirname,basename = os.path.split(executable) alt = os.path.join(dirname,'pythonw.exe') if basename.lower()=='python.exe' and os.path.exists(alt): # use pythonw.exe to avoid opening a console window executable = alt from distutils.spawn import spawn spawn([executable,'-E','-c','pass'],0) if os.path.exists(ok_file): log.info( "TEST PASSED: %s appears to support .pth files", instdir ) return True finally: if f: f.close() if os.path.exists(ok_file): os.unlink(ok_file) if os.path.exists(pth_file): os.unlink(pth_file) if not self.multi_version: log.warn("TEST FAILED: %s does NOT support .pth files", instdir) return False def install_egg_scripts(self, dist): """Write all the scripts for `dist`, unless scripts are excluded""" if not self.exclude_scripts and dist.metadata_isdir('scripts'): for script_name in dist.metadata_listdir('scripts'): if dist.metadata_isdir('scripts/' + script_name): # The "script" is a directory, likely a Python 3 # __pycache__ directory, so skip it. continue self.install_script( dist, script_name, dist.get_metadata('scripts/'+script_name) ) self.install_wrapper_scripts(dist) def add_output(self, path): if os.path.isdir(path): for base, dirs, files in os.walk(path): for filename in files: self.outputs.append(os.path.join(base,filename)) else: self.outputs.append(path) def not_editable(self, spec): if self.editable: raise DistutilsArgError( "Invalid argument %r: you can't use filenames or URLs " "with --editable (except via the --find-links option)." % (spec,) ) def check_editable(self,spec): if not self.editable: return if os.path.exists(os.path.join(self.build_directory, spec.key)): raise DistutilsArgError( "%r already exists in %s; can't do a checkout there" % (spec.key, self.build_directory) ) def easy_install(self, spec, deps=False): tmpdir = tempfile.mkdtemp(prefix="easy_install-") download = None if not self.editable: self.install_site_py() try: if not isinstance(spec,Requirement): if URL_SCHEME(spec): # It's a url, download it to tmpdir and process self.not_editable(spec) download = self.package_index.download(spec, tmpdir) return self.install_item(None, download, tmpdir, deps, True) elif os.path.exists(spec): # Existing file or directory, just process it directly self.not_editable(spec) return self.install_item(None, spec, tmpdir, deps, True) else: spec = parse_requirement_arg(spec) self.check_editable(spec) dist = self.package_index.fetch_distribution( spec, tmpdir, self.upgrade, self.editable, not self.always_copy, self.local_index ) if dist is None: msg = "Could not find suitable distribution for %r" % spec if self.always_copy: msg+=" (--always-copy skips system and development eggs)" raise DistutilsError(msg) elif dist.precedence==DEVELOP_DIST: # .egg-info dists don't need installing, just process deps self.process_distribution(spec, dist, deps, "Using") return dist else: return self.install_item(spec, dist.location, tmpdir, deps) finally: if os.path.exists(tmpdir): rmtree(tmpdir) def install_item(self, spec, download, tmpdir, deps, install_needed=False): # Installation is also needed if file in tmpdir or is not an egg install_needed = install_needed or self.always_copy install_needed = install_needed or os.path.dirname(download) == tmpdir install_needed = install_needed or not download.endswith('.egg') install_needed = install_needed or ( self.always_copy_from is not None and os.path.dirname(normalize_path(download)) == normalize_path(self.always_copy_from) ) if spec and not install_needed: # at this point, we know it's a local .egg, we just don't know if # it's already installed. for dist in self.local_index[spec.project_name]: if dist.location==download: break else: install_needed = True # it's not in the local index log.info("Processing %s", os.path.basename(download)) if install_needed: dists = self.install_eggs(spec, download, tmpdir) for dist in dists: self.process_distribution(spec, dist, deps) else: dists = [self.egg_distribution(download)] self.process_distribution(spec, dists[0], deps, "Using") if spec is not None: for dist in dists: if dist in spec: return dist def select_scheme(self, name): """Sets the install directories by applying the install schemes.""" # it's the caller's problem if they supply a bad name! scheme = INSTALL_SCHEMES[name] for key in SCHEME_KEYS: attrname = 'install_' + key if getattr(self, attrname) is None: setattr(self, attrname, scheme[key]) def process_distribution(self, requirement, dist, deps=True, *info): self.update_pth(dist) self.package_index.add(dist) # First remove the dist from self.local_index, to avoid problems using # old cached data in case its underlying file has been replaced. # # This is a quick-fix for a zipimporter caching issue in case the dist # has been implemented as and already loaded from a zip file that got # replaced later on. For more detailed information see setuptools issue # #168 at 'http://bitbucket.org/pypa/setuptools/issue/168'. if dist in self.local_index[dist.key]: self.local_index.remove(dist) self.local_index.add(dist) self.install_egg_scripts(dist) self.installed_projects[dist.key] = dist log.info(self.installation_report(requirement, dist, *info)) if (dist.has_metadata('dependency_links.txt') and not self.no_find_links): self.package_index.add_find_links( dist.get_metadata_lines('dependency_links.txt') ) if not deps and not self.always_copy: return elif requirement is not None and dist.key != requirement.key: log.warn("Skipping dependencies for %s", dist) return # XXX this is not the distribution we were looking for elif requirement is None or dist not in requirement: # if we wound up with a different version, resolve what we've got distreq = dist.as_requirement() requirement = requirement or distreq requirement = Requirement( distreq.project_name, distreq.specs, requirement.extras ) log.info("Processing dependencies for %s", requirement) try: distros = WorkingSet([]).resolve( [requirement], self.local_index, self.easy_install ) except DistributionNotFound: e = sys.exc_info()[1] raise DistutilsError( "Could not find required distribution %s" % e.args ) except VersionConflict: e = sys.exc_info()[1] raise DistutilsError( "Installed distribution %s conflicts with requirement %s" % e.args ) if self.always_copy or self.always_copy_from: # Force all the relevant distros to be copied or activated for dist in distros: if dist.key not in self.installed_projects: self.easy_install(dist.as_requirement()) log.info("Finished processing dependencies for %s", requirement) def should_unzip(self, dist): if self.zip_ok is not None: return not self.zip_ok if dist.has_metadata('not-zip-safe'): return True if not dist.has_metadata('zip-safe'): return True return False def maybe_move(self, spec, dist_filename, setup_base): dst = os.path.join(self.build_directory, spec.key) if os.path.exists(dst): msg = "%r already exists in %s; build directory %s will not be kept" log.warn(msg, spec.key, self.build_directory, setup_base) return setup_base if os.path.isdir(dist_filename): setup_base = dist_filename else: if os.path.dirname(dist_filename)==setup_base: os.unlink(dist_filename) # get it out of the tmp dir contents = os.listdir(setup_base) if len(contents)==1: dist_filename = os.path.join(setup_base,contents[0]) if os.path.isdir(dist_filename): # if the only thing there is a directory, move it instead setup_base = dist_filename ensure_directory(dst) shutil.move(setup_base, dst) return dst def install_wrapper_scripts(self, dist): if not self.exclude_scripts: for args in get_script_args(dist): self.write_script(*args) def install_script(self, dist, script_name, script_text, dev_path=None): """Generate a legacy script wrapper and install it""" spec = str(dist.as_requirement()) is_script = is_python_script(script_text, script_name) def get_template(filename): """ There are a couple of template scripts in the package. This function loads one of them and prepares it for use. These templates use triple-quotes to escape variable substitutions so the scripts get the 2to3 treatment when build on Python 3. The templates cannot use triple-quotes naturally. """ raw_bytes = resource_string('setuptools', template_name) template_str = raw_bytes.decode('utf-8') clean_template = template_str.replace('"""', '') return clean_template if is_script: # See https://bitbucket.org/pypa/setuptools/issue/134 for info # on script file naming and downstream issues with SVR4 template_name = 'script template.py' if dev_path: template_name = template_name.replace('.py', ' (dev).py') script_text = (get_script_header(script_text) + get_template(template_name) % locals()) self.write_script(script_name, _to_ascii(script_text), 'b') def write_script(self, script_name, contents, mode="t", blockers=()): """Write an executable file to the scripts directory""" self.delete_blockers( # clean up old .py/.pyw w/o a script [os.path.join(self.script_dir,x) for x in blockers]) log.info("Installing %s script to %s", script_name, self.script_dir) target = os.path.join(self.script_dir, script_name) self.add_output(target) mask = current_umask() if not self.dry_run: ensure_directory(target) if os.path.exists(target): os.unlink(target) f = open(target,"w"+mode) f.write(contents) f.close() chmod(target, 0o777-mask) def install_eggs(self, spec, dist_filename, tmpdir): # .egg dirs or files are already built, so just return them if dist_filename.lower().endswith('.egg'): return [self.install_egg(dist_filename, tmpdir)] elif dist_filename.lower().endswith('.exe'): return [self.install_exe(dist_filename, tmpdir)] # Anything else, try to extract and build setup_base = tmpdir if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'): unpack_archive(dist_filename, tmpdir, self.unpack_progress) elif os.path.isdir(dist_filename): setup_base = os.path.abspath(dist_filename) if (setup_base.startswith(tmpdir) # something we downloaded and self.build_directory and spec is not None): setup_base = self.maybe_move(spec, dist_filename, setup_base) # Find the setup.py file setup_script = os.path.join(setup_base, 'setup.py') if not os.path.exists(setup_script): setups = glob(os.path.join(setup_base, '*', 'setup.py')) if not setups: raise DistutilsError( "Couldn't find a setup script in %s" % os.path.abspath(dist_filename) ) if len(setups)>1: raise DistutilsError( "Multiple setup scripts in %s" % os.path.abspath(dist_filename) ) setup_script = setups[0] # Now run it, and return the result if self.editable: log.info(self.report_editable(spec, setup_script)) return [] else: return self.build_and_install(setup_script, setup_base) def egg_distribution(self, egg_path): if os.path.isdir(egg_path): metadata = PathMetadata(egg_path,os.path.join(egg_path,'EGG-INFO')) else: metadata = EggMetadata(zipimport.zipimporter(egg_path)) return Distribution.from_filename(egg_path,metadata=metadata) def install_egg(self, egg_path, tmpdir): destination = os.path.join(self.install_dir,os.path.basename(egg_path)) destination = os.path.abspath(destination) if not self.dry_run: ensure_directory(destination) dist = self.egg_distribution(egg_path) if not samefile(egg_path, destination): if os.path.isdir(destination) and not os.path.islink(destination): dir_util.remove_tree(destination, dry_run=self.dry_run) elif os.path.exists(destination): self.execute(os.unlink,(destination,),"Removing "+destination) uncache_zipdir(destination) if os.path.isdir(egg_path): if egg_path.startswith(tmpdir): f,m = shutil.move, "Moving" else: f,m = shutil.copytree, "Copying" elif self.should_unzip(dist): self.mkpath(destination) f,m = self.unpack_and_compile, "Extracting" elif egg_path.startswith(tmpdir): f,m = shutil.move, "Moving" else: f,m = shutil.copy2, "Copying" self.execute(f, (egg_path, destination), (m+" %s to %s") % (os.path.basename(egg_path),os.path.dirname(destination))) self.add_output(destination) return self.egg_distribution(destination) def install_exe(self, dist_filename, tmpdir): # See if it's valid, get data cfg = extract_wininst_cfg(dist_filename) if cfg is None: raise DistutilsError( "%s is not a valid distutils Windows .exe" % dist_filename ) # Create a dummy distribution object until we build the real distro dist = Distribution( None, project_name=cfg.get('metadata','name'), version=cfg.get('metadata','version'), platform=get_platform(), ) # Convert the .exe to an unpacked egg egg_path = dist.location = os.path.join(tmpdir, dist.egg_name()+'.egg') egg_tmp = egg_path + '.tmp' _egg_info = os.path.join(egg_tmp, 'EGG-INFO') pkg_inf = os.path.join(_egg_info, 'PKG-INFO') ensure_directory(pkg_inf) # make sure EGG-INFO dir exists dist._provider = PathMetadata(egg_tmp, _egg_info) # XXX self.exe_to_egg(dist_filename, egg_tmp) # Write EGG-INFO/PKG-INFO if not os.path.exists(pkg_inf): f = open(pkg_inf,'w') f.write('Metadata-Version: 1.0\n') for k,v in cfg.items('metadata'): if k != 'target_version': f.write('%s: %s\n' % (k.replace('_','-').title(), v)) f.close() script_dir = os.path.join(_egg_info,'scripts') self.delete_blockers( # delete entry-point scripts to avoid duping [os.path.join(script_dir,args[0]) for args in get_script_args(dist)] ) # Build .egg file from tmpdir bdist_egg.make_zipfile( egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run ) # install the .egg return self.install_egg(egg_path, tmpdir) def exe_to_egg(self, dist_filename, egg_tmp): """Extract a bdist_wininst to the directories an egg would use""" # Check for .pth file and set up prefix translations prefixes = get_exe_prefixes(dist_filename) to_compile = [] native_libs = [] top_level = {} def process(src,dst): s = src.lower() for old,new in prefixes: if s.startswith(old): src = new+src[len(old):] parts = src.split('/') dst = os.path.join(egg_tmp, *parts) dl = dst.lower() if dl.endswith('.pyd') or dl.endswith('.dll'): parts[-1] = bdist_egg.strip_module(parts[-1]) top_level[os.path.splitext(parts[0])[0]] = 1 native_libs.append(src) elif dl.endswith('.py') and old!='SCRIPTS/': top_level[os.path.splitext(parts[0])[0]] = 1 to_compile.append(dst) return dst if not src.endswith('.pth'): log.warn("WARNING: can't process %s", src) return None # extract, tracking .pyd/.dll->native_libs and .py -> to_compile unpack_archive(dist_filename, egg_tmp, process) stubs = [] for res in native_libs: if res.lower().endswith('.pyd'): # create stubs for .pyd's parts = res.split('/') resource = parts[-1] parts[-1] = bdist_egg.strip_module(parts[-1])+'.py' pyfile = os.path.join(egg_tmp, *parts) to_compile.append(pyfile) stubs.append(pyfile) bdist_egg.write_stub(resource, pyfile) self.byte_compile(to_compile) # compile .py's bdist_egg.write_safety_flag(os.path.join(egg_tmp,'EGG-INFO'), bdist_egg.analyze_egg(egg_tmp, stubs)) # write zip-safety flag for name in 'top_level','native_libs': if locals()[name]: txt = os.path.join(egg_tmp, 'EGG-INFO', name+'.txt') if not os.path.exists(txt): f = open(txt,'w') f.write('\n'.join(locals()[name])+'\n') f.close() def installation_report(self, req, dist, what="Installed"): """Helpful installation message for display to package users""" msg = "\n%(what)s %(eggloc)s%(extras)s" if self.multi_version and not self.no_report: msg += """ Because this distribution was installed --multi-version, before you can import modules from this package in an application, you will need to 'import pkg_resources' and then use a 'require()' call similar to one of these examples, in order to select the desired version: pkg_resources.require("%(name)s") # latest installed version pkg_resources.require("%(name)s==%(version)s") # this exact version pkg_resources.require("%(name)s>=%(version)s") # this version or higher """ if self.install_dir not in map(normalize_path,sys.path): msg += """ Note also that the installation directory must be on sys.path at runtime for this to work. (e.g. by being the application's script directory, by being on PYTHONPATH, or by being added to sys.path by your code.) """ eggloc = dist.location name = dist.project_name version = dist.version extras = '' # TODO: self.report_extras(req, dist) return msg % locals() def report_editable(self, spec, setup_script): dirname = os.path.dirname(setup_script) python = sys.executable return """\nExtracted editable version of %(spec)s to %(dirname)s If it uses setuptools in its setup script, you can activate it in "development" mode by going to that directory and running:: %(python)s setup.py develop See the setuptools documentation for the "develop" command for more info. """ % locals() def run_setup(self, setup_script, setup_base, args): sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg) sys.modules.setdefault('distutils.command.egg_info', egg_info) args = list(args) if self.verbose>2: v = 'v' * (self.verbose - 1) args.insert(0,'-'+v) elif self.verbose<2: args.insert(0,'-q') if self.dry_run: args.insert(0,'-n') log.info( "Running %s %s", setup_script[len(setup_base)+1:], ' '.join(args) ) try: run_setup(setup_script, args) except SystemExit: v = sys.exc_info()[1] raise DistutilsError("Setup script exited with %s" % (v.args[0],)) def build_and_install(self, setup_script, setup_base): args = ['bdist_egg', '--dist-dir'] dist_dir = tempfile.mkdtemp( prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script) ) try: self._set_fetcher_options(os.path.dirname(setup_script)) args.append(dist_dir) self.run_setup(setup_script, setup_base, args) all_eggs = Environment([dist_dir]) eggs = [] for key in all_eggs: for dist in all_eggs[key]: eggs.append(self.install_egg(dist.location, setup_base)) if not eggs and not self.dry_run: log.warn("No eggs found in %s (setup script problem?)", dist_dir) return eggs finally: rmtree(dist_dir) log.set_verbosity(self.verbose) # restore our log verbosity def _set_fetcher_options(self, base): """ When easy_install is about to run bdist_egg on a source dist, that source dist might have 'setup_requires' directives, requiring additional fetching. Ensure the fetcher options given to easy_install are available to that command as well. """ # find the fetch options from easy_install and write them out # to the setup.cfg file. ei_opts = self.distribution.get_option_dict('easy_install').copy() fetch_directives = ( 'find_links', 'site_dirs', 'index_url', 'optimize', 'site_dirs', 'allow_hosts', ) fetch_options = {} for key, val in ei_opts.items(): if key not in fetch_directives: continue fetch_options[key.replace('_', '-')] = val[1] # create a settings dictionary suitable for `edit_config` settings = dict(easy_install=fetch_options) cfg_filename = os.path.join(base, 'setup.cfg') setopt.edit_config(cfg_filename, settings) def update_pth(self, dist): if self.pth_file is None: return for d in self.pth_file[dist.key]: # drop old entries if self.multi_version or d.location != dist.location: log.info("Removing %s from easy-install.pth file", d) self.pth_file.remove(d) if d.location in self.shadow_path: self.shadow_path.remove(d.location) if not self.multi_version: if dist.location in self.pth_file.paths: log.info( "%s is already the active version in easy-install.pth", dist ) else: log.info("Adding %s to easy-install.pth file", dist) self.pth_file.add(dist) # add new entry if dist.location not in self.shadow_path: self.shadow_path.append(dist.location) if not self.dry_run: self.pth_file.save() if dist.key=='setuptools': # Ensure that setuptools itself never becomes unavailable! # XXX should this check for latest version? filename = os.path.join(self.install_dir,'setuptools.pth') if os.path.islink(filename): os.unlink(filename) f = open(filename, 'wt') f.write(self.pth_file.make_relative(dist.location)+'\n') f.close() def unpack_progress(self, src, dst): # Progress filter for unpacking log.debug("Unpacking %s to %s", src, dst) return dst # only unpack-and-compile skips files for dry run def unpack_and_compile(self, egg_path, destination): to_compile = [] to_chmod = [] def pf(src, dst): if dst.endswith('.py') and not src.startswith('EGG-INFO/'): to_compile.append(dst) elif dst.endswith('.dll') or dst.endswith('.so'): to_chmod.append(dst) self.unpack_progress(src,dst) return not self.dry_run and dst or None unpack_archive(egg_path, destination, pf) self.byte_compile(to_compile) if not self.dry_run: for f in to_chmod: mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755 chmod(f, mode) def byte_compile(self, to_compile): if _dont_write_bytecode: self.warn('byte-compiling is disabled, skipping.') return from distutils.util import byte_compile try: # try to make the byte compile messages quieter log.set_verbosity(self.verbose - 1) byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run) if self.optimize: byte_compile( to_compile, optimize=self.optimize, force=1, dry_run=self.dry_run ) finally: log.set_verbosity(self.verbose) # restore original verbosity def no_default_version_msg(self): template = """bad install directory or PYTHONPATH You are attempting to install a package to a directory that is not on PYTHONPATH and which Python does not read ".pth" files from. The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: %s and your PYTHONPATH environment variable currently contains: %r Here are some of your options for correcting the problem: * You can choose a different installation directory, i.e., one that is on PYTHONPATH or supports .pth files * You can add the installation directory to the PYTHONPATH environment variable. (It must then also be on PYTHONPATH whenever you run Python and want to use the package(s) you are installing.) * You can set up the installation directory to support ".pth" files by using one of the approaches described here: https://pythonhosted.org/setuptools/easy_install.html#custom-installation-locations Please make the appropriate changes for your system and try again.""" return template % (self.install_dir, os.environ.get('PYTHONPATH','')) def install_site_py(self): """Make sure there's a site.py in the target dir, if needed""" if self.sitepy_installed: return # already did it, or don't need to sitepy = os.path.join(self.install_dir, "site.py") source = resource_string("setuptools", "site-patch.py") current = "" if os.path.exists(sitepy): log.debug("Checking existing site.py in %s", self.install_dir) f = open(sitepy,'rb') current = f.read() # we want str, not bytes if sys.version_info >= (3,): current = current.decode() f.close() if not current.startswith('def __boot():'): raise DistutilsError( "%s is not a setuptools-generated site.py; please" " remove it." % sitepy ) if current != source: log.info("Creating %s", sitepy) if not self.dry_run: ensure_directory(sitepy) f = open(sitepy,'wb') f.write(source) f.close() self.byte_compile([sitepy]) self.sitepy_installed = True def create_home_path(self): """Create directories under ~.""" if not self.user: return home = convert_path(os.path.expanduser("~")) for name, path in iteritems(self.config_vars): if path.startswith(home) and not os.path.isdir(path): self.debug_print("os.makedirs('%s', 0o700)" % path) os.makedirs(path, 0o700) INSTALL_SCHEMES = dict( posix = dict( install_dir = '$base/lib/python$py_version_short/site-packages', script_dir = '$base/bin', ), ) DEFAULT_SCHEME = dict( install_dir = '$base/Lib/site-packages', script_dir = '$base/Scripts', ) def _expand(self, *attrs): config_vars = self.get_finalized_command('install').config_vars if self.prefix: # Set default install_dir/scripts from --prefix config_vars = config_vars.copy() config_vars['base'] = self.prefix scheme = self.INSTALL_SCHEMES.get(os.name,self.DEFAULT_SCHEME) for attr,val in scheme.items(): if getattr(self,attr,None) is None: setattr(self,attr,val) from distutils.util import subst_vars for attr in attrs: val = getattr(self, attr) if val is not None: val = subst_vars(val, config_vars) if os.name == 'posix': val = os.path.expanduser(val) setattr(self, attr, val) def get_site_dirs(): # return a list of 'site' dirs sitedirs = [_f for _f in os.environ.get('PYTHONPATH', '').split(os.pathsep) if _f] prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) for prefix in prefixes: if prefix: if sys.platform in ('os2emx', 'riscos'): sitedirs.append(os.path.join(prefix, "Lib", "site-packages")) elif os.sep == '/': sitedirs.extend([os.path.join(prefix, "lib", "python" + sys.version[:3], "site-packages"), os.path.join(prefix, "lib", "site-python")]) else: sitedirs.extend( [prefix, os.path.join(prefix, "lib", "site-packages")] ) if sys.platform == 'darwin': # for framework builds *only* we add the standard Apple # locations. Currently only per-user, but /Library and # /Network/Library could be added too if 'Python.framework' in prefix: home = os.environ.get('HOME') if home: sitedirs.append( os.path.join(home, 'Library', 'Python', sys.version[:3], 'site-packages')) lib_paths = get_path('purelib'), get_path('platlib') for site_lib in lib_paths: if site_lib not in sitedirs: sitedirs.append(site_lib) if site.ENABLE_USER_SITE: sitedirs.append(site.USER_SITE) sitedirs = list(map(normalize_path, sitedirs)) return sitedirs def expand_paths(inputs): """Yield sys.path directories that might contain "old-style" packages""" seen = {} for dirname in inputs: dirname = normalize_path(dirname) if dirname in seen: continue seen[dirname] = 1 if not os.path.isdir(dirname): continue files = os.listdir(dirname) yield dirname, files for name in files: if not name.endswith('.pth'): # We only care about the .pth files continue if name in ('easy-install.pth','setuptools.pth'): # Ignore .pth files that we control continue # Read the .pth file f = open(os.path.join(dirname,name)) lines = list(yield_lines(f)) f.close() # Yield existing non-dupe, non-import directory lines from it for line in lines: if not line.startswith("import"): line = normalize_path(line.rstrip()) if line not in seen: seen[line] = 1 if not os.path.isdir(line): continue yield line, os.listdir(line) def extract_wininst_cfg(dist_filename): """Extract configuration data from a bdist_wininst .exe Returns a ConfigParser.RawConfigParser, or None """ f = open(dist_filename,'rb') try: endrec = zipfile._EndRecData(f) if endrec is None: return None prepended = (endrec[9] - endrec[5]) - endrec[6] if prepended < 12: # no wininst data here return None f.seek(prepended-12) from setuptools.compat import StringIO, ConfigParser import struct tag, cfglen, bmlen = struct.unpack("<iii",f.read(12)) if tag not in (0x1234567A, 0x1234567B): return None # not a valid tag f.seek(prepended-(12+cfglen)) cfg = ConfigParser.RawConfigParser({'version':'','target_version':''}) try: part = f.read(cfglen) # part is in bytes, but we need to read up to the first null # byte. if sys.version_info >= (2,6): null_byte = bytes([0]) else: null_byte = chr(0) config = part.split(null_byte, 1)[0] # Now the config is in bytes, but for RawConfigParser, it should # be text, so decode it. config = config.decode(sys.getfilesystemencoding()) cfg.readfp(StringIO(config)) except ConfigParser.Error: return None if not cfg.has_section('metadata') or not cfg.has_section('Setup'): return None return cfg finally: f.close() def get_exe_prefixes(exe_filename): """Get exe->egg path translations for a given .exe file""" prefixes = [ ('PURELIB/', ''), ('PLATLIB/pywin32_system32', ''), ('PLATLIB/', ''), ('SCRIPTS/', 'EGG-INFO/scripts/'), ('DATA/lib/site-packages', ''), ] z = zipfile.ZipFile(exe_filename) try: for info in z.infolist(): name = info.filename parts = name.split('/') if len(parts)==3 and parts[2]=='PKG-INFO': if parts[1].endswith('.egg-info'): prefixes.insert(0,('/'.join(parts[:2]), 'EGG-INFO/')) break if len(parts) != 2 or not name.endswith('.pth'): continue if name.endswith('-nspkg.pth'): continue if parts[0].upper() in ('PURELIB','PLATLIB'): contents = z.read(name) if sys.version_info >= (3,): contents = contents.decode() for pth in yield_lines(contents): pth = pth.strip().replace('\\','/') if not pth.startswith('import'): prefixes.append((('%s/%s/' % (parts[0],pth)), '')) finally: z.close() prefixes = [(x.lower(),y) for x, y in prefixes] prefixes.sort() prefixes.reverse() return prefixes def parse_requirement_arg(spec): try: return Requirement.parse(spec) except ValueError: raise DistutilsError( "Not a URL, existing file, or requirement spec: %r" % (spec,) ) class PthDistributions(Environment): """A .pth file with Distribution paths in it""" dirty = False def __init__(self, filename, sitedirs=()): self.filename = filename self.sitedirs = list(map(normalize_path, sitedirs)) self.basedir = normalize_path(os.path.dirname(self.filename)) self._load() Environment.__init__(self, [], None, None) for path in yield_lines(self.paths): list(map(self.add, find_distributions(path, True))) def _load(self): self.paths = [] saw_import = False seen = dict.fromkeys(self.sitedirs) if os.path.isfile(self.filename): f = open(self.filename,'rt') for line in f: if line.startswith('import'): saw_import = True continue path = line.rstrip() self.paths.append(path) if not path.strip() or path.strip().startswith('#'): continue # skip non-existent paths, in case somebody deleted a package # manually, and duplicate paths as well path = self.paths[-1] = normalize_path( os.path.join(self.basedir,path) ) if not os.path.exists(path) or path in seen: self.paths.pop() # skip it self.dirty = True # we cleaned up, so we're dirty now :) continue seen[path] = 1 f.close() if self.paths and not saw_import: self.dirty = True # ensure anything we touch has import wrappers while self.paths and not self.paths[-1].strip(): self.paths.pop() def save(self): """Write changed .pth file back to disk""" if not self.dirty: return data = '\n'.join(map(self.make_relative,self.paths)) if data: log.debug("Saving %s", self.filename) data = ( "import sys; sys.__plen = len(sys.path)\n" "%s\n" "import sys; new=sys.path[sys.__plen:];" " del sys.path[sys.__plen:];" " p=getattr(sys,'__egginsert',0); sys.path[p:p]=new;" " sys.__egginsert = p+len(new)\n" ) % data if os.path.islink(self.filename): os.unlink(self.filename) f = open(self.filename,'wt') f.write(data) f.close() elif os.path.exists(self.filename): log.debug("Deleting empty %s", self.filename) os.unlink(self.filename) self.dirty = False def add(self, dist): """Add `dist` to the distribution map""" if (dist.location not in self.paths and ( dist.location not in self.sitedirs or dist.location == os.getcwd() # account for '.' being in PYTHONPATH )): self.paths.append(dist.location) self.dirty = True Environment.add(self, dist) def remove(self, dist): """Remove `dist` from the distribution map""" while dist.location in self.paths: self.paths.remove(dist.location) self.dirty = True Environment.remove(self, dist) def make_relative(self,path): npath, last = os.path.split(normalize_path(path)) baselen = len(self.basedir) parts = [last] sep = os.altsep=='/' and '/' or os.sep while len(npath)>=baselen: if npath==self.basedir: parts.append(os.curdir) parts.reverse() return sep.join(parts) npath, last = os.path.split(npath) parts.append(last) else: return path def _first_line_re(): """ Return a regular expression based on first_line_re suitable for matching strings. """ if isinstance(first_line_re.pattern, str): return first_line_re # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern. return re.compile(first_line_re.pattern.decode()) def get_script_header(script_text, executable=sys_executable, wininst=False): """Create a #! line, getting options (if any) from script_text""" first = (script_text+'\n').splitlines()[0] match = _first_line_re().match(first) options = '' if match: options = match.group(1) or '' if options: options = ' '+options if wininst: executable = "python.exe" else: executable = nt_quote_arg(executable) hdr = "#!%(executable)s%(options)s\n" % locals() if not isascii(hdr): # Non-ascii path to sys.executable, use -x to prevent warnings if options: if options.strip().startswith('-'): options = ' -x'+options.strip()[1:] # else: punt, we can't do it, let the warning happen anyway else: options = ' -x' executable = fix_jython_executable(executable, options) hdr = "#!%(executable)s%(options)s\n" % locals() return hdr def auto_chmod(func, arg, exc): if func is os.remove and os.name=='nt': chmod(arg, stat.S_IWRITE) return func(arg) et, ev, _ = sys.exc_info() reraise(et, (ev[0], ev[1] + (" %s %s" % (func,arg)))) def uncache_zipdir(path): """ Remove any globally cached zip file related data for `path` Stale zipimport.zipimporter objects need to be removed when a zip file is replaced as they contain cached zip file directory information. If they are asked to get data from their zip file, they will use that cached information to calculate the data location in the zip file. This calculated location may be incorrect for the replaced zip file, which may in turn cause the read operation to either fail or return incorrect data. Note we have no way to clear any local caches from here. That is left up to whomever is in charge of maintaining that cache. """ normalized_path = normalize_path(path) _uncache(normalized_path, zipimport._zip_directory_cache) _uncache(normalized_path, sys.path_importer_cache) def _uncache(normalized_path, cache): to_remove = [] prefix_len = len(normalized_path) for p in cache: np = normalize_path(p) if (np.startswith(normalized_path) and np[prefix_len:prefix_len + 1] in (os.sep, '')): to_remove.append(p) for p in to_remove: del cache[p] def is_python(text, filename='<string>'): "Is this string a valid Python script?" try: compile(text, filename, 'exec') except (SyntaxError, TypeError): return False else: return True def is_sh(executable): """Determine if the specified executable is a .sh (contains a #! line)""" try: fp = open(executable) magic = fp.read(2) fp.close() except (OSError,IOError): return executable return magic == '#!' def nt_quote_arg(arg): """Quote a command line argument according to Windows parsing rules""" result = [] needquote = False nb = 0 needquote = (" " in arg) or ("\t" in arg) if needquote: result.append('"') for c in arg: if c == '\\': nb += 1 elif c == '"': # double preceding backslashes, then add a \" result.append('\\' * (nb*2) + '\\"') nb = 0 else: if nb: result.append('\\' * nb) nb = 0 result.append(c) if nb: result.append('\\' * nb) if needquote: result.append('\\' * nb) # double the trailing backslashes result.append('"') return ''.join(result) def is_python_script(script_text, filename): """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc. """ if filename.endswith('.py') or filename.endswith('.pyw'): return True # extension says it's Python if is_python(script_text, filename): return True # it's syntactically valid Python if script_text.startswith('#!'): # It begins with a '#!' line, so check if 'python' is in it somewhere return 'python' in script_text.splitlines()[0].lower() return False # Not any Python I can recognize try: from os import chmod as _chmod except ImportError: # Jython compatibility def _chmod(*args): pass def chmod(path, mode): log.debug("changing mode of %s to %o", path, mode) try: _chmod(path, mode) except os.error: e = sys.exc_info()[1] log.debug("chmod failed: %s", e) def fix_jython_executable(executable, options): if sys.platform.startswith('java') and is_sh(executable): # Workaround for Jython is not needed on Linux systems. import java if java.lang.System.getProperty("os.name") == "Linux": return executable # Workaround Jython's sys.executable being a .sh (an invalid # shebang line interpreter) if options: # Can't apply the workaround, leave it broken log.warn( "WARNING: Unable to adapt shebang line for Jython," " the following script is NOT executable\n" " see http://bugs.jython.org/issue1112 for" " more information.") else: return '/usr/bin/env %s' % executable return executable class ScriptWriter(object): """ Encapsulates behavior around writing entry point scripts for console and gui apps. """ template = textwrap.dedent(""" # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r __requires__ = %(spec)r import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point(%(spec)r, %(group)r, %(name)r)() ) """).lstrip() @classmethod def get_script_args(cls, dist, executable=sys_executable, wininst=False): """ Yield write_script() argument tuples for a distribution's entrypoints """ gen_class = cls.get_writer(wininst) spec = str(dist.as_requirement()) header = get_script_header("", executable, wininst) for type_ in 'console', 'gui': group = type_ + '_scripts' for name, ep in dist.get_entry_map(group).items(): script_text = gen_class.template % locals() for res in gen_class._get_script_args(type_, name, header, script_text): yield res @classmethod def get_writer(cls, force_windows): if force_windows or sys.platform=='win32': return WindowsScriptWriter.get_writer() return cls @classmethod def _get_script_args(cls, type_, name, header, script_text): # Simply write the stub with no extension. yield (name, header+script_text) class WindowsScriptWriter(ScriptWriter): @classmethod def get_writer(cls): """ Get a script writer suitable for Windows """ writer_lookup = dict( executable=WindowsExecutableLauncherWriter, natural=cls, ) # for compatibility, use the executable launcher by default launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable') return writer_lookup[launcher] @classmethod def _get_script_args(cls, type_, name, header, script_text): "For Windows, add a .py extension" ext = dict(console='.pya', gui='.pyw')[type_] if ext not in os.environ['PATHEXT'].lower().split(';'): warnings.warn("%s not listed in PATHEXT; scripts will not be " "recognized as executables." % ext, UserWarning) old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe'] old.remove(ext) header = cls._adjust_header(type_, header) blockers = [name+x for x in old] yield name+ext, header+script_text, 't', blockers @staticmethod def _adjust_header(type_, orig_header): """ Make sure 'pythonw' is used for gui and and 'python' is used for console (regardless of what sys.executable is). """ pattern = 'pythonw.exe' repl = 'python.exe' if type_ == 'gui': pattern, repl = repl, pattern pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE) new_header = pattern_ob.sub(string=orig_header, repl=repl) clean_header = new_header[2:-1].strip('"') if sys.platform == 'win32' and not os.path.exists(clean_header): # the adjusted version doesn't exist, so return the original return orig_header return new_header class WindowsExecutableLauncherWriter(WindowsScriptWriter): @classmethod def _get_script_args(cls, type_, name, header, script_text): """ For Windows, add a .py extension and an .exe launcher """ if type_=='gui': launcher_type = 'gui' ext = '-script.pyw' old = ['.pyw'] else: launcher_type = 'cli' ext = '-script.py' old = ['.py','.pyc','.pyo'] hdr = cls._adjust_header(type_, header) blockers = [name+x for x in old] yield (name+ext, hdr+script_text, 't', blockers) yield ( name+'.exe', get_win_launcher(launcher_type), 'b' # write in binary mode ) if not is_64bit(): # install a manifest for the launcher to prevent Windows # from detecting it as an installer (which it will for # launchers like easy_install.exe). Consider only # adding a manifest for launchers detected as installers. # See Distribute #143 for details. m_name = name + '.exe.manifest' yield (m_name, load_launcher_manifest(name), 't') # for backward-compatibility get_script_args = ScriptWriter.get_script_args def get_win_launcher(type): """ Load the Windows launcher (executable) suitable for launching a script. `type` should be either 'cli' or 'gui' Returns the executable as a byte string. """ launcher_fn = '%s.exe' % type if platform.machine().lower()=='arm': launcher_fn = launcher_fn.replace(".", "-arm.") if is_64bit(): launcher_fn = launcher_fn.replace(".", "-64.") else: launcher_fn = launcher_fn.replace(".", "-32.") return resource_string('setuptools', launcher_fn) def load_launcher_manifest(name): manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml') if sys.version_info[0] < 3: return manifest % vars() else: return manifest.decode('utf-8') % vars() def rmtree(path, ignore_errors=False, onerror=auto_chmod): """Recursively delete a directory tree. This code is taken from the Python 2.4 version of 'shutil', because the 2.3 version doesn't really work right. """ if ignore_errors: def onerror(*args): pass elif onerror is None: def onerror(*args): raise names = [] try: names = os.listdir(path) except os.error: onerror(os.listdir, path, sys.exc_info()) for name in names: fullname = os.path.join(path, name) try: mode = os.lstat(fullname).st_mode except os.error: mode = 0 if stat.S_ISDIR(mode): rmtree(fullname, ignore_errors, onerror) else: try: os.remove(fullname) except os.error: onerror(os.remove, fullname, sys.exc_info()) try: os.rmdir(path) except os.error: onerror(os.rmdir, path, sys.exc_info()) def current_umask(): tmp = os.umask(0o022) os.umask(tmp) return tmp def bootstrap(): # This function is called when setuptools*.egg is run using /bin/sh import setuptools argv0 = os.path.dirname(setuptools.__path__[0]) sys.argv[0] = argv0 sys.argv.append(argv0) main() def main(argv=None, **kw): from setuptools import setup from setuptools.dist import Distribution import distutils.core USAGE = """\ usage: %(script)s [options] requirement_or_url ... or: %(script)s --help """ def gen_usage(script_name): return USAGE % dict( script=os.path.basename(script_name), ) def with_ei_usage(f): old_gen_usage = distutils.core.gen_usage try: distutils.core.gen_usage = gen_usage return f() finally: distutils.core.gen_usage = old_gen_usage class DistributionWithoutHelpCommands(Distribution): common_usage = "" def _show_help(self,*args,**kw): with_ei_usage(lambda: Distribution._show_help(self,*args,**kw)) if argv is None: argv = sys.argv[1:] with_ei_usage(lambda: setup( script_args = ['-q','easy_install', '-v']+argv, script_name = sys.argv[0] or 'easy_install', distclass=DistributionWithoutHelpCommands, **kw ) )
mit
coffenbacher/askbot-devel
askbot/conf/login_providers.py
1
4822
""" External service key settings """ from askbot.conf.settings_wrapper import settings from askbot.conf.super_groups import LOGIN_USERS_COMMUNICATION from askbot.deps import livesettings from django.utils.translation import ugettext_lazy as _ from django.conf import settings as django_settings from askbot.skins import utils as skin_utils LOGIN_PROVIDERS = livesettings.ConfigurationGroup( 'LOGIN_PROVIDERS', _('Login provider setings'), super_group = LOGIN_USERS_COMMUNICATION ) settings.register( livesettings.BooleanValue( LOGIN_PROVIDERS, 'PASSWORD_REGISTER_SHOW_PROVIDER_BUTTONS', default = True, description=_('Show alternative login provider buttons on the password "Sign Up" page'), ) ) #todo: remove this - we don't want the local login button #but instead always show the login/password field when used settings.register( livesettings.BooleanValue( LOGIN_PROVIDERS, 'SIGNIN_ALWAYS_SHOW_LOCAL_LOGIN', default = True, description=_('Always display local login form and hide "Askbot" button.'), ) ) settings.register( livesettings.BooleanValue( LOGIN_PROVIDERS, 'SIGNIN_WORDPRESS_SITE_ENABLED', default = False, description=_('Activate to allow login with self-hosted wordpress site'), help_text=_('to activate this feature you must fill out the wordpress xml-rpc setting bellow') ) ) settings.register( livesettings.URLValue( LOGIN_PROVIDERS, 'WORDPRESS_SITE_URL', default = '', description=_('Fill it with the wordpress url to the xml-rpc, normally http://mysite.com/xmlrpc.php'), help_text=_('To enable, go to Settings->Writing->Remote Publishing and check the box for XML-RPC') ) ) settings.register( livesettings.ImageValue( LOGIN_PROVIDERS, 'WORDPRESS_SITE_ICON', default='/images/logo.gif', description=_('Upload your icon'), url_resolver=skin_utils.get_media_url ) ) settings.register( livesettings.BooleanValue( LOGIN_PROVIDERS, 'SIGNIN_CUSTOM_OPENID_ENABLED', default=False, description=_('Enable custom OpenID login') ) ) settings.register( livesettings.StringValue( LOGIN_PROVIDERS, 'SIGNIN_CUSTOM_OPENID_NAME', default=_('Custom OpenID'), description=_('Short name for the custom OpenID provider') ) ) CUSTOM_OPENID_MODE_CHOICES = ( ('openid-direct', _('Direct button login')), ('openid-username', _('Requires username')) ) settings.register( livesettings.StringValue( LOGIN_PROVIDERS, 'SIGNIN_CUSTOM_OPENID_MODE', default='openid-direct', description=_('Type of OpenID login'), choices=CUSTOM_OPENID_MODE_CHOICES ) ) settings.register( livesettings.ImageValue( LOGIN_PROVIDERS, 'SIGNIN_CUSTOM_OPENID_LOGIN_BUTTON', default='/images/logo.gif', description=_('Upload custom OpenID icon'), url_resolver=skin_utils.get_media_url ) ) settings.register( livesettings.StringValue( LOGIN_PROVIDERS, 'SIGNIN_CUSTOM_OPENID_ENDPOINT', default='http://example.com', description=_('Custom OpenID endpoint'), help_text=_('Important: with the "username" mode there must be a ' '%%(username)s placeholder e.g. ' 'http://example.com/%%(username)s/'), ) ) providers = ( 'local', 'AOL', 'Blogger', 'ClaimID', 'Facebook', 'Flickr', 'Google', 'Mozilla Persona', 'Twitter', 'LinkedIn', 'LiveJournal', #'myOpenID', 'OpenID', 'Technorati', 'Wordpress', 'Vidoop', 'Verisign', 'Yahoo', 'identi.ca', 'LaunchPad', ) DISABLED_BY_DEFAULT = ('LaunchPad', 'Mozilla Persona') NEED_EXTRA_SETUP = ('Twitter', 'Facebook', 'LinkedIn', 'identi.ca',) for provider in providers: if provider == 'local': provider_string = unicode(_('local password')) else: provider_string = provider kwargs = { 'description': _('Activate %(provider)s login') % {'provider': provider_string}, 'default': not (provider in DISABLED_BY_DEFAULT) } if provider in NEED_EXTRA_SETUP: kwargs['help_text'] = _( 'Note: to really enable %(provider)s login ' 'some additional parameters will need to be set ' 'in the "External keys" section' ) % {'provider': provider} setting_name = 'SIGNIN_%s_ENABLED' % provider.upper().replace(' ', '_') settings.register( livesettings.BooleanValue( LOGIN_PROVIDERS, setting_name, **kwargs ) )
gpl-3.0
nirmeshk/oh-mainline
vendor/packages/Pygments/pygments/styles/borland.py
364
1562
# -*- coding: utf-8 -*- """ pygments.styles.borland ~~~~~~~~~~~~~~~~~~~~~~~ Style similar to the style used in the Borland IDEs. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace class BorlandStyle(Style): """ Style similar to the style used in the borland IDEs. """ default_style = '' styles = { Whitespace: '#bbbbbb', Comment: 'italic #008800', Comment.Preproc: 'noitalic #008080', Comment.Special: 'noitalic bold', String: '#0000FF', String.Char: '#800080', Number: '#0000FF', Keyword: 'bold #000080', Operator.Word: 'bold', Name.Tag: 'bold #000080', Name.Attribute: '#FF0000', Generic.Heading: '#999999', Generic.Subheading: '#aaaaaa', Generic.Deleted: 'bg:#ffdddd #000000', Generic.Inserted: 'bg:#ddffdd #000000', Generic.Error: '#aa0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: '#555555', Generic.Output: '#888888', Generic.Traceback: '#aa0000', Error: 'bg:#e3d2d2 #a61717' }
agpl-3.0
themissingcow/inTheHood
python/InTheHood/Store.py
2
3622
# Copyright (c) 2011, Tom Cowland. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # * Neither the name Tom Cowland nor the names of any # other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### \todo Argument validation (a storage class should be able to assume all ### arguments are valid). import time class Store : def __init__( self, storageClassInstance ) : self.__store = storageClassInstance def validate( self ) : for m in ( "initialize", "registerStint", "removeStint", "stints", "contexts", "removeContext", "transactionBegin", "transactionEnd" ) : if not hasattr( self.__store, m ) : raise RuntimeError, "Specified storage back end '%s' does not "\ "implement the required method '%s'" % ( self.__store, m ) self.__store.initialize() return True def registerStint( self, stint ) : self.__store.registerStint( stint ) def removeStint( self, user, context ) : if context : self.__store.removeStint( user, context ) else : for c in self.contexts( user ) : self.__store.removeStint( user, c ) def stints( self, user=None ) : if user : stints = [] stints = self.__store.stints() for s in stints : if s.user == user : stints.append( s ) return stints else : return self.__store.stints() def contexts( self, user=None ) : if user : contexts = [] stints = self.__store.stints() for s in stints : if s.user == user : contexts.append( s.context ) return contexts else : return self.__store.contexts() def removeContext( self, context ) : self.__store.removeContext( context ) def transactionBegin( self, transactionId=None, lock=False ) : if not transactionId : transactionId = time.time() self.__lastTransaction = transactionId self.__store.transactionBegin( transactionId, lock ) def transactionEnd( self, transactionId=None ) : if not transactionId : transactionId = self.__lastTransaction if not transactionId : raise RuntimeError, "Unable to determine the last transaction ID" self.__store.transactionEnd( transactionId )
bsd-3-clause
michalliu/OpenWrt-Firefly-Libraries
staging_dir/target-mipsel_1004kc+dsp_uClibc-0.9.33.2/usr/lib/python2.7/test/test_textwrap.py
84
25554
# # Test suite for the textwrap module. # # Original tests written by Greg Ward <gward@python.net>. # Converted to PyUnit by Peter Hansen <peter@engcorp.com>. # Currently maintained by Greg Ward. # # $Id$ # import unittest from test import test_support from textwrap import TextWrapper, wrap, fill, dedent class BaseTestCase(unittest.TestCase): '''Parent class with utility methods for textwrap tests.''' def show(self, textin): if isinstance(textin, list): result = [] for i in range(len(textin)): result.append(" %d: %r" % (i, textin[i])) result = '\n'.join(result) elif isinstance(textin, basestring): result = " %s\n" % repr(textin) return result def check(self, result, expect): self.assertEqual(result, expect, 'expected:\n%s\nbut got:\n%s' % ( self.show(expect), self.show(result))) def check_wrap(self, text, width, expect, **kwargs): result = wrap(text, width, **kwargs) self.check(result, expect) def check_split(self, text, expect): result = self.wrapper._split(text) self.assertEqual(result, expect, "\nexpected %r\n" "but got %r" % (expect, result)) class WrapTestCase(BaseTestCase): def setUp(self): self.wrapper = TextWrapper(width=45) def test_simple(self): # Simple case: just words, spaces, and a bit of punctuation text = "Hello there, how are you this fine day? I'm glad to hear it!" self.check_wrap(text, 12, ["Hello there,", "how are you", "this fine", "day? I'm", "glad to hear", "it!"]) self.check_wrap(text, 42, ["Hello there, how are you this fine day?", "I'm glad to hear it!"]) self.check_wrap(text, 80, [text]) def test_empty_string(self): # Check that wrapping the empty string returns an empty list. self.check_wrap("", 6, []) self.check_wrap("", 6, [], drop_whitespace=False) def test_empty_string_with_initial_indent(self): # Check that the empty string is not indented. self.check_wrap("", 6, [], initial_indent="++") self.check_wrap("", 6, [], initial_indent="++", drop_whitespace=False) def test_whitespace(self): # Whitespace munging and end-of-sentence detection text = """\ This is a paragraph that already has line breaks. But some of its lines are much longer than the others, so it needs to be wrapped. Some lines are \ttabbed too. What a mess! """ expect = ["This is a paragraph that already has line", "breaks. But some of its lines are much", "longer than the others, so it needs to be", "wrapped. Some lines are tabbed too. What a", "mess!"] wrapper = TextWrapper(45, fix_sentence_endings=True) result = wrapper.wrap(text) self.check(result, expect) result = wrapper.fill(text) self.check(result, '\n'.join(expect)) def test_fix_sentence_endings(self): wrapper = TextWrapper(60, fix_sentence_endings=True) # SF #847346: ensure that fix_sentence_endings=True does the # right thing even on input short enough that it doesn't need to # be wrapped. text = "A short line. Note the single space." expect = ["A short line. Note the single space."] self.check(wrapper.wrap(text), expect) # Test some of the hairy end cases that _fix_sentence_endings() # is supposed to handle (the easy stuff is tested in # test_whitespace() above). text = "Well, Doctor? What do you think?" expect = ["Well, Doctor? What do you think?"] self.check(wrapper.wrap(text), expect) text = "Well, Doctor?\nWhat do you think?" self.check(wrapper.wrap(text), expect) text = 'I say, chaps! Anyone for "tennis?"\nHmmph!' expect = ['I say, chaps! Anyone for "tennis?" Hmmph!'] self.check(wrapper.wrap(text), expect) wrapper.width = 20 expect = ['I say, chaps!', 'Anyone for "tennis?"', 'Hmmph!'] self.check(wrapper.wrap(text), expect) text = 'And she said, "Go to hell!"\nCan you believe that?' expect = ['And she said, "Go to', 'hell!" Can you', 'believe that?'] self.check(wrapper.wrap(text), expect) wrapper.width = 60 expect = ['And she said, "Go to hell!" Can you believe that?'] self.check(wrapper.wrap(text), expect) text = 'File stdio.h is nice.' expect = ['File stdio.h is nice.'] self.check(wrapper.wrap(text), expect) def test_wrap_short(self): # Wrapping to make short lines longer text = "This is a\nshort paragraph." self.check_wrap(text, 20, ["This is a short", "paragraph."]) self.check_wrap(text, 40, ["This is a short paragraph."]) def test_wrap_short_1line(self): # Test endcases text = "This is a short line." self.check_wrap(text, 30, ["This is a short line."]) self.check_wrap(text, 30, ["(1) This is a short line."], initial_indent="(1) ") def test_hyphenated(self): # Test breaking hyphenated words text = ("this-is-a-useful-feature-for-" "reformatting-posts-from-tim-peters'ly") self.check_wrap(text, 40, ["this-is-a-useful-feature-for-", "reformatting-posts-from-tim-peters'ly"]) self.check_wrap(text, 41, ["this-is-a-useful-feature-for-", "reformatting-posts-from-tim-peters'ly"]) self.check_wrap(text, 42, ["this-is-a-useful-feature-for-reformatting-", "posts-from-tim-peters'ly"]) def test_hyphenated_numbers(self): # Test that hyphenated numbers (eg. dates) are not broken like words. text = ("Python 1.0.0 was released on 1994-01-26. Python 1.0.1 was\n" "released on 1994-02-15.") self.check_wrap(text, 35, ['Python 1.0.0 was released on', '1994-01-26. Python 1.0.1 was', 'released on 1994-02-15.']) self.check_wrap(text, 40, ['Python 1.0.0 was released on 1994-01-26.', 'Python 1.0.1 was released on 1994-02-15.']) text = "I do all my shopping at 7-11." self.check_wrap(text, 25, ["I do all my shopping at", "7-11."]) self.check_wrap(text, 27, ["I do all my shopping at", "7-11."]) self.check_wrap(text, 29, ["I do all my shopping at 7-11."]) def test_em_dash(self): # Test text with em-dashes text = "Em-dashes should be written -- thus." self.check_wrap(text, 25, ["Em-dashes should be", "written -- thus."]) # Probe the boundaries of the properly written em-dash, # ie. " -- ". self.check_wrap(text, 29, ["Em-dashes should be written", "-- thus."]) expect = ["Em-dashes should be written --", "thus."] self.check_wrap(text, 30, expect) self.check_wrap(text, 35, expect) self.check_wrap(text, 36, ["Em-dashes should be written -- thus."]) # The improperly written em-dash is handled too, because # it's adjacent to non-whitespace on both sides. text = "You can also do--this or even---this." expect = ["You can also do", "--this or even", "---this."] self.check_wrap(text, 15, expect) self.check_wrap(text, 16, expect) expect = ["You can also do--", "this or even---", "this."] self.check_wrap(text, 17, expect) self.check_wrap(text, 19, expect) expect = ["You can also do--this or even", "---this."] self.check_wrap(text, 29, expect) self.check_wrap(text, 31, expect) expect = ["You can also do--this or even---", "this."] self.check_wrap(text, 32, expect) self.check_wrap(text, 35, expect) # All of the above behaviour could be deduced by probing the # _split() method. text = "Here's an -- em-dash and--here's another---and another!" expect = ["Here's", " ", "an", " ", "--", " ", "em-", "dash", " ", "and", "--", "here's", " ", "another", "---", "and", " ", "another!"] self.check_split(text, expect) text = "and then--bam!--he was gone" expect = ["and", " ", "then", "--", "bam!", "--", "he", " ", "was", " ", "gone"] self.check_split(text, expect) def test_unix_options (self): # Test that Unix-style command-line options are wrapped correctly. # Both Optik (OptionParser) and Docutils rely on this behaviour! text = "You should use the -n option, or --dry-run in its long form." self.check_wrap(text, 20, ["You should use the", "-n option, or --dry-", "run in its long", "form."]) self.check_wrap(text, 21, ["You should use the -n", "option, or --dry-run", "in its long form."]) expect = ["You should use the -n option, or", "--dry-run in its long form."] self.check_wrap(text, 32, expect) self.check_wrap(text, 34, expect) self.check_wrap(text, 35, expect) self.check_wrap(text, 38, expect) expect = ["You should use the -n option, or --dry-", "run in its long form."] self.check_wrap(text, 39, expect) self.check_wrap(text, 41, expect) expect = ["You should use the -n option, or --dry-run", "in its long form."] self.check_wrap(text, 42, expect) # Again, all of the above can be deduced from _split(). text = "the -n option, or --dry-run or --dryrun" expect = ["the", " ", "-n", " ", "option,", " ", "or", " ", "--dry-", "run", " ", "or", " ", "--dryrun"] self.check_split(text, expect) def test_funky_hyphens (self): # Screwy edge cases cooked up by David Goodger. All reported # in SF bug #596434. self.check_split("what the--hey!", ["what", " ", "the", "--", "hey!"]) self.check_split("what the--", ["what", " ", "the--"]) self.check_split("what the--.", ["what", " ", "the--."]) self.check_split("--text--.", ["--text--."]) # When I first read bug #596434, this is what I thought David # was talking about. I was wrong; these have always worked # fine. The real problem is tested in test_funky_parens() # below... self.check_split("--option", ["--option"]) self.check_split("--option-opt", ["--option-", "opt"]) self.check_split("foo --option-opt bar", ["foo", " ", "--option-", "opt", " ", "bar"]) def test_punct_hyphens(self): # Oh bother, SF #965425 found another problem with hyphens -- # hyphenated words in single quotes weren't handled correctly. # In fact, the bug is that *any* punctuation around a hyphenated # word was handled incorrectly, except for a leading "--", which # was special-cased for Optik and Docutils. So test a variety # of styles of punctuation around a hyphenated word. # (Actually this is based on an Optik bug report, #813077). self.check_split("the 'wibble-wobble' widget", ['the', ' ', "'wibble-", "wobble'", ' ', 'widget']) self.check_split('the "wibble-wobble" widget', ['the', ' ', '"wibble-', 'wobble"', ' ', 'widget']) self.check_split("the (wibble-wobble) widget", ['the', ' ', "(wibble-", "wobble)", ' ', 'widget']) self.check_split("the ['wibble-wobble'] widget", ['the', ' ', "['wibble-", "wobble']", ' ', 'widget']) def test_funky_parens (self): # Second part of SF bug #596434: long option strings inside # parentheses. self.check_split("foo (--option) bar", ["foo", " ", "(--option)", " ", "bar"]) # Related stuff -- make sure parens work in simpler contexts. self.check_split("foo (bar) baz", ["foo", " ", "(bar)", " ", "baz"]) self.check_split("blah (ding dong), wubba", ["blah", " ", "(ding", " ", "dong),", " ", "wubba"]) def test_drop_whitespace_false(self): # Check that drop_whitespace=False preserves whitespace. # SF patch #1581073 text = " This is a sentence with much whitespace." self.check_wrap(text, 10, [" This is a", " ", "sentence ", "with ", "much white", "space."], drop_whitespace=False) def test_drop_whitespace_false_whitespace_only(self): # Check that drop_whitespace=False preserves a whitespace-only string. self.check_wrap(" ", 6, [" "], drop_whitespace=False) def test_drop_whitespace_false_whitespace_only_with_indent(self): # Check that a whitespace-only string gets indented (when # drop_whitespace is False). self.check_wrap(" ", 6, [" "], drop_whitespace=False, initial_indent=" ") def test_drop_whitespace_whitespace_only(self): # Check drop_whitespace on a whitespace-only string. self.check_wrap(" ", 6, []) def test_drop_whitespace_leading_whitespace(self): # Check that drop_whitespace does not drop leading whitespace (if # followed by non-whitespace). # SF bug #622849 reported inconsistent handling of leading # whitespace; let's test that a bit, shall we? text = " This is a sentence with leading whitespace." self.check_wrap(text, 50, [" This is a sentence with leading whitespace."]) self.check_wrap(text, 30, [" This is a sentence with", "leading whitespace."]) def test_drop_whitespace_whitespace_line(self): # Check that drop_whitespace skips the whole line if a non-leading # line consists only of whitespace. text = "abcd efgh" # Include the result for drop_whitespace=False for comparison. self.check_wrap(text, 6, ["abcd", " ", "efgh"], drop_whitespace=False) self.check_wrap(text, 6, ["abcd", "efgh"]) def test_drop_whitespace_whitespace_only_with_indent(self): # Check that initial_indent is not applied to a whitespace-only # string. This checks a special case of the fact that dropping # whitespace occurs before indenting. self.check_wrap(" ", 6, [], initial_indent="++") def test_drop_whitespace_whitespace_indent(self): # Check that drop_whitespace does not drop whitespace indents. # This checks a special case of the fact that dropping whitespace # occurs before indenting. self.check_wrap("abcd efgh", 6, [" abcd", " efgh"], initial_indent=" ", subsequent_indent=" ") if test_support.have_unicode: def test_unicode(self): # *Very* simple test of wrapping Unicode strings. I'm sure # there's more to it than this, but let's at least make # sure textwrap doesn't crash on Unicode input! text = u"Hello there, how are you today?" self.check_wrap(text, 50, [u"Hello there, how are you today?"]) self.check_wrap(text, 20, [u"Hello there, how are", "you today?"]) olines = self.wrapper.wrap(text) self.assertIsInstance(olines, list) self.assertIsInstance(olines[0], unicode) otext = self.wrapper.fill(text) self.assertIsInstance(otext, unicode) def test_no_split_at_umlaut(self): text = u"Die Empf\xe4nger-Auswahl" self.check_wrap(text, 13, [u"Die", u"Empf\xe4nger-", u"Auswahl"]) def test_umlaut_followed_by_dash(self): text = u"aa \xe4\xe4-\xe4\xe4" self.check_wrap(text, 7, [u"aa \xe4\xe4-", u"\xe4\xe4"]) def test_split(self): # Ensure that the standard _split() method works as advertised # in the comments text = "Hello there -- you goof-ball, use the -b option!" result = self.wrapper._split(text) self.check(result, ["Hello", " ", "there", " ", "--", " ", "you", " ", "goof-", "ball,", " ", "use", " ", "the", " ", "-b", " ", "option!"]) def test_break_on_hyphens(self): # Ensure that the break_on_hyphens attributes work text = "yaba daba-doo" self.check_wrap(text, 10, ["yaba daba-", "doo"], break_on_hyphens=True) self.check_wrap(text, 10, ["yaba", "daba-doo"], break_on_hyphens=False) def test_bad_width(self): # Ensure that width <= 0 is caught. text = "Whatever, it doesn't matter." self.assertRaises(ValueError, wrap, text, 0) self.assertRaises(ValueError, wrap, text, -1) class LongWordTestCase (BaseTestCase): def setUp(self): self.wrapper = TextWrapper() self.text = '''\ Did you say "supercalifragilisticexpialidocious?" How *do* you spell that odd word, anyways? ''' def test_break_long(self): # Wrap text with long words and lots of punctuation self.check_wrap(self.text, 30, ['Did you say "supercalifragilis', 'ticexpialidocious?" How *do*', 'you spell that odd word,', 'anyways?']) self.check_wrap(self.text, 50, ['Did you say "supercalifragilisticexpialidocious?"', 'How *do* you spell that odd word, anyways?']) # SF bug 797650. Prevent an infinite loop by making sure that at # least one character gets split off on every pass. self.check_wrap('-'*10+'hello', 10, ['----------', ' h', ' e', ' l', ' l', ' o'], subsequent_indent = ' '*15) # bug 1146. Prevent a long word to be wrongly wrapped when the # preceding word is exactly one character shorter than the width self.check_wrap(self.text, 12, ['Did you say ', '"supercalifr', 'agilisticexp', 'ialidocious?', '" How *do*', 'you spell', 'that odd', 'word,', 'anyways?']) def test_nobreak_long(self): # Test with break_long_words disabled self.wrapper.break_long_words = 0 self.wrapper.width = 30 expect = ['Did you say', '"supercalifragilisticexpialidocious?"', 'How *do* you spell that odd', 'word, anyways?' ] result = self.wrapper.wrap(self.text) self.check(result, expect) # Same thing with kwargs passed to standalone wrap() function. result = wrap(self.text, width=30, break_long_words=0) self.check(result, expect) class IndentTestCases(BaseTestCase): # called before each test method def setUp(self): self.text = '''\ This paragraph will be filled, first without any indentation, and then with some (including a hanging indent).''' def test_fill(self): # Test the fill() method expect = '''\ This paragraph will be filled, first without any indentation, and then with some (including a hanging indent).''' result = fill(self.text, 40) self.check(result, expect) def test_initial_indent(self): # Test initial_indent parameter expect = [" This paragraph will be filled,", "first without any indentation, and then", "with some (including a hanging indent)."] result = wrap(self.text, 40, initial_indent=" ") self.check(result, expect) expect = "\n".join(expect) result = fill(self.text, 40, initial_indent=" ") self.check(result, expect) def test_subsequent_indent(self): # Test subsequent_indent parameter expect = '''\ * This paragraph will be filled, first without any indentation, and then with some (including a hanging indent).''' result = fill(self.text, 40, initial_indent=" * ", subsequent_indent=" ") self.check(result, expect) # Despite the similar names, DedentTestCase is *not* the inverse # of IndentTestCase! class DedentTestCase(unittest.TestCase): def assertUnchanged(self, text): """assert that dedent() has no effect on 'text'""" self.assertEqual(text, dedent(text)) def test_dedent_nomargin(self): # No lines indented. text = "Hello there.\nHow are you?\nOh good, I'm glad." self.assertUnchanged(text) # Similar, with a blank line. text = "Hello there.\n\nBoo!" self.assertUnchanged(text) # Some lines indented, but overall margin is still zero. text = "Hello there.\n This is indented." self.assertUnchanged(text) # Again, add a blank line. text = "Hello there.\n\n Boo!\n" self.assertUnchanged(text) def test_dedent_even(self): # All lines indented by two spaces. text = " Hello there.\n How are ya?\n Oh good." expect = "Hello there.\nHow are ya?\nOh good." self.assertEqual(expect, dedent(text)) # Same, with blank lines. text = " Hello there.\n\n How are ya?\n Oh good.\n" expect = "Hello there.\n\nHow are ya?\nOh good.\n" self.assertEqual(expect, dedent(text)) # Now indent one of the blank lines. text = " Hello there.\n \n How are ya?\n Oh good.\n" expect = "Hello there.\n\nHow are ya?\nOh good.\n" self.assertEqual(expect, dedent(text)) def test_dedent_uneven(self): # Lines indented unevenly. text = '''\ def foo(): while 1: return foo ''' expect = '''\ def foo(): while 1: return foo ''' self.assertEqual(expect, dedent(text)) # Uneven indentation with a blank line. text = " Foo\n Bar\n\n Baz\n" expect = "Foo\n Bar\n\n Baz\n" self.assertEqual(expect, dedent(text)) # Uneven indentation with a whitespace-only line. text = " Foo\n Bar\n \n Baz\n" expect = "Foo\n Bar\n\n Baz\n" self.assertEqual(expect, dedent(text)) # dedent() should not mangle internal tabs def test_dedent_preserve_internal_tabs(self): text = " hello\tthere\n how are\tyou?" expect = "hello\tthere\nhow are\tyou?" self.assertEqual(expect, dedent(text)) # make sure that it preserves tabs when it's not making any # changes at all self.assertEqual(expect, dedent(expect)) # dedent() should not mangle tabs in the margin (i.e. # tabs and spaces both count as margin, but are *not* # considered equivalent) def test_dedent_preserve_margin_tabs(self): text = " hello there\n\thow are you?" self.assertUnchanged(text) # same effect even if we have 8 spaces text = " hello there\n\thow are you?" self.assertUnchanged(text) # dedent() only removes whitespace that can be uniformly removed! text = "\thello there\n\thow are you?" expect = "hello there\nhow are you?" self.assertEqual(expect, dedent(text)) text = " \thello there\n \thow are you?" self.assertEqual(expect, dedent(text)) text = " \t hello there\n \t how are you?" self.assertEqual(expect, dedent(text)) text = " \thello there\n \t how are you?" expect = "hello there\n how are you?" self.assertEqual(expect, dedent(text)) def test_main(): test_support.run_unittest(WrapTestCase, LongWordTestCase, IndentTestCases, DedentTestCase) if __name__ == '__main__': test_main()
gpl-2.0
kimimj/scrapy
scrapy/spidermiddlewares/depth.py
88
2051
""" Depth Spider Middleware See documentation in docs/topics/spider-middleware.rst """ import logging from scrapy.http import Request logger = logging.getLogger(__name__) class DepthMiddleware(object): def __init__(self, maxdepth, stats=None, verbose_stats=False, prio=1): self.maxdepth = maxdepth self.stats = stats self.verbose_stats = verbose_stats self.prio = prio @classmethod def from_crawler(cls, crawler): settings = crawler.settings maxdepth = settings.getint('DEPTH_LIMIT') verbose = settings.getbool('DEPTH_STATS_VERBOSE') prio = settings.getint('DEPTH_PRIORITY') return cls(maxdepth, crawler.stats, verbose, prio) def process_spider_output(self, response, result, spider): def _filter(request): if isinstance(request, Request): depth = response.meta['depth'] + 1 request.meta['depth'] = depth if self.prio: request.priority -= depth * self.prio if self.maxdepth and depth > self.maxdepth: logger.debug( "Ignoring link (depth > %(maxdepth)d): %(requrl)s ", {'maxdepth': self.maxdepth, 'requrl': request.url}, extra={'spider': spider} ) return False elif self.stats: if self.verbose_stats: self.stats.inc_value('request_depth_count/%s' % depth, spider=spider) self.stats.max_value('request_depth_max', depth, spider=spider) return True # base case (depth=0) if self.stats and 'depth' not in response.meta: response.meta['depth'] = 0 if self.verbose_stats: self.stats.inc_value('request_depth_count/0', spider=spider) return (r for r in result or () if _filter(r))
bsd-3-clause
srvelivela/ansibledoc
lib/ansible/module_utils/ec2.py
12
9146
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # Copyright (c), Michael DeHaan <michael.dehaan@gmail.com>, 2012-2013 # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os try: import boto3 HAS_BOTO3 = True except: HAS_BOTO3 = False try: from distutils.version import LooseVersion HAS_LOOSE_VERSION = True except: HAS_LOOSE_VERSION = False def boto3_conn(module, conn_type=None, resource=None, region=None, endpoint=None, **params): if conn_type not in ['both', 'resource', 'client']: module.fail_json(msg='There is an issue in the code of the module. You must specify either both, resource or client to the conn_type parameter in the boto3_conn function call') if conn_type == 'resource': resource = boto3.session.Session().resource(resource, region_name=region, endpoint_url=endpoint, **params) return resource elif conn_type == 'client': client = boto3.session.Session().client(resource, region_name=region, endpoint_url=endpoint, **params) return client else: resource = boto3.session.Session().resource(resource, region_name=region, endpoint_url=endpoint, **params) client = boto3.session.Session().client(resource, region_name=region, endpoint_url=endpoint, **params) return client, resource def aws_common_argument_spec(): return dict( ec2_url=dict(), aws_secret_key=dict(aliases=['ec2_secret_key', 'secret_key'], no_log=True), aws_access_key=dict(aliases=['ec2_access_key', 'access_key']), validate_certs=dict(default=True, type='bool'), security_token=dict(aliases=['access_token'], no_log=True), profile=dict(), ) def ec2_argument_spec(): spec = aws_common_argument_spec() spec.update( dict( region=dict(aliases=['aws_region', 'ec2_region']), ) ) return spec def boto_supports_profile_name(): return hasattr(boto.ec2.EC2Connection, 'profile_name') def get_aws_connection_info(module, boto3=False): # Check module args for credentials, then check environment vars # access_key ec2_url = module.params.get('ec2_url') access_key = module.params.get('aws_access_key') secret_key = module.params.get('aws_secret_key') security_token = module.params.get('security_token') region = module.params.get('region') profile_name = module.params.get('profile') validate_certs = module.params.get('validate_certs') if not ec2_url: if 'AWS_URL' in os.environ: ec2_url = os.environ['AWS_URL'] elif 'EC2_URL' in os.environ: ec2_url = os.environ['EC2_URL'] if not access_key: if 'AWS_ACCESS_KEY_ID' in os.environ: access_key = os.environ['AWS_ACCESS_KEY_ID'] elif 'AWS_ACCESS_KEY' in os.environ: access_key = os.environ['AWS_ACCESS_KEY'] elif 'EC2_ACCESS_KEY' in os.environ: access_key = os.environ['EC2_ACCESS_KEY'] else: # in case access_key came in as empty string access_key = None if not secret_key: if 'AWS_SECRET_ACCESS_KEY' in os.environ: secret_key = os.environ['AWS_SECRET_ACCESS_KEY'] elif 'AWS_SECRET_KEY' in os.environ: secret_key = os.environ['AWS_SECRET_KEY'] elif 'EC2_SECRET_KEY' in os.environ: secret_key = os.environ['EC2_SECRET_KEY'] else: # in case secret_key came in as empty string secret_key = None if not region: if 'AWS_REGION' in os.environ: region = os.environ['AWS_REGION'] elif 'AWS_DEFAULT_REGION' in os.environ: region = os.environ['AWS_DEFAULT_REGION'] elif 'EC2_REGION' in os.environ: region = os.environ['EC2_REGION'] else: # boto.config.get returns None if config not found region = boto.config.get('Boto', 'aws_region') if not region: region = boto.config.get('Boto', 'ec2_region') if not security_token: if 'AWS_SECURITY_TOKEN' in os.environ: security_token = os.environ['AWS_SECURITY_TOKEN'] elif 'EC2_SECURITY_TOKEN' in os.environ: security_token = os.environ['EC2_SECURITY_TOKEN'] else: # in case security_token came in as empty string security_token = None if HAS_BOTO3 and boto3: boto_params = dict(aws_access_key_id=access_key, aws_secret_access_key=secret_key, aws_session_token=security_token) if validate_certs: boto_params['verify'] = validate_certs if profile_name: boto_params['profile_name'] = profile_name else: boto_params = dict(aws_access_key_id=access_key, aws_secret_access_key=secret_key, security_token=security_token) # profile_name only works as a key in boto >= 2.24 # so only set profile_name if passed as an argument if profile_name: if not boto_supports_profile_name(): module.fail_json("boto does not support profile_name before 2.24") boto_params['profile_name'] = profile_name if validate_certs and HAS_LOOSE_VERSION and LooseVersion(boto.Version) >= LooseVersion("2.6.0"): boto_params['validate_certs'] = validate_certs return region, ec2_url, boto_params def get_ec2_creds(module): ''' for compatibility mode with old modules that don't/can't yet use ec2_connect method ''' region, ec2_url, boto_params = get_aws_connection_info(module) return ec2_url, boto_params['aws_access_key_id'], boto_params['aws_secret_access_key'], region def boto_fix_security_token_in_profile(conn, profile_name): ''' monkey patch for boto issue boto/boto#2100 ''' profile = 'profile ' + profile_name if boto.config.has_option(profile, 'aws_security_token'): conn.provider.set_security_token(boto.config.get(profile, 'aws_security_token')) return conn def connect_to_aws(aws_module, region, **params): conn = aws_module.connect_to_region(region, **params) if not conn: if region not in [aws_module_region.name for aws_module_region in aws_module.regions()]: raise StandardError("Region %s does not seem to be available for aws module %s. If the region definitely exists, you may need to upgrade boto or extend with endpoints_path" % (region, aws_module.__name__)) else: raise StandardError("Unknown problem connecting to region %s for aws module %s." % (region, aws_module.__name__)) if params.get('profile_name'): conn = boto_fix_security_token_in_profile(conn, params['profile_name']) return conn def ec2_connect(module): """ Return an ec2 connection""" region, ec2_url, boto_params = get_aws_connection_info(module) # If we have a region specified, connect to its endpoint. if region: try: ec2 = connect_to_aws(boto.ec2, region, **boto_params) except (boto.exception.NoAuthHandlerFound, StandardError), e: module.fail_json(msg=str(e)) # Otherwise, no region so we fallback to the old connection method elif ec2_url: try: ec2 = boto.connect_ec2_endpoint(ec2_url, **boto_params) except (boto.exception.NoAuthHandlerFound, StandardError), e: module.fail_json(msg=str(e)) else: module.fail_json(msg="Either region or ec2_url must be specified") return ec2
gpl-3.0
tuxfux-hlp-notes/python-batches
archieves/batch-62/modules/mysheets/lib/python2.7/site-packages/pip/_vendor/html5lib/treewalkers/__init__.py
1229
2323
"""A collection of modules for iterating through different kinds of tree, generating tokens identical to those produced by the tokenizer module. To create a tree walker for a new type of tree, you need to do implement a tree walker object (called TreeWalker by convention) that implements a 'serialize' method taking a tree as sole argument and returning an iterator generating tokens. """ from __future__ import absolute_import, division, unicode_literals import sys from ..utils import default_etree treeWalkerCache = {} def getTreeWalker(treeType, implementation=None, **kwargs): """Get a TreeWalker class for various types of tree with built-in support treeType - the name of the tree type required (case-insensitive). Supported values are: "dom" - The xml.dom.minidom DOM implementation "pulldom" - The xml.dom.pulldom event stream "etree" - A generic walker for tree implementations exposing an elementtree-like interface (known to work with ElementTree, cElementTree and lxml.etree). "lxml" - Optimized walker for lxml.etree "genshi" - a Genshi stream implementation - (Currently applies to the "etree" tree type only). A module implementing the tree type e.g. xml.etree.ElementTree or cElementTree.""" treeType = treeType.lower() if treeType not in treeWalkerCache: if treeType in ("dom", "pulldom"): name = "%s.%s" % (__name__, treeType) __import__(name) mod = sys.modules[name] treeWalkerCache[treeType] = mod.TreeWalker elif treeType == "genshi": from . import genshistream treeWalkerCache[treeType] = genshistream.TreeWalker elif treeType == "lxml": from . import lxmletree treeWalkerCache[treeType] = lxmletree.TreeWalker elif treeType == "etree": from . import etree if implementation is None: implementation = default_etree # XXX: NEVER cache here, caching is done in the etree submodule return etree.getETreeModule(implementation, **kwargs).TreeWalker return treeWalkerCache.get(treeType)
gpl-3.0
pzankov/hydroctrl
water_tank.py
1
3485
#!/usr/bin/env python3 from adc import ADS1115, ADCFilter from settings import UR, SUPPLY_TANK_CONFIG class LinearInterpolation: """ Interpolate a 1-D function. `x` and `y` are arrays of values used to approximate some function f: ``y = f(x)``. """ def __init__(self, x, y): if len(x) != len(y): raise Exception('Arrays must have the same number of elements') if len(x) < 2: raise Exception('At least two points are required') self.x = x self.y = y def __call__(self, x_new): distances = [abs(v - x_new) for v in self.x] indexes = list(range(len(distances))) indexes.sort(key=distances.__getitem__) i1 = indexes[0] i2 = indexes[1] x1 = self.x[i1] x2 = self.x[i2] y1 = self.y[i1] y2 = self.y[i2] y_new = y1 + (x_new - x1) / (x2 - x1) * (y2 - y1) # Pint forgets to convert Quantity with uncertainty into Measurement if type(y_new) == UR.Quantity: y_new = UR.Measurement(y_new.magnitude.nominal_value, y_new.magnitude.std_dev, y_new.units) return y_new class PressureSensorCalibration: """ MP3V5050DP pressure sensor calibration. """ # Sensitivity is constant (see Datasheet) sensitivity = 54 * UR.mV / UR.kPa def __init__(self, pressure_offset): self.pressure_offset = pressure_offset def compute_pressure(self, voltage): return voltage / self.sensitivity - self.pressure_offset class PressureSensorInterface: """ Complete MP3V5050DP pressure sensor interface with calibration. """ def __init__(self, config): adc_sps = config['adc']['sps'] adc = ADS1115( i2c_busn=config['adc']['i2c_busn'], i2c_addr=config['adc']['i2c_addr']) adc.config( channel=config['adc']['channel'], fsr=config['adc']['fsr'], sps=adc_sps) self.adc = ADCFilter( adc=adc, samples_count=adc_sps) self.calibration = PressureSensorCalibration( pressure_offset=config['calibration']['pressure_offset']) def get_pressure_and_voltage(self): voltage = self.adc.get_voltage() pressure = self.calibration.compute_pressure(voltage) return pressure, voltage def get_pressure(self): return self.get_pressure_and_voltage()[0] class WaterTankInterface: """ Complete water tank interface with calibration. """ def __init__(self, config): points = config['calibration']['points'] self.calibration = LinearInterpolation( x=[p['pressure'] for p in points], y=[p['volume'] for p in points]) self.sensor = PressureSensorInterface(config) def get_volume_and_pressure_and_voltage(self): pressure, voltage = self.sensor.get_pressure_and_voltage() volume = self.calibration(pressure) return volume, pressure, voltage def get_volume(self): return self.get_volume_and_pressure_and_voltage()[0] def main(): tank = WaterTankInterface(SUPPLY_TANK_CONFIG) while True: try: volume, pressure, voltage = tank.get_volume_and_pressure_and_voltage() print('{:~.1fP} {:~.1fP} {:~.1fP}'.format(voltage.to('mV'), pressure.to('cmH2O'), volume.to('L'))) except Exception as e: print(e) if __name__ == '__main__': main()
mit
bchareyre/ratchet
examples/test/paraview-spheres-solid-section/pv_section.py
6
31536
try: paraview.simple except: from paraview.simple import * paraview.simple._DisableFirstRenderCameraReset() RenderView1 = CreateRenderView() RenderView1.LightSpecularColor = [1.0, 1.0, 1.0] RenderView1.KeyLightAzimuth = 10.0 RenderView1.UseTexturedBackground = 0 RenderView1.UseLight = 1 RenderView1.CameraPosition = [-10.901121443539559, -17.271355476388358, 4.309974877565033] RenderView1.FillLightKFRatio = 3.0 RenderView1.Background2 = [0.0, 0.0, 0.165] RenderView1.FillLightAzimuth = -10.0 RenderView1.LODResolution = 50.0 RenderView1.BackgroundTexture = [] RenderView1.InteractionMode = '3D' RenderView1.StencilCapable = 1 RenderView1.LightIntensity = 1.0 RenderView1.CameraFocalPoint = [4.732498500000004, 5.045734999999994, 4.874767500000023] RenderView1.ImageReductionFactor = 2 RenderView1.CameraViewAngle = 30.0 RenderView1.CameraParallelScale = 7.0538593576100945 RenderView1.EyeAngle = 2.0 RenderView1.HeadLightKHRatio = 3.0 RenderView1.StereoRender = 0 RenderView1.KeyLightIntensity = 0.75 RenderView1.BackLightAzimuth = 110.0 RenderView1.OrientationAxesInteractivity = 0 RenderView1.UseInteractiveRenderingForSceenshots = 0 RenderView1.UseOffscreenRendering = 0 RenderView1.Background = [1.0, 1.0, 1.0] RenderView1.UseOffscreenRenderingForScreenshots = 0 RenderView1.NonInteractiveRenderDelay = 2 RenderView1.CenterOfRotation = [4.7324985, 5.045735, 4.8747675] RenderView1.CameraParallelProjection = 0 RenderView1.CompressorConfig = 'vtkSquirtCompressor 0 3' RenderView1.HeadLightWarmth = 0.5 RenderView1.MaximumNumberOfPeels = 4 RenderView1.LightDiffuseColor = [1.0, 1.0, 1.0] RenderView1.StereoType = 'Red-Blue' RenderView1.DepthPeeling = 1 RenderView1.BackLightKBRatio = 3.5 RenderView1.StereoCapableWindow = 1 RenderView1.CameraViewUp = [-0.818931483577863, 0.5738512869077476, -0.006776851723502143] RenderView1.LightType = 'HeadLight' RenderView1.LightAmbientColor = [1.0, 1.0, 1.0] RenderView1.RemoteRenderThreshold = 3.0 RenderView1.CacheKey = 0.0 RenderView1.UseCache = 0 RenderView1.KeyLightElevation = 50.0 RenderView1.CenterAxesVisibility = 0 RenderView1.MaintainLuminance = 0 RenderView1.StillRenderImageReductionFactor = 1 RenderView1.BackLightWarmth = 0.5 RenderView1.FillLightElevation = -75.0 RenderView1.MultiSamples = 0 RenderView1.FillLightWarmth = 0.4 RenderView1.AlphaBitPlanes = 1 RenderView1.LightSwitch = 0 RenderView1.OrientationAxesVisibility = 0 RenderView1.CameraClippingRange = [14.893135346284218, 43.89470107765568] RenderView1.BackLightElevation = 0.0 RenderView1.ViewTime = 0.0 RenderView1.OrientationAxesOutlineColor = [1.0, 1.0, 1.0] RenderView1.LODThreshold = 5.0 RenderView1.CollectGeometryThreshold = 100.0 RenderView1.UseGradientBackground = 0 RenderView1.KeyLightWarmth = 0.6 RenderView1.OrientationAxesLabelColor = [1.0, 1.0, 1.0] test_vtk = LegacyVTKReader( guiName="test.vtk", FileNames=['/tmp/test.vtk'] ) Glyph1 = Glyph( guiName="Glyph1", RandomMode=1, GlyphTransform="Transform2", GlyphType="Sphere", MaximumNumberofPoints=5000, ScaleMode='scalar', MaskPoints=0, Vectors=['POINTS', ''], SetScaleFactor=1.0, Scalars=['POINTS', 'radius'], Orient=1 ) Glyph1.GlyphType.StartTheta = 0.0 Glyph1.GlyphType.ThetaResolution = 12 Glyph1.GlyphTransform.Rotate = [0.0, 0.0, 0.0] Glyph1.GlyphTransform.Translate = [0.0, 0.0, 0.0] Glyph1.GlyphType.PhiResolution = 12 Glyph1.GlyphType.EndTheta = 360.0 Glyph1.GlyphType.EndPhi = 180.0 Glyph1.GlyphType.Center = [0.0, 0.0, 0.0] Glyph1.GlyphType.Radius = 1.0 Glyph1.GlyphTransform.Scale = [1.0, 1.0, 1.0] Glyph1.GlyphType.StartPhi = 0.0 Clip2 = Clip( guiName="Clip2", InsideOut=0, UseValueAsOffset=0, Scalars=['POINTS', 'radius'], Value=0.0, ClipType="Plane" ) Clip2.ClipType.Normal = [1.0, 1.0, 1.0] Clip2.ClipType.Origin = [5.0, 5.0, 5.0] Clip2.ClipType.Offset = 0.0 testSection_vtk = LegacyVTKReader( guiName="testSection.vtk", FileNames=['/tmp/testSection.vtk'] ) Glyph3 = Glyph( guiName="Glyph3", ScaleMode='scalar', GlyphType="Cylinder", MaskPoints=0, RandomMode=1, Vectors=['POINTS', 'normal'], GlyphTransform="Transform2", Scalars=['POINTS', 'radius'], MaximumNumberofPoints=5000, SetScaleFactor=1.0, Orient=1 ) Glyph3.GlyphType.Capping = 1 Glyph3.GlyphType.Height = 0.01 Glyph3.GlyphTransform.Rotate = [0.0, 0.0, -90.0] Glyph3.GlyphType.Radius = 1.0 Glyph3.GlyphTransform.Translate = [0.0, 0.0, 0.0] Glyph3.GlyphType.Center = [0.0, 0.0, 0.0] Glyph3.GlyphType.Resolution = 18 Glyph3.GlyphTransform.Scale = [1.0, 1.0, 1.0] a1_radius_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] ) a1_radiusOrig_PiecewiseFunction = CreatePiecewiseFunction( Points=[0.0, 0.0, 0.5, 0.0, 1.0, 1.0, 0.5, 0.0] ) a1_radius_PVLookupTable = GetLookupTableForArray( "radius", 1, Discretize=1, RGBPoints=[0.522954, 0.0, 0.0, 1.0, 1.42914, 1.0, 0.0, 0.0], UseLogScale=0, VectorComponent=0, NanColor=[0.498039, 0.498039, 0.498039], NumberOfTableValues=256, ColorSpace='HSV', VectorMode='Magnitude', HSVWrap=0, ScalarRangeInitialized=1.0, LockScalarRange=1 ) a1_radiusOrig_PVLookupTable = GetLookupTableForArray( "radiusOrig", 1, Discretize=1, RGBPoints=[0.54491, 0.0, 0.0, 1.0, 1.41118, 1.0, 0.0, 0.0], UseLogScale=0, VectorComponent=0, NanColor=[0.498039, 0.498039, 0.498039], NumberOfTableValues=256, ColorSpace='HSV', VectorMode='Magnitude', HSVWrap=0, ScalarRangeInitialized=1.0, LockScalarRange=1 ) SetActiveSource(test_vtk) DataRepresentation1 = Show() DataRepresentation1.CubeAxesZAxisVisibility = 1 DataRepresentation1.SelectionPointLabelColor = [0.5, 0.5, 0.5] DataRepresentation1.SelectionPointFieldDataArrayName = 'radius' DataRepresentation1.SuppressLOD = 0 DataRepresentation1.CubeAxesXGridLines = 0 DataRepresentation1.CubeAxesYAxisTickVisibility = 1 DataRepresentation1.CubeAxesColor = [1.0, 1.0, 1.0] DataRepresentation1.Position = [0.0, 0.0, 0.0] DataRepresentation1.BackfaceRepresentation = 'Follow Frontface' DataRepresentation1.SelectionOpacity = 1.0 DataRepresentation1.SelectionPointLabelShadow = 0 DataRepresentation1.CubeAxesYGridLines = 0 DataRepresentation1.CubeAxesZAxisRange = [0.0, 1.0] DataRepresentation1.OrientationMode = 'Direction' DataRepresentation1.Source.TipResolution = 6 DataRepresentation1.ScaleMode = 'No Data Scaling Off' DataRepresentation1.Diffuse = 1.0 DataRepresentation1.SelectionUseOutline = 0 DataRepresentation1.CubeAxesZTitle = 'Z-Axis' DataRepresentation1.Specular = 0.1 DataRepresentation1.SelectionVisibility = 1 DataRepresentation1.InterpolateScalarsBeforeMapping = 1 DataRepresentation1.CubeAxesZAxisTickVisibility = 1 DataRepresentation1.Origin = [0.0, 0.0, 0.0] DataRepresentation1.CubeAxesVisibility = 0 DataRepresentation1.Scale = [1.0, 1.0, 1.0] DataRepresentation1.SelectionCellLabelJustification = 'Left' DataRepresentation1.DiffuseColor = [1.0, 1.0, 1.0] DataRepresentation1.SelectionCellLabelOpacity = 1.0 DataRepresentation1.Source = "Arrow" DataRepresentation1.Source.Invert = 0 DataRepresentation1.Masking = 0 DataRepresentation1.Opacity = 1.0 DataRepresentation1.LineWidth = 1.0 DataRepresentation1.MeshVisibility = 0 DataRepresentation1.Visibility = 1 DataRepresentation1.SelectionCellLabelFontSize = 18 DataRepresentation1.CubeAxesCornerOffset = 0.0 DataRepresentation1.SelectionPointLabelJustification = 'Left' DataRepresentation1.SelectionPointLabelVisibility = 0 DataRepresentation1.SelectOrientationVectors = '' DataRepresentation1.CubeAxesTickLocation = 'Inside' DataRepresentation1.CubeAxesXAxisMinorTickVisibility = 1 DataRepresentation1.CubeAxesYAxisVisibility = 1 DataRepresentation1.SelectionPointLabelFontFamily = 'Arial' DataRepresentation1.Source.ShaftResolution = 6 DataRepresentation1.CubeAxesFlyMode = 'Closest Triad' DataRepresentation1.SelectScaleArray = '' DataRepresentation1.CubeAxesYTitle = 'Y-Axis' DataRepresentation1.ColorAttributeType = 'POINT_DATA' DataRepresentation1.SpecularPower = 100.0 DataRepresentation1.Texture = [] DataRepresentation1.SelectionCellLabelShadow = 0 DataRepresentation1.AmbientColor = [1.0, 1.0, 1.0] DataRepresentation1.MapScalars = 1 DataRepresentation1.PointSize = 2.0 DataRepresentation1.Source.TipLength = 0.35 DataRepresentation1.SelectionCellLabelFormat = '' DataRepresentation1.Scaling = 0 DataRepresentation1.StaticMode = 0 DataRepresentation1.SelectionCellLabelColor = [0.0, 1.0, 0.0] DataRepresentation1.Source.TipRadius = 0.1 DataRepresentation1.EdgeColor = [0.0, 0.0, 0.5000076295109483] DataRepresentation1.CubeAxesXAxisTickVisibility = 1 DataRepresentation1.SelectionCellLabelVisibility = 0 DataRepresentation1.NonlinearSubdivisionLevel = 1 DataRepresentation1.CubeAxesXAxisRange = [0.0, 1.0] DataRepresentation1.Representation = 'Surface' DataRepresentation1.CubeAxesYAxisRange = [0.0, 1.0] DataRepresentation1.CustomBounds = [0.0, 1.0, 0.0, 1.0, 0.0, 1.0] DataRepresentation1.Orientation = [0.0, 0.0, 0.0] DataRepresentation1.CubeAxesEnableCustomAxisRange = 0 DataRepresentation1.CubeAxesXTitle = 'X-Axis' DataRepresentation1.CubeAxesInertia = 1 DataRepresentation1.BackfaceOpacity = 1.0 DataRepresentation1.SelectionCellFieldDataArrayName = 'vtkOriginalCellIds' DataRepresentation1.SelectionColor = [1.0, 0.0, 1.0] DataRepresentation1.Ambient = 0.0 DataRepresentation1.SelectionPointLabelFontSize = 18 DataRepresentation1.ScaleFactor = 0.8360145000000001 DataRepresentation1.BackfaceAmbientColor = [1.0, 1.0, 1.0] DataRepresentation1.Source.ShaftRadius = 0.03 DataRepresentation1.SelectMaskArray = '' DataRepresentation1.SelectionLineWidth = 2.0 DataRepresentation1.CubeAxesZAxisMinorTickVisibility = 1 DataRepresentation1.CubeAxesXAxisVisibility = 1 DataRepresentation1.Interpolation = 'Gouraud' DataRepresentation1.SelectionCellLabelFontFamily = 'Arial' DataRepresentation1.SelectionCellLabelItalic = 0 DataRepresentation1.CubeAxesYAxisMinorTickVisibility = 1 DataRepresentation1.CubeAxesZGridLines = 0 DataRepresentation1.SelectionPointLabelFormat = '' DataRepresentation1.SelectionPointLabelOpacity = 1.0 DataRepresentation1.BackfaceDiffuseColor = [1.0, 1.0, 1.0] DataRepresentation1.Pickable = 1 DataRepresentation1.CustomBoundsActive = [0, 0, 0] DataRepresentation1.SelectionRepresentation = 'Wireframe' DataRepresentation1.SelectionPointLabelBold = 0 DataRepresentation1.ColorArrayName = 'radius' DataRepresentation1.SelectionPointLabelItalic = 0 DataRepresentation1.AllowSpecularHighlightingWithScalarColoring = 0 DataRepresentation1.SpecularColor = [1.0, 1.0, 1.0] DataRepresentation1.LookupTable = a1_radius_PVLookupTable DataRepresentation1.SelectionPointSize = 5.0 DataRepresentation1.SelectionCellLabelBold = 0 DataRepresentation1.Orient = 0 SetActiveSource(Glyph1) DataRepresentation3 = Show() DataRepresentation3.CubeAxesZAxisVisibility = 1 DataRepresentation3.SelectionPointLabelColor = [0.5, 0.5, 0.5] DataRepresentation3.SelectionPointFieldDataArrayName = 'radius' DataRepresentation3.SuppressLOD = 0 DataRepresentation3.CubeAxesXGridLines = 0 DataRepresentation3.CubeAxesYAxisTickVisibility = 1 DataRepresentation3.CubeAxesColor = [1.0, 1.0, 1.0] DataRepresentation3.Position = [0.0, 0.0, 0.0] DataRepresentation3.BackfaceRepresentation = 'Follow Frontface' DataRepresentation3.SelectionOpacity = 1.0 DataRepresentation3.SelectionPointLabelShadow = 0 DataRepresentation3.CubeAxesYGridLines = 0 DataRepresentation3.CubeAxesZAxisRange = [0.0, 1.0] DataRepresentation3.OrientationMode = 'Direction' DataRepresentation3.Source.TipResolution = 6 DataRepresentation3.ScaleMode = 'No Data Scaling Off' DataRepresentation3.Diffuse = 1.0 DataRepresentation3.SelectionUseOutline = 0 DataRepresentation3.CubeAxesZTitle = 'Z-Axis' DataRepresentation3.Specular = 0.1 DataRepresentation3.SelectionVisibility = 1 DataRepresentation3.InterpolateScalarsBeforeMapping = 1 DataRepresentation3.CubeAxesZAxisTickVisibility = 1 DataRepresentation3.Origin = [0.0, 0.0, 0.0] DataRepresentation3.CubeAxesVisibility = 0 DataRepresentation3.Scale = [1.0, 1.0, 1.0] DataRepresentation3.SelectionCellLabelJustification = 'Left' DataRepresentation3.DiffuseColor = [1.0, 1.0, 1.0] DataRepresentation3.SelectionCellLabelOpacity = 1.0 DataRepresentation3.Source = "Arrow" DataRepresentation3.Source.Invert = 0 DataRepresentation3.Masking = 0 DataRepresentation3.Opacity = 1.0 DataRepresentation3.LineWidth = 1.0 DataRepresentation3.MeshVisibility = 0 DataRepresentation3.Visibility = 0 DataRepresentation3.SelectionCellLabelFontSize = 18 DataRepresentation3.CubeAxesCornerOffset = 0.0 DataRepresentation3.SelectionPointLabelJustification = 'Left' DataRepresentation3.SelectionPointLabelVisibility = 0 DataRepresentation3.SelectOrientationVectors = '' DataRepresentation3.CubeAxesTickLocation = 'Inside' DataRepresentation3.CubeAxesXAxisMinorTickVisibility = 1 DataRepresentation3.CubeAxesYAxisVisibility = 1 DataRepresentation3.SelectionPointLabelFontFamily = 'Arial' DataRepresentation3.Source.ShaftResolution = 6 DataRepresentation3.CubeAxesFlyMode = 'Closest Triad' DataRepresentation3.SelectScaleArray = '' DataRepresentation3.CubeAxesYTitle = 'Y-Axis' DataRepresentation3.ColorAttributeType = 'POINT_DATA' DataRepresentation3.SpecularPower = 100.0 DataRepresentation3.Texture = [] DataRepresentation3.SelectionCellLabelShadow = 0 DataRepresentation3.AmbientColor = [1.0, 1.0, 1.0] DataRepresentation3.MapScalars = 1 DataRepresentation3.PointSize = 2.0 DataRepresentation3.Source.TipLength = 0.35 DataRepresentation3.SelectionCellLabelFormat = '' DataRepresentation3.Scaling = 0 DataRepresentation3.StaticMode = 0 DataRepresentation3.SelectionCellLabelColor = [0.0, 1.0, 0.0] DataRepresentation3.Source.TipRadius = 0.1 DataRepresentation3.EdgeColor = [0.0, 0.0, 0.5000076295109483] DataRepresentation3.CubeAxesXAxisTickVisibility = 1 DataRepresentation3.SelectionCellLabelVisibility = 0 DataRepresentation3.NonlinearSubdivisionLevel = 1 DataRepresentation3.CubeAxesXAxisRange = [0.0, 1.0] DataRepresentation3.Representation = 'Surface' DataRepresentation3.CubeAxesYAxisRange = [0.0, 1.0] DataRepresentation3.CustomBounds = [0.0, 1.0, 0.0, 1.0, 0.0, 1.0] DataRepresentation3.Orientation = [0.0, 0.0, 0.0] DataRepresentation3.CubeAxesEnableCustomAxisRange = 0 DataRepresentation3.CubeAxesXTitle = 'X-Axis' DataRepresentation3.CubeAxesInertia = 1 DataRepresentation3.BackfaceOpacity = 1.0 DataRepresentation3.SelectionCellFieldDataArrayName = 'vtkOriginalCellIds' DataRepresentation3.SelectionColor = [1.0, 0.0, 1.0] DataRepresentation3.Ambient = 0.0 DataRepresentation3.SelectionPointLabelFontSize = 18 DataRepresentation3.ScaleFactor = 0.9713980622589589 DataRepresentation3.BackfaceAmbientColor = [1.0, 1.0, 1.0] DataRepresentation3.Source.ShaftRadius = 0.03 DataRepresentation3.SelectMaskArray = '' DataRepresentation3.SelectionLineWidth = 2.0 DataRepresentation3.CubeAxesZAxisMinorTickVisibility = 1 DataRepresentation3.CubeAxesXAxisVisibility = 1 DataRepresentation3.Interpolation = 'Gouraud' DataRepresentation3.SelectionCellLabelFontFamily = 'Arial' DataRepresentation3.SelectionCellLabelItalic = 0 DataRepresentation3.CubeAxesYAxisMinorTickVisibility = 1 DataRepresentation3.CubeAxesZGridLines = 0 DataRepresentation3.SelectionPointLabelFormat = '' DataRepresentation3.SelectionPointLabelOpacity = 1.0 DataRepresentation3.BackfaceDiffuseColor = [1.0, 1.0, 1.0] DataRepresentation3.Pickable = 1 DataRepresentation3.CustomBoundsActive = [0, 0, 0] DataRepresentation3.SelectionRepresentation = 'Wireframe' DataRepresentation3.SelectionPointLabelBold = 0 DataRepresentation3.ColorArrayName = 'radius' DataRepresentation3.SelectionPointLabelItalic = 0 DataRepresentation3.AllowSpecularHighlightingWithScalarColoring = 0 DataRepresentation3.SpecularColor = [1.0, 1.0, 1.0] DataRepresentation3.LookupTable = a1_radius_PVLookupTable DataRepresentation3.SelectionPointSize = 5.0 DataRepresentation3.SelectionCellLabelBold = 0 DataRepresentation3.Orient = 0 SetActiveSource(Clip2) DataRepresentation5 = Show() DataRepresentation5.CubeAxesZAxisVisibility = 1 DataRepresentation5.SelectionPointLabelColor = [0.5, 0.5, 0.5] DataRepresentation5.SelectionPointFieldDataArrayName = 'radius' DataRepresentation5.SuppressLOD = 0 DataRepresentation5.CubeAxesXGridLines = 0 DataRepresentation5.CubeAxesYAxisTickVisibility = 1 DataRepresentation5.CubeAxesColor = [1.0, 1.0, 1.0] DataRepresentation5.Position = [0.0, 0.0, 0.0] DataRepresentation5.BackfaceRepresentation = 'Follow Frontface' DataRepresentation5.SelectionOpacity = 1.0 DataRepresentation5.SelectionPointLabelShadow = 0 DataRepresentation5.CubeAxesYGridLines = 0 DataRepresentation5.CubeAxesZAxisRange = [0.0, 1.0] DataRepresentation5.OrientationMode = 'Direction' DataRepresentation5.Source.TipResolution = 6 DataRepresentation5.ScaleMode = 'No Data Scaling Off' DataRepresentation5.Diffuse = 1.0 DataRepresentation5.SelectionUseOutline = 0 DataRepresentation5.SelectionPointLabelFormat = '' DataRepresentation5.CubeAxesZTitle = 'Z-Axis' DataRepresentation5.Specular = 0.1 DataRepresentation5.SelectionVisibility = 1 DataRepresentation5.InterpolateScalarsBeforeMapping = 1 DataRepresentation5.CubeAxesZAxisTickVisibility = 1 DataRepresentation5.Origin = [0.0, 0.0, 0.0] DataRepresentation5.CubeAxesVisibility = 0 DataRepresentation5.Scale = [1.0, 1.0, 1.0] DataRepresentation5.SelectionCellLabelJustification = 'Left' DataRepresentation5.DiffuseColor = [1.0, 1.0, 1.0] DataRepresentation5.SelectionCellLabelOpacity = 1.0 DataRepresentation5.CubeAxesInertia = 1 DataRepresentation5.Source = "Arrow" DataRepresentation5.Source.Invert = 0 DataRepresentation5.Masking = 0 DataRepresentation5.Opacity = 1.0 DataRepresentation5.LineWidth = 1.0 DataRepresentation5.MeshVisibility = 0 DataRepresentation5.Visibility = 1 DataRepresentation5.SelectionCellLabelFontSize = 18 DataRepresentation5.CubeAxesCornerOffset = 0.0 DataRepresentation5.SelectionPointLabelJustification = 'Left' DataRepresentation5.SelectionPointLabelVisibility = 0 DataRepresentation5.SelectOrientationVectors = '' DataRepresentation5.CubeAxesTickLocation = 'Inside' DataRepresentation5.BackfaceDiffuseColor = [1.0, 1.0, 1.0] DataRepresentation5.CubeAxesYAxisVisibility = 1 DataRepresentation5.SelectionPointLabelFontFamily = 'Arial' DataRepresentation5.Source.ShaftResolution = 6 DataRepresentation5.CubeAxesFlyMode = 'Closest Triad' DataRepresentation5.SelectScaleArray = '' DataRepresentation5.CubeAxesYTitle = 'Y-Axis' DataRepresentation5.ColorAttributeType = 'POINT_DATA' DataRepresentation5.SpecularPower = 100.0 DataRepresentation5.Texture = [] DataRepresentation5.SelectionCellLabelShadow = 0 DataRepresentation5.AmbientColor = [1.0, 1.0, 1.0] DataRepresentation5.MapScalars = 1 DataRepresentation5.PointSize = 2.0 DataRepresentation5.Source.TipLength = 0.35 DataRepresentation5.SelectionCellLabelFormat = '' DataRepresentation5.Scaling = 0 DataRepresentation5.StaticMode = 0 DataRepresentation5.SelectionCellLabelColor = [0.0, 1.0, 0.0] DataRepresentation5.Source.TipRadius = 0.1 DataRepresentation5.EdgeColor = [0.0, 0.0, 0.5000076295109483] DataRepresentation5.CubeAxesXAxisTickVisibility = 1 DataRepresentation5.SelectionCellLabelVisibility = 0 DataRepresentation5.NonlinearSubdivisionLevel = 1 DataRepresentation5.CubeAxesXAxisRange = [0.0, 1.0] DataRepresentation5.Representation = 'Surface' DataRepresentation5.CubeAxesYAxisRange = [0.0, 1.0] DataRepresentation5.CustomBounds = [0.0, 1.0, 0.0, 1.0, 0.0, 1.0] DataRepresentation5.Orientation = [0.0, 0.0, 0.0] DataRepresentation5.CubeAxesEnableCustomAxisRange = 0 DataRepresentation5.CubeAxesXTitle = 'X-Axis' DataRepresentation5.ScalarOpacityUnitDistance = 1.1040324233388048 DataRepresentation5.BackfaceOpacity = 1.0 DataRepresentation5.SelectionPointLabelFontSize = 18 DataRepresentation5.SelectionCellFieldDataArrayName = 'vtkOriginalCellIds' DataRepresentation5.SelectionColor = [1.0, 0.0, 1.0] DataRepresentation5.Ambient = 0.0 DataRepresentation5.CubeAxesXAxisMinorTickVisibility = 1 DataRepresentation5.ScaleFactor = 0.8981979608535767 DataRepresentation5.BackfaceAmbientColor = [1.0, 1.0, 1.0] DataRepresentation5.Source.ShaftRadius = 0.03 DataRepresentation5.ScalarOpacityFunction = a1_radius_PiecewiseFunction DataRepresentation5.SelectMaskArray = '' DataRepresentation5.SelectionLineWidth = 2.0 DataRepresentation5.CubeAxesZAxisMinorTickVisibility = 1 DataRepresentation5.CubeAxesXAxisVisibility = 1 DataRepresentation5.Interpolation = 'Gouraud' DataRepresentation5.SelectMapper = 'Projected tetra' DataRepresentation5.SelectionCellLabelFontFamily = 'Arial' DataRepresentation5.SelectionCellLabelItalic = 0 DataRepresentation5.CubeAxesYAxisMinorTickVisibility = 1 DataRepresentation5.CubeAxesZGridLines = 0 DataRepresentation5.ExtractedBlockIndex = 0 DataRepresentation5.SelectionPointLabelOpacity = 1.0 DataRepresentation5.Pickable = 1 DataRepresentation5.CustomBoundsActive = [0, 0, 0] DataRepresentation5.SelectionRepresentation = 'Wireframe' DataRepresentation5.SelectionPointLabelBold = 0 DataRepresentation5.ColorArrayName = 'radius' DataRepresentation5.SelectionPointLabelItalic = 0 DataRepresentation5.AllowSpecularHighlightingWithScalarColoring = 0 DataRepresentation5.SpecularColor = [1.0, 1.0, 1.0] DataRepresentation5.LookupTable = a1_radius_PVLookupTable DataRepresentation5.SelectionPointSize = 5.0 DataRepresentation5.SelectionCellLabelBold = 0 DataRepresentation5.Orient = 0 SetActiveSource(testSection_vtk) DataRepresentation7 = Show() DataRepresentation7.CubeAxesZAxisVisibility = 1 DataRepresentation7.SelectionPointLabelColor = [0.5, 0.5, 0.5] DataRepresentation7.SelectionPointFieldDataArrayName = 'radius' DataRepresentation7.SuppressLOD = 0 DataRepresentation7.CubeAxesXGridLines = 0 DataRepresentation7.CubeAxesYAxisTickVisibility = 1 DataRepresentation7.CubeAxesColor = [1.0, 1.0, 1.0] DataRepresentation7.Position = [0.0, 0.0, 0.0] DataRepresentation7.BackfaceRepresentation = 'Follow Frontface' DataRepresentation7.SelectionOpacity = 1.0 DataRepresentation7.SelectionPointLabelShadow = 0 DataRepresentation7.CubeAxesYGridLines = 0 DataRepresentation7.CubeAxesZAxisRange = [0.0, 1.0] DataRepresentation7.OrientationMode = 'Direction' DataRepresentation7.Source.TipResolution = 6 DataRepresentation7.ScaleMode = 'No Data Scaling Off' DataRepresentation7.Diffuse = 1.0 DataRepresentation7.SelectionUseOutline = 0 DataRepresentation7.CubeAxesZTitle = 'Z-Axis' DataRepresentation7.Specular = 0.1 DataRepresentation7.SelectionVisibility = 1 DataRepresentation7.InterpolateScalarsBeforeMapping = 1 DataRepresentation7.CubeAxesZAxisTickVisibility = 1 DataRepresentation7.Origin = [0.0, 0.0, 0.0] DataRepresentation7.CubeAxesVisibility = 0 DataRepresentation7.Scale = [1.0, 1.0, 1.0] DataRepresentation7.SelectionCellLabelJustification = 'Left' DataRepresentation7.DiffuseColor = [1.0, 1.0, 1.0] DataRepresentation7.SelectionCellLabelOpacity = 1.0 DataRepresentation7.Source = "Arrow" DataRepresentation7.Source.Invert = 0 DataRepresentation7.Masking = 0 DataRepresentation7.Opacity = 1.0 DataRepresentation7.LineWidth = 1.0 DataRepresentation7.MeshVisibility = 0 DataRepresentation7.Visibility = 1 DataRepresentation7.SelectionCellLabelFontSize = 18 DataRepresentation7.CubeAxesCornerOffset = 0.0 DataRepresentation7.SelectionPointLabelJustification = 'Left' DataRepresentation7.SelectionPointLabelVisibility = 0 DataRepresentation7.SelectOrientationVectors = '' DataRepresentation7.CubeAxesTickLocation = 'Inside' DataRepresentation7.CubeAxesXAxisMinorTickVisibility = 1 DataRepresentation7.CubeAxesYAxisVisibility = 1 DataRepresentation7.SelectionPointLabelFontFamily = 'Arial' DataRepresentation7.Source.ShaftResolution = 6 DataRepresentation7.CubeAxesFlyMode = 'Closest Triad' DataRepresentation7.SelectScaleArray = '' DataRepresentation7.CubeAxesYTitle = 'Y-Axis' DataRepresentation7.ColorAttributeType = 'POINT_DATA' DataRepresentation7.SpecularPower = 100.0 DataRepresentation7.Texture = [] DataRepresentation7.SelectionCellLabelShadow = 0 DataRepresentation7.AmbientColor = [1.0, 1.0, 1.0] DataRepresentation7.MapScalars = 1 DataRepresentation7.PointSize = 2.0 DataRepresentation7.Source.TipLength = 0.35 DataRepresentation7.SelectionCellLabelFormat = '' DataRepresentation7.Scaling = 0 DataRepresentation7.StaticMode = 0 DataRepresentation7.SelectionCellLabelColor = [0.0, 1.0, 0.0] DataRepresentation7.Source.TipRadius = 0.1 DataRepresentation7.EdgeColor = [0.0, 0.0, 0.5000076295109483] DataRepresentation7.CubeAxesXAxisTickVisibility = 1 DataRepresentation7.SelectionCellLabelVisibility = 0 DataRepresentation7.NonlinearSubdivisionLevel = 1 DataRepresentation7.CubeAxesXAxisRange = [0.0, 1.0] DataRepresentation7.Representation = 'Surface' DataRepresentation7.CubeAxesYAxisRange = [0.0, 1.0] DataRepresentation7.CustomBounds = [0.0, 1.0, 0.0, 1.0, 0.0, 1.0] DataRepresentation7.Orientation = [0.0, 0.0, 0.0] DataRepresentation7.CubeAxesEnableCustomAxisRange = 0 DataRepresentation7.CubeAxesXTitle = 'X-Axis' DataRepresentation7.CubeAxesInertia = 1 DataRepresentation7.BackfaceOpacity = 1.0 DataRepresentation7.SelectionCellFieldDataArrayName = 'vtkOriginalCellIds' DataRepresentation7.SelectionColor = [1.0, 0.0, 1.0] DataRepresentation7.Ambient = 0.0 DataRepresentation7.SelectionPointLabelFontSize = 18 DataRepresentation7.ScaleFactor = 0.73055 DataRepresentation7.BackfaceAmbientColor = [1.0, 1.0, 1.0] DataRepresentation7.Source.ShaftRadius = 0.03 DataRepresentation7.SelectMaskArray = '' DataRepresentation7.SelectionLineWidth = 2.0 DataRepresentation7.CubeAxesZAxisMinorTickVisibility = 1 DataRepresentation7.CubeAxesXAxisVisibility = 1 DataRepresentation7.Interpolation = 'Gouraud' DataRepresentation7.SelectionCellLabelFontFamily = 'Arial' DataRepresentation7.SelectionCellLabelItalic = 0 DataRepresentation7.CubeAxesYAxisMinorTickVisibility = 1 DataRepresentation7.CubeAxesZGridLines = 0 DataRepresentation7.SelectionPointLabelFormat = '' DataRepresentation7.SelectionPointLabelOpacity = 1.0 DataRepresentation7.BackfaceDiffuseColor = [1.0, 1.0, 1.0] DataRepresentation7.Pickable = 1 DataRepresentation7.CustomBoundsActive = [0, 0, 0] DataRepresentation7.SelectionRepresentation = 'Wireframe' DataRepresentation7.SelectionPointLabelBold = 0 DataRepresentation7.ColorArrayName = 'radius' DataRepresentation7.SelectionPointLabelItalic = 0 DataRepresentation7.AllowSpecularHighlightingWithScalarColoring = 0 DataRepresentation7.SpecularColor = [1.0, 1.0, 1.0] DataRepresentation7.LookupTable = a1_radius_PVLookupTable DataRepresentation7.SelectionPointSize = 5.0 DataRepresentation7.SelectionCellLabelBold = 0 DataRepresentation7.Orient = 0 SetActiveSource(Glyph3) DataRepresentation8 = Show() DataRepresentation8.CubeAxesZAxisVisibility = 1 DataRepresentation8.SelectionPointLabelColor = [0.5, 0.5, 0.5] DataRepresentation8.SelectionPointFieldDataArrayName = 'radius' DataRepresentation8.SuppressLOD = 0 DataRepresentation8.CubeAxesXGridLines = 0 DataRepresentation8.CubeAxesYAxisTickVisibility = 1 DataRepresentation8.CubeAxesColor = [1.0, 1.0, 1.0] DataRepresentation8.Position = [0.0, 0.0, 0.0] DataRepresentation8.BackfaceRepresentation = 'Follow Frontface' DataRepresentation8.SelectionOpacity = 1.0 DataRepresentation8.SelectionPointLabelShadow = 0 DataRepresentation8.CubeAxesYGridLines = 0 DataRepresentation8.CubeAxesZAxisRange = [0.0, 1.0] DataRepresentation8.OrientationMode = 'Direction' DataRepresentation8.Source.TipResolution = 6 DataRepresentation8.ScaleMode = 'No Data Scaling Off' DataRepresentation8.Diffuse = 1.0 DataRepresentation8.SelectionUseOutline = 0 DataRepresentation8.CubeAxesZTitle = 'Z-Axis' DataRepresentation8.Specular = 0.1 DataRepresentation8.SelectionVisibility = 1 DataRepresentation8.InterpolateScalarsBeforeMapping = 1 DataRepresentation8.CubeAxesZAxisTickVisibility = 1 DataRepresentation8.Origin = [0.0, 0.0, 0.0] DataRepresentation8.CubeAxesVisibility = 0 DataRepresentation8.Scale = [1.0, 1.0, 1.0] DataRepresentation8.SelectionCellLabelJustification = 'Left' DataRepresentation8.DiffuseColor = [1.0, 1.0, 1.0] DataRepresentation8.SelectionCellLabelOpacity = 1.0 DataRepresentation8.Source = "Arrow" DataRepresentation8.Source.Invert = 0 DataRepresentation8.Masking = 0 DataRepresentation8.Opacity = 1.0 DataRepresentation8.LineWidth = 1.0 DataRepresentation8.MeshVisibility = 0 DataRepresentation8.Visibility = 1 DataRepresentation8.SelectionCellLabelFontSize = 18 DataRepresentation8.CubeAxesCornerOffset = 0.0 DataRepresentation8.SelectionPointLabelJustification = 'Left' DataRepresentation8.SelectionPointLabelVisibility = 0 DataRepresentation8.SelectOrientationVectors = '' DataRepresentation8.CubeAxesTickLocation = 'Inside' DataRepresentation8.CubeAxesXAxisMinorTickVisibility = 1 DataRepresentation8.CubeAxesYAxisVisibility = 1 DataRepresentation8.SelectionPointLabelFontFamily = 'Arial' DataRepresentation8.Source.ShaftResolution = 6 DataRepresentation8.CubeAxesFlyMode = 'Closest Triad' DataRepresentation8.SelectScaleArray = '' DataRepresentation8.CubeAxesYTitle = 'Y-Axis' DataRepresentation8.ColorAttributeType = 'POINT_DATA' DataRepresentation8.SpecularPower = 100.0 DataRepresentation8.Texture = [] DataRepresentation8.SelectionCellLabelShadow = 0 DataRepresentation8.AmbientColor = [1.0, 1.0, 1.0] DataRepresentation8.MapScalars = 1 DataRepresentation8.PointSize = 2.0 DataRepresentation8.Source.TipLength = 0.35 DataRepresentation8.SelectionCellLabelFormat = '' DataRepresentation8.Scaling = 0 DataRepresentation8.StaticMode = 0 DataRepresentation8.SelectionCellLabelColor = [0.0, 1.0, 0.0] DataRepresentation8.Source.TipRadius = 0.1 DataRepresentation8.EdgeColor = [0.0, 0.0, 0.5000076295109483] DataRepresentation8.CubeAxesXAxisTickVisibility = 1 DataRepresentation8.SelectionCellLabelVisibility = 0 DataRepresentation8.NonlinearSubdivisionLevel = 1 DataRepresentation8.CubeAxesXAxisRange = [0.0, 1.0] DataRepresentation8.Representation = 'Surface' DataRepresentation8.CubeAxesYAxisRange = [0.0, 1.0] DataRepresentation8.CustomBounds = [0.0, 1.0, 0.0, 1.0, 0.0, 1.0] DataRepresentation8.Orientation = [0.0, 0.0, 0.0] DataRepresentation8.CubeAxesEnableCustomAxisRange = 0 DataRepresentation8.CubeAxesXTitle = 'X-Axis' DataRepresentation8.CubeAxesInertia = 1 DataRepresentation8.BackfaceOpacity = 1.0 DataRepresentation8.SelectionCellFieldDataArrayName = 'vtkOriginalCellIds' DataRepresentation8.SelectionColor = [1.0, 0.0, 1.0] DataRepresentation8.Ambient = 0.0 DataRepresentation8.SelectionPointLabelFontSize = 18 DataRepresentation8.ScaleFactor = 0.8328240185976029 DataRepresentation8.BackfaceAmbientColor = [1.0, 1.0, 1.0] DataRepresentation8.Source.ShaftRadius = 0.03 DataRepresentation8.SelectMaskArray = '' DataRepresentation8.SelectionLineWidth = 2.0 DataRepresentation8.CubeAxesZAxisMinorTickVisibility = 1 DataRepresentation8.CubeAxesXAxisVisibility = 1 DataRepresentation8.Interpolation = 'Gouraud' DataRepresentation8.SelectionCellLabelFontFamily = 'Arial' DataRepresentation8.SelectionCellLabelItalic = 0 DataRepresentation8.CubeAxesYAxisMinorTickVisibility = 1 DataRepresentation8.CubeAxesZGridLines = 0 DataRepresentation8.SelectionPointLabelFormat = '' DataRepresentation8.SelectionPointLabelOpacity = 1.0 DataRepresentation8.BackfaceDiffuseColor = [1.0, 1.0, 1.0] DataRepresentation8.Pickable = 1 DataRepresentation8.CustomBoundsActive = [0, 0, 0] DataRepresentation8.SelectionRepresentation = 'Wireframe' DataRepresentation8.SelectionPointLabelBold = 0 DataRepresentation8.ColorArrayName = 'radiusOrig' DataRepresentation8.SelectionPointLabelItalic = 0 DataRepresentation8.AllowSpecularHighlightingWithScalarColoring = 0 DataRepresentation8.SpecularColor = [1.0, 1.0, 1.0] DataRepresentation8.LookupTable = a1_radiusOrig_PVLookupTable DataRepresentation8.SelectionPointSize = 5.0 DataRepresentation8.SelectionCellLabelBold = 0 DataRepresentation8.Orient = 0 Render()
gpl-2.0
rschnapka/odoo
openerp/tests/addons/test_limits/models.py
435
1034
# -*- coding: utf-8 -*- import time import openerp class m(openerp.osv.osv.Model): """ This model exposes a few methods that will consume between 'almost no resource' and 'a lot of resource'. """ _name = 'test.limits.model' def consume_nothing(self, cr, uid, context=None): return True def consume_memory(self, cr, uid, size, context=None): l = [0] * size return True def leak_memory(self, cr, uid, size, context=None): if not hasattr(self, 'l'): self.l = [] self.l.append([0] * size) return True def consume_time(self, cr, uid, seconds, context=None): time.sleep(seconds) return True def consume_cpu_time(self, cr, uid, seconds, context=None): t0 = time.clock() t1 = time.clock() while t1 - t0 < seconds: for i in xrange(10000000): x = i * i t1 = time.clock() return True # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
nklulupeterpan/Comedy
node_modules/gulp-sass/node_modules/node-sass/node_modules/node-gyp/gyp/pylib/gyp/MSVSProject.py
2736
6387
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Visual Studio project reader/writer.""" import gyp.common import gyp.easy_xml as easy_xml #------------------------------------------------------------------------------ class Tool(object): """Visual Studio tool.""" def __init__(self, name, attrs=None): """Initializes the tool. Args: name: Tool name. attrs: Dict of tool attributes; may be None. """ self._attrs = attrs or {} self._attrs['Name'] = name def _GetSpecification(self): """Creates an element for the tool. Returns: A new xml.dom.Element for the tool. """ return ['Tool', self._attrs] class Filter(object): """Visual Studio filter - that is, a virtual folder.""" def __init__(self, name, contents=None): """Initializes the folder. Args: name: Filter (folder) name. contents: List of filenames and/or Filter objects contained. """ self.name = name self.contents = list(contents or []) #------------------------------------------------------------------------------ class Writer(object): """Visual Studio XML project writer.""" def __init__(self, project_path, version, name, guid=None, platforms=None): """Initializes the project. Args: project_path: Path to the project file. version: Format version to emit. name: Name of the project. guid: GUID to use for project, if not None. platforms: Array of string, the supported platforms. If null, ['Win32'] """ self.project_path = project_path self.version = version self.name = name self.guid = guid # Default to Win32 for platforms. if not platforms: platforms = ['Win32'] # Initialize the specifications of the various sections. self.platform_section = ['Platforms'] for platform in platforms: self.platform_section.append(['Platform', {'Name': platform}]) self.tool_files_section = ['ToolFiles'] self.configurations_section = ['Configurations'] self.files_section = ['Files'] # Keep a dict keyed on filename to speed up access. self.files_dict = dict() def AddToolFile(self, path): """Adds a tool file to the project. Args: path: Relative path from project to tool file. """ self.tool_files_section.append(['ToolFile', {'RelativePath': path}]) def _GetSpecForConfiguration(self, config_type, config_name, attrs, tools): """Returns the specification for a configuration. Args: config_type: Type of configuration node. config_name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Returns: """ # Handle defaults if not attrs: attrs = {} if not tools: tools = [] # Add configuration node and its attributes node_attrs = attrs.copy() node_attrs['Name'] = config_name specification = [config_type, node_attrs] # Add tool nodes and their attributes if tools: for t in tools: if isinstance(t, Tool): specification.append(t._GetSpecification()) else: specification.append(Tool(t)._GetSpecification()) return specification def AddConfig(self, name, attrs=None, tools=None): """Adds a configuration to the project. Args: name: Configuration name. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. """ spec = self._GetSpecForConfiguration('Configuration', name, attrs, tools) self.configurations_section.append(spec) def _AddFilesToNode(self, parent, files): """Adds files and/or filters to the parent node. Args: parent: Destination node files: A list of Filter objects and/or relative paths to files. Will call itself recursively, if the files list contains Filter objects. """ for f in files: if isinstance(f, Filter): node = ['Filter', {'Name': f.name}] self._AddFilesToNode(node, f.contents) else: node = ['File', {'RelativePath': f}] self.files_dict[f] = node parent.append(node) def AddFiles(self, files): """Adds files to the project. Args: files: A list of Filter objects and/or relative paths to files. This makes a copy of the file/filter tree at the time of this call. If you later add files to a Filter object which was passed into a previous call to AddFiles(), it will not be reflected in this project. """ self._AddFilesToNode(self.files_section, files) # TODO(rspangler) This also doesn't handle adding files to an existing # filter. That is, it doesn't merge the trees. def AddFileConfig(self, path, config, attrs=None, tools=None): """Adds a configuration to a file. Args: path: Relative path to the file. config: Name of configuration to add. attrs: Dict of configuration attributes; may be None. tools: List of tools (strings or Tool objects); may be None. Raises: ValueError: Relative path does not match any file added via AddFiles(). """ # Find the file node with the right relative path parent = self.files_dict.get(path) if not parent: raise ValueError('AddFileConfig: file "%s" not in project.' % path) # Add the config to the file node spec = self._GetSpecForConfiguration('FileConfiguration', config, attrs, tools) parent.append(spec) def WriteIfChanged(self): """Writes the project file.""" # First create XML content definition content = [ 'VisualStudioProject', {'ProjectType': 'Visual C++', 'Version': self.version.ProjectVersion(), 'Name': self.name, 'ProjectGUID': self.guid, 'RootNamespace': self.name, 'Keyword': 'Win32Proj' }, self.platform_section, self.tool_files_section, self.configurations_section, ['References'], # empty section self.files_section, ['Globals'] # empty section ] easy_xml.WriteXmlIfChanged(content, self.project_path, encoding="Windows-1252")
mit
vansjyo/Hacktoberfest-2k17
GUI_Calculator/shareWithMeCalc/calculator.py
2
7666
from Tkinter import * import math class Calc(): def __init__(self): self.total = 0 self.current= "" self.new_num = True self.op_pending = False self.op = "" self.eq_flag = False def num_press(self,num): temp = text_box.get() self.eq_flag = False temp2 = str(num) if self.new_num == True: self.current = temp2 self.new_num = False else: if temp2 == '.': if temp2 in temp: return self.current = temp + temp2 text_box.delete(0,END) text_box.insert(0,self.current) def calc_total(self): if self.op_pending == True: self.do_calc() self.op_pending = False def display(self, value): text_box.delete(0,END) text_box.insert(0,value) def do_calc(self): self.current = float(self.current) if self.op == "add": self.total+=self.current if self.op == "minus": self.total-=self.current if self.op == "times": self.total*=self.current try: if self.op == "divide": self.total/=self.current except ZeroDivisionError: error="Div by 0 not possible!!" text_box.delete(0,END) text_box.insert(0,error) text_box.delete(0,END) text_box.insert(0,self.total) self.new_num = True def operation(self,op): if self.op_pending == True: self.do_calc() self.op = op else: self.op_pending = True if self.eq_flag == False: self.total = float(text_box.get()) else: self.total = self.current self.new_num = True self.op = op self.eq_flag = False def reciprocal(self): try: self.current = float(self.current) self.current = float(1/self.current) text_box.delete(0,END) text_box.insert(0,self.current) self.new_num = True except ZeroDivisionError: error="Div by 0 not possible!!" text_box.delete(0,END) text_box.insert(0,error) def pow(self): self.current = float(self.current) self.total=self.total**self.current text_box.delete(0,END) text_box.insert(0,self.total) self.new_num = True def sine(self): self.current = float(self.current) self.current = float(math.sin((self.current))) text_box.delete(0,END) text_box.insert(0,self.current) self.new_num = True def cosine(self): self.current = float(self.current) self.current = float(math.cos((self.current))) text_box.delete(0,END) text_box.insert(0,self.current) self.new_num = True def cosec(self): self.current = float(self.current) self.current = float(math.cosec((self.current))) text_box.delete(0,END) text_box.insert(0,self.current) self.new_num = True def tan(self): self.current = float(self.current) self.current = float(math.tan((self.current))) text_box.delete(0,END) text_box.insert(0,self.current) self.new_num = True def cot(self): self.current = float(self.current) self.current = float(math.cot((self.current))) text_box.delete(0,END) text_box.insert(0,self.current) self.new_num = True def sec(self): self.current = float(self.current) self.current = float(math.sec((self.current))) text_box.delete(0,END) text_box.insert(0,self.current) self.new_num = True def Clear(): text_box.delete(0,END) root = Tk() root.title("My_Calculator") root.minsize(width = 350, height = 475) root.maxsize(width = 350, height = 475) frame = Frame(root,width = 1000, height = 10) frame.pack() my_calc = Calc() num = StringVar() text_box = Entry(frame,textvariable = num , bd=20, insertwidth =1 , font=30,justify = RIGHT) text_box.pack(side = TOP) b1 = Button(frame, padx = 16 , pady =16 , bd=8, text = "1",fg = "black") b1.pack(side = LEFT) b1["command"] = lambda: my_calc.num_press(1) b2 = Button(frame, padx = 16 , pady =16 , bd=8, text = "2",fg = "black") b2.pack(side = LEFT) b2["command"] = lambda: my_calc.num_press(2) b3 = Button(frame, padx = 16 , pady =16 , bd=8, text = "3",fg = "black") b3.pack(side = LEFT) b3["command"] = lambda: my_calc.num_press(3) b4 = Button(frame, padx = 16 , pady =16 , bd=8, text = "(",fg = "black") b4.pack(side = LEFT) b3["command"] = lambda: my_calc.num_press() b4 = Button(frame, padx = 16 , pady =16 , bd=8, text = ")",fg = "black") b4.pack(side = LEFT) b3["command"] = lambda: my_calc.num_press(3) frame1 = Frame(root) frame1.pack(side = TOP) b5 = Button(frame1, padx = 16 , pady =16 , bd=8, text = "4",fg = "black") b5.pack(side = LEFT) b5["command"] = lambda: my_calc.num_press(4) b6 = Button(frame1, padx = 16 , pady =16 , bd=8, text = "5",fg = "black") b6.pack(side = LEFT) b6["command"] = lambda: my_calc.num_press(5) b7 = Button(frame1, padx = 16 , pady =16 , bd=8, text = "6",fg = "black") b7.pack(side = LEFT) b7["command"] = lambda: my_calc.num_press(6) b8 = Button(frame1, padx = 16 , pady =16 , bd=8, text = "+",fg = "black") b8.pack(side = LEFT) b8["command"] = lambda: my_calc.operation("add") b8 = Button(frame1, padx = 16 , pady =16 , bd=8, text = "-",fg = "black") b8.pack(side = LEFT) b8["command"] = lambda: my_calc.operation("minus") frame2 = Frame(root) frame2.pack(side = TOP) b5 = Button(frame2, padx = 16 , pady =16 , bd=8, text = "7",fg = "black") b5.pack(side = LEFT) b5["command"] = lambda: my_calc.num_press(7) b5 = Button(frame2, padx = 16 , pady =16 , bd=8, text = "8",fg = "black") b5.pack(side = LEFT) b5["command"] = lambda: my_calc.num_press(8) b5 = Button(frame2, padx = 16 , pady =16 , bd=8, text = "9",fg = "black", command = Clear) b5.pack(side = LEFT) b5["command"] = lambda: my_calc.num_press(9) b5 = Button(frame2, padx = 16 , pady =16 , bd=8, text = "/",fg = "black") b5.pack(side = LEFT) b5["command"] = lambda: my_calc.operation("divide") b5 = Button(frame2, padx = 16 , pady =16 , bd=8, text = "*",fg = "black") b5.pack(side = LEFT) b5["command"] = lambda: my_calc.operation("times") frame3 =Frame(root) frame3.pack(side = TOP) b5 = Button(frame3, padx = 16 , pady =16 , bd=8, text = ".",fg = "black") b5.pack(side = LEFT) b5["command"] = lambda: my_calc.num_press(".") b5 = Button(frame3, padx = 16 , pady =16 , bd=8, text = "0",fg = "black") b5.pack(side = LEFT) b5["command"] = lambda: my_calc.num_press(0) b5 = Button(frame3, padx = 16 , pady =16 , bd=8, text = "CE",fg = "black",command = Clear) b5.pack(side = LEFT) b5 = Button(frame3, padx = 16 , pady =16 , bd=8, text = "C",fg = "black",command = Clear) b5.pack(side = LEFT) b5 = Button(frame3, padx = 16 , pady =16 , bd=8, text = "=",fg = "black") b5.pack(side = LEFT) b5["command"] = my_calc.calc_total frame4 = Frame(root) frame4.pack(side = TOP) b8 = Button(frame4, padx = 16 , pady =16 , bd=8, text = "sin",fg = "black") b8.pack(side = LEFT) b8["command"]= my_calc.sine b8 = Button(frame4, padx = 16 , pady =16 , bd=8, text = "cos",fg = "black") b8.pack(side = LEFT) b8["command"]= my_calc.cosine b8 = Button(frame4, padx = 16 , pady =16 , bd=8, text = "tan",fg = "black") b8.pack(side = LEFT) b8["command"]= my_calc.tan b8 = Button(frame4, padx = 16 , pady =16 , bd=8, text = "^",fg = "black") b8.pack(side = LEFT) b8["command"]= my_calc.pow b8 = Button(frame4, padx = 16 , pady =16 , bd=8, text = "1/x",fg = "black") b8.pack(side = LEFT) b8["command"]= my_calc.reciprocal frame5 = Frame(root) frame5.pack(side = TOP) b8 = Button(frame5, padx = 16 , pady =16 , bd=8, text = "cosec",fg = "black") b8.pack(side = LEFT) b8["command"]= my_calc.cosec b8 = Button(frame5, padx = 16 , pady =16 , bd=8, text = "sec",fg = "black") b8.pack(side = LEFT) b8["command"]= my_calc.sec b8 = Button(frame5, padx = 16 , pady =16 , bd=8, text = "cot",fg = "black") b8.pack(side = LEFT) b8["command"]= my_calc.cot b8 = Button(frame5, padx = 16 , pady =16 , bd=8, text = "OFF",fg = "black",command= root.quit) b8.pack(side = LEFT) root.mainloop()
mit
bbc/kamaelia
Sketches/MH/RTP/RTPMux.py
3
5090
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from Kamaelia.Chassis.Pipeline import Pipeline #from Multicast_transceiver import Multicast_transceiver from Multicast_transceiver_threaded import Multicast_transceiver #from Kamaelia.Protocol.SimpleReliableMulticast import RecoverOrder from Kamaelia.File.Writing import SimpleFileWriter from Kamaelia.Util.Detuple import SimpleDetupler from Kamaelia.Util.Console import ConsoleEchoer import sys; sys.path.append("../DVB_Remuxing/") from ExtractPCR import AlignTSPackets from RTP import RTPFramer from RTP import RTPDeframer from Kamaelia.Util.Backplane import Backplane, SubscribeTo, PublishTo from Axon.Component import component from SDP import SDPParser from Kamaelia.Chassis.Carousel import Carousel from Kamaelia.Chassis.Graphline import Graphline from RecoverOrder import RecoverOrder from Kamaelia.Device.DVB.SoftDemux import DVB_SoftDemuxer import time import random import sys sys.path.append("../MobileReframe") from OneShot import OneShot from chunks_to_lines import chunks_to_lines from Kamaelia.Protocol.HTTP.HTTPClient import SimpleHTTPClient from Kamaelia.Util.PureTransformer import PureTransformer from Kamaelia.Chassis.Pipeline import Pipeline def GetRTPAddressFromSDP(sdp_url): return \ Pipeline( OneShot(sdp_url), SimpleHTTPClient(), chunks_to_lines(), SDPParser(), PureTransformer(lambda session : \ (session["connection"][2], session["media"][0]["media"][1]) ), ) class GroupTSPackets(component): def main(self): p=[] while 1: while self.dataReady("inbox"): p.append(self.recv("inbox")) if len(p)==7: self.send( "".join(p), "outbox") p=[] self.pause() yield 1 class PrepForRTP(component): def main(self): starttime = time.time() ssrc = random.randint(0,(2**32) - 1) while 1: while self.dataReady("inbox"): payload=self.recv("inbox") timestamp = (time.time() - starttime) * 90000 packet = { 'payloadtype' : 33, # MPEG 2 TS 'payload' : payload, 'timestamp' : int(timestamp), 'ssrc' : ssrc, } self.send(packet, "outbox") self.pause() yield 1 pidfilter = {} for i in range(0,0x2000): pidfilter[i] = ["outbox"] class DetectGap(component): def main(self): while not self.dataReady("inbox"): self.pause() yield 1 data = self.recv("inbox") self.send(data,"outbox") next = (data[0]+1)&0xffff while 1: while self.dataReady("inbox"): data = self.recv("inbox") if data[0] != next: print "Gap size %d going to %d\n" % (data[0]-next,data[0]) next=(data[0]+1)&0xffff self.send(data,"outbox") self.pause() yield 1 #sdp_url = "http://support.bbc.co.uk/multicast/sdp/bbcone-avc.sdp" sdp_url = "http://support.bbc.co.uk/multicast/sdp/bbcone-mpeg2.sdp" Pipeline( Graphline( SDP = GetRTPAddressFromSDP(sdp_url), GET = Carousel(lambda (host,port): Multicast_transceiver("0.0.0.0",port,host,0)), linkages = { ("SDP","outbox") : ("GET","next"), ("GET","outbox") : ("","outbox"), ("GET","signal") : ("","signal"), } ), # SimpleDetupler(1), RTPDeframer(), RecoverOrder(bufsize=64, modulo=65536), DetectGap(), SimpleDetupler(1), SimpleDetupler("payload"), # AlignTSPackets(), DVB_SoftDemuxer(pidfilter), # PublishTo("TS PACKETS"), # ).activate() # #Pipeline( SubscribeTo("TS PACKETS"), GroupTSPackets(), PrepForRTP(), RTPFramer(), Multicast_transceiver("0.0.0.0", 0, "224.168.2.9", 1600) # ).activate() ).run() #Backplane("TS PACKETS").run()
apache-2.0
christophlsa/odoo
addons/product/product.py
21
68721
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import math import re import time from _common import ceiling from openerp import SUPERUSER_ID from openerp import tools from openerp.osv import osv, fields, expression from openerp.tools.translate import _ from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT import psycopg2 import openerp.addons.decimal_precision as dp from openerp.tools.float_utils import float_round, float_compare def ean_checksum(eancode): """returns the checksum of an ean string of length 13, returns -1 if the string has the wrong length""" if len(eancode) != 13: return -1 oddsum=0 evensum=0 total=0 eanvalue=eancode reversevalue = eanvalue[::-1] finalean=reversevalue[1:] for i in range(len(finalean)): if i % 2 == 0: oddsum += int(finalean[i]) else: evensum += int(finalean[i]) total=(oddsum * 3) + evensum check = int(10 - math.ceil(total % 10.0)) %10 return check def check_ean(eancode): """returns True if eancode is a valid ean13 string, or null""" if not eancode: return True if len(eancode) != 13: return False try: int(eancode) except: return False return ean_checksum(eancode) == int(eancode[-1]) def sanitize_ean13(ean13): """Creates and returns a valid ean13 from an invalid one""" if not ean13: return "0000000000000" ean13 = re.sub("[A-Za-z]","0",ean13); ean13 = re.sub("[^0-9]","",ean13); ean13 = ean13[:13] if len(ean13) < 13: ean13 = ean13 + '0' * (13-len(ean13)) return ean13[:-1] + str(ean_checksum(ean13)) #---------------------------------------------------------- # UOM #---------------------------------------------------------- class product_uom_categ(osv.osv): _name = 'product.uom.categ' _description = 'Product uom categ' _columns = { 'name': fields.char('Name', required=True, translate=True), } class product_uom(osv.osv): _name = 'product.uom' _description = 'Product Unit of Measure' def _compute_factor_inv(self, factor): return factor and (1.0 / factor) or 0.0 def _factor_inv(self, cursor, user, ids, name, arg, context=None): res = {} for uom in self.browse(cursor, user, ids, context=context): res[uom.id] = self._compute_factor_inv(uom.factor) return res def _factor_inv_write(self, cursor, user, id, name, value, arg, context=None): return self.write(cursor, user, id, {'factor': self._compute_factor_inv(value)}, context=context) def name_create(self, cr, uid, name, context=None): """ The UoM category and factor are required, so we'll have to add temporary values for imported UoMs """ uom_categ = self.pool.get('product.uom.categ') # look for the category based on the english name, i.e. no context on purpose! # TODO: should find a way to have it translated but not created until actually used categ_misc = 'Unsorted/Imported Units' categ_id = uom_categ.search(cr, uid, [('name', '=', categ_misc)]) if categ_id: categ_id = categ_id[0] else: categ_id, _ = uom_categ.name_create(cr, uid, categ_misc) uom_id = self.create(cr, uid, {self._rec_name: name, 'category_id': categ_id, 'factor': 1}) return self.name_get(cr, uid, [uom_id], context=context)[0] def create(self, cr, uid, data, context=None): if 'factor_inv' in data: if data['factor_inv'] != 1: data['factor'] = self._compute_factor_inv(data['factor_inv']) del(data['factor_inv']) return super(product_uom, self).create(cr, uid, data, context) _order = "name" _columns = { 'name': fields.char('Unit of Measure', required=True, translate=True), 'category_id': fields.many2one('product.uom.categ', 'Unit of Measure Category', required=True, ondelete='cascade', help="Conversion between Units of Measure can only occur if they belong to the same category. The conversion will be made based on the ratios."), 'factor': fields.float('Ratio', required=True, digits=0, # force NUMERIC with unlimited precision help='How much bigger or smaller this unit is compared to the reference Unit of Measure for this category:\n'\ '1 * (reference unit) = ratio * (this unit)'), 'factor_inv': fields.function(_factor_inv, digits=0, # force NUMERIC with unlimited precision fnct_inv=_factor_inv_write, string='Bigger Ratio', help='How many times this Unit of Measure is bigger than the reference Unit of Measure in this category:\n'\ '1 * (this unit) = ratio * (reference unit)', required=True), 'rounding': fields.float('Rounding Precision', digits=0, required=True, help="The computed quantity will be a multiple of this value. "\ "Use 1.0 for a Unit of Measure that cannot be further split, such as a piece."), 'active': fields.boolean('Active', help="By unchecking the active field you can disable a unit of measure without deleting it."), 'uom_type': fields.selection([('bigger','Bigger than the reference Unit of Measure'), ('reference','Reference Unit of Measure for this category'), ('smaller','Smaller than the reference Unit of Measure')],'Type', required=1), } _defaults = { 'active': 1, 'rounding': 0.01, 'factor': 1, 'uom_type': 'reference', 'factor': 1.0, } _sql_constraints = [ ('factor_gt_zero', 'CHECK (factor!=0)', 'The conversion ratio for a unit of measure cannot be 0!') ] def _compute_qty(self, cr, uid, from_uom_id, qty, to_uom_id=False, round=True, rounding_method='UP'): if not from_uom_id or not qty or not to_uom_id: return qty uoms = self.browse(cr, uid, [from_uom_id, to_uom_id]) if uoms[0].id == from_uom_id: from_unit, to_unit = uoms[0], uoms[-1] else: from_unit, to_unit = uoms[-1], uoms[0] return self._compute_qty_obj(cr, uid, from_unit, qty, to_unit, round=round, rounding_method=rounding_method) def _compute_qty_obj(self, cr, uid, from_unit, qty, to_unit, round=True, rounding_method='UP', context=None): if context is None: context = {} if from_unit.category_id.id != to_unit.category_id.id: if context.get('raise-exception', True): raise osv.except_osv(_('Error!'), _('Conversion from Product UoM %s to Default UoM %s is not possible as they both belong to different Category!.') % (from_unit.name,to_unit.name,)) else: return qty amount = qty/from_unit.factor if to_unit: amount = amount * to_unit.factor if round: amount = float_round(amount, precision_rounding=to_unit.rounding, rounding_method=rounding_method) return amount def _compute_price(self, cr, uid, from_uom_id, price, to_uom_id=False): if (not from_uom_id or not price or not to_uom_id or (to_uom_id == from_uom_id)): return price from_unit, to_unit = self.browse(cr, uid, [from_uom_id, to_uom_id]) if from_unit.category_id.id != to_unit.category_id.id: return price amount = price * from_unit.factor if to_uom_id: amount = amount / to_unit.factor return amount def onchange_type(self, cursor, user, ids, value): if value == 'reference': return {'value': {'factor': 1, 'factor_inv': 1}} return {} def write(self, cr, uid, ids, vals, context=None): if isinstance(ids, (int, long)): ids = [ids] if 'category_id' in vals: for uom in self.browse(cr, uid, ids, context=context): if uom.category_id.id != vals['category_id']: raise osv.except_osv(_('Warning!'),_("Cannot change the category of existing Unit of Measure '%s'.") % (uom.name,)) return super(product_uom, self).write(cr, uid, ids, vals, context=context) class product_ul(osv.osv): _name = "product.ul" _description = "Logistic Unit" _columns = { 'name' : fields.char('Name', select=True, required=True, translate=True), 'type' : fields.selection([('unit','Unit'),('pack','Pack'),('box', 'Box'), ('pallet', 'Pallet')], 'Type', required=True), 'height': fields.float('Height', help='The height of the package'), 'width': fields.float('Width', help='The width of the package'), 'length': fields.float('Length', help='The length of the package'), 'weight': fields.float('Empty Package Weight'), } #---------------------------------------------------------- # Categories #---------------------------------------------------------- class product_category(osv.osv): def name_get(self, cr, uid, ids, context=None): if isinstance(ids, (list, tuple)) and not len(ids): return [] if isinstance(ids, (long, int)): ids = [ids] reads = self.read(cr, uid, ids, ['name','parent_id'], context=context) res = [] for record in reads: name = record['name'] if record['parent_id']: name = record['parent_id'][1]+' / '+name res.append((record['id'], name)) return res def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100): if not args: args = [] if not context: context = {} if name: # Be sure name_search is symetric to name_get categories = name.split(' / ') parents = list(categories) child = parents.pop() domain = [('name', operator, child)] if parents: names_ids = self.name_search(cr, uid, ' / '.join(parents), args=args, operator='ilike', context=context, limit=limit) category_ids = [name_id[0] for name_id in names_ids] if operator in expression.NEGATIVE_TERM_OPERATORS: category_ids = self.search(cr, uid, [('id', 'not in', category_ids)]) domain = expression.OR([[('parent_id', 'in', category_ids)], domain]) else: domain = expression.AND([[('parent_id', 'in', category_ids)], domain]) for i in range(1, len(categories)): domain = [[('name', operator, ' / '.join(categories[-1 - i:]))], domain] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = expression.AND(domain) else: domain = expression.OR(domain) ids = self.search(cr, uid, expression.AND([domain, args]), limit=limit, context=context) else: ids = self.search(cr, uid, args, limit=limit, context=context) return self.name_get(cr, uid, ids, context) def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None): res = self.name_get(cr, uid, ids, context=context) return dict(res) _name = "product.category" _description = "Product Category" _columns = { 'name': fields.char('Name', required=True, translate=True, select=True), 'complete_name': fields.function(_name_get_fnc, type="char", string='Name'), 'parent_id': fields.many2one('product.category','Parent Category', select=True, ondelete='cascade'), 'child_id': fields.one2many('product.category', 'parent_id', string='Child Categories'), 'sequence': fields.integer('Sequence', select=True, help="Gives the sequence order when displaying a list of product categories."), 'type': fields.selection([('view','View'), ('normal','Normal')], 'Category Type', help="A category of the view type is a virtual category that can be used as the parent of another category to create a hierarchical structure."), 'parent_left': fields.integer('Left Parent', select=1), 'parent_right': fields.integer('Right Parent', select=1), } _defaults = { 'type' : 'normal', } _parent_name = "parent_id" _parent_store = True _parent_order = 'sequence, name' _order = 'parent_left' _constraints = [ (osv.osv._check_recursion, 'Error ! You cannot create recursive categories.', ['parent_id']) ] class produce_price_history(osv.osv): """ Keep track of the ``product.template`` standard prices as they are changed. """ _name = 'product.price.history' _rec_name = 'datetime' _order = 'datetime desc' _columns = { 'company_id': fields.many2one('res.company', required=True), 'product_template_id': fields.many2one('product.template', 'Product Template', required=True, ondelete='cascade'), 'datetime': fields.datetime('Historization Time'), 'cost': fields.float('Historized Cost'), } def _get_default_company(self, cr, uid, context=None): if 'force_company' in context: return context['force_company'] else: company = self.pool['res.users'].browse(cr, uid, uid, context=context).company_id return company.id if company else False _defaults = { 'datetime': fields.datetime.now, 'company_id': _get_default_company, } #---------------------------------------------------------- # Product Attributes #---------------------------------------------------------- class product_attribute(osv.osv): _name = "product.attribute" _description = "Product Attribute" _columns = { 'name': fields.char('Name', translate=True, required=True), 'value_ids': fields.one2many('product.attribute.value', 'attribute_id', 'Values', copy=True), } class product_attribute_value(osv.osv): _name = "product.attribute.value" _order = 'sequence' def _get_price_extra(self, cr, uid, ids, name, args, context=None): result = dict.fromkeys(ids, 0) if not context.get('active_id'): return result for obj in self.browse(cr, uid, ids, context=context): for price_id in obj.price_ids: if price_id.product_tmpl_id.id == context.get('active_id'): result[obj.id] = price_id.price_extra break return result def _set_price_extra(self, cr, uid, id, name, value, args, context=None): if context is None: context = {} if 'active_id' not in context: return None p_obj = self.pool['product.attribute.price'] p_ids = p_obj.search(cr, uid, [('value_id', '=', id), ('product_tmpl_id', '=', context['active_id'])], context=context) if p_ids: p_obj.write(cr, uid, p_ids, {'price_extra': value}, context=context) else: p_obj.create(cr, uid, { 'product_tmpl_id': context['active_id'], 'value_id': id, 'price_extra': value, }, context=context) def name_get(self, cr, uid, ids, context=None): if context and not context.get('show_attribute', True): return super(product_attribute_value, self).name_get(cr, uid, ids, context=context) res = [] for value in self.browse(cr, uid, ids, context=context): res.append([value.id, "%s: %s" % (value.attribute_id.name, value.name)]) return res _columns = { 'sequence': fields.integer('Sequence', help="Determine the display order"), 'name': fields.char('Value', translate=True, required=True), 'attribute_id': fields.many2one('product.attribute', 'Attribute', required=True, ondelete='cascade'), 'product_ids': fields.many2many('product.product', id1='att_id', id2='prod_id', string='Variants', readonly=True), 'price_extra': fields.function(_get_price_extra, type='float', string='Attribute Price Extra', fnct_inv=_set_price_extra, digits_compute=dp.get_precision('Product Price'), help="Price Extra: Extra price for the variant with this attribute value on sale price. eg. 200 price extra, 1000 + 200 = 1200."), 'price_ids': fields.one2many('product.attribute.price', 'value_id', string='Attribute Prices', readonly=True), } _sql_constraints = [ ('value_company_uniq', 'unique (name,attribute_id)', 'This attribute value already exists !') ] _defaults = { 'price_extra': 0.0, } def unlink(self, cr, uid, ids, context=None): ctx = dict(context or {}, active_test=False) product_ids = self.pool['product.product'].search(cr, uid, [('attribute_value_ids', 'in', ids)], context=ctx) if product_ids: raise osv.except_osv(_('Integrity Error!'), _('The operation cannot be completed:\nYou trying to delete an attribute value with a reference on a product variant.')) return super(product_attribute_value, self).unlink(cr, uid, ids, context=context) class product_attribute_price(osv.osv): _name = "product.attribute.price" _columns = { 'product_tmpl_id': fields.many2one('product.template', 'Product Template', required=True, ondelete='cascade'), 'value_id': fields.many2one('product.attribute.value', 'Product Attribute Value', required=True, ondelete='cascade'), 'price_extra': fields.float('Price Extra', digits_compute=dp.get_precision('Product Price')), } class product_attribute_line(osv.osv): _name = "product.attribute.line" _rec_name = 'attribute_id' _columns = { 'product_tmpl_id': fields.many2one('product.template', 'Product Template', required=True, ondelete='cascade'), 'attribute_id': fields.many2one('product.attribute', 'Attribute', required=True, ondelete='restrict'), 'value_ids': fields.many2many('product.attribute.value', id1='line_id', id2='val_id', string='Product Attribute Value'), } #---------------------------------------------------------- # Products #---------------------------------------------------------- class product_template(osv.osv): _name = "product.template" _inherit = ['mail.thread'] _description = "Product Template" _order = "name" def _get_image(self, cr, uid, ids, name, args, context=None): result = dict.fromkeys(ids, False) for obj in self.browse(cr, uid, ids, context=context): result[obj.id] = tools.image_get_resized_images(obj.image, avoid_resize_medium=True) return result def _set_image(self, cr, uid, id, name, value, args, context=None): return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context) def _is_product_variant(self, cr, uid, ids, name, arg, context=None): return self._is_product_variant_impl(cr, uid, ids, name, arg, context=context) def _is_product_variant_impl(self, cr, uid, ids, name, arg, context=None): return dict.fromkeys(ids, False) def _product_template_price(self, cr, uid, ids, name, arg, context=None): plobj = self.pool.get('product.pricelist') res = {} quantity = context.get('quantity') or 1.0 pricelist = context.get('pricelist', False) partner = context.get('partner', False) if pricelist: # Support context pricelists specified as display_name or ID for compatibility if isinstance(pricelist, basestring): pricelist_ids = plobj.name_search( cr, uid, pricelist, operator='=', context=context, limit=1) pricelist = pricelist_ids[0][0] if pricelist_ids else pricelist if isinstance(pricelist, (int, long)): products = self.browse(cr, uid, ids, context=context) qtys = map(lambda x: (x, quantity, partner), products) pl = plobj.browse(cr, uid, pricelist, context=context) price = plobj._price_get_multi(cr,uid, pl, qtys, context=context) for id in ids: res[id] = price.get(id, 0.0) for id in ids: res.setdefault(id, 0.0) return res def get_history_price(self, cr, uid, product_tmpl, company_id, date=None, context=None): if context is None: context = {} if date is None: date = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT) price_history_obj = self.pool.get('product.price.history') history_ids = price_history_obj.search(cr, uid, [('company_id', '=', company_id), ('product_template_id', '=', product_tmpl), ('datetime', '<=', date)], limit=1) if history_ids: return price_history_obj.read(cr, uid, history_ids[0], ['cost'], context=context)['cost'] return 0.0 def _set_standard_price(self, cr, uid, product_tmpl_id, value, context=None): ''' Store the standard price change in order to be able to retrieve the cost of a product template for a given date''' if context is None: context = {} price_history_obj = self.pool['product.price.history'] user_company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id company_id = context.get('force_company', user_company) price_history_obj.create(cr, uid, { 'product_template_id': product_tmpl_id, 'cost': value, 'company_id': company_id, }, context=context) def _get_product_variant_count(self, cr, uid, ids, name, arg, context=None): res = {} for product in self.browse(cr, uid, ids, context=context): res[product.id] = len(product.product_variant_ids) return res _columns = { 'name': fields.char('Name', required=True, translate=True, select=True), 'product_manager': fields.many2one('res.users','Product Manager'), 'description': fields.text('Description',translate=True, help="A precise description of the Product, used only for internal information purposes."), 'description_purchase': fields.text('Purchase Description',translate=True, help="A description of the Product that you want to communicate to your suppliers. " "This description will be copied to every Purchase Order, Receipt and Supplier Invoice/Refund."), 'description_sale': fields.text('Sale Description',translate=True, help="A description of the Product that you want to communicate to your customers. " "This description will be copied to every Sale Order, Delivery Order and Customer Invoice/Refund"), 'type': fields.selection([('consu', 'Consumable'),('service','Service')], 'Product Type', required=True, help="Consumable are product where you don't manage stock, a service is a non-material product provided by a company or an individual."), 'rental': fields.boolean('Can be Rent'), 'categ_id': fields.many2one('product.category','Internal Category', required=True, change_default=True, domain="[('type','=','normal')]" ,help="Select category for the current product"), 'price': fields.function(_product_template_price, type='float', string='Price', digits_compute=dp.get_precision('Product Price')), 'list_price': fields.float('Sale Price', digits_compute=dp.get_precision('Product Price'), help="Base price to compute the customer price. Sometimes called the catalog price."), 'lst_price' : fields.related('list_price', type="float", string='Public Price', digits_compute=dp.get_precision('Product Price')), 'standard_price': fields.property(type = 'float', digits_compute=dp.get_precision('Product Price'), help="Cost price of the product template used for standard stock valuation in accounting and used as a base price on purchase orders. " "Expressed in the default unit of measure of the product.", groups="base.group_user", string="Cost Price"), 'volume': fields.float('Volume', help="The volume in m3."), 'weight': fields.float('Gross Weight', digits_compute=dp.get_precision('Stock Weight'), help="The gross weight in Kg."), 'weight_net': fields.float('Net Weight', digits_compute=dp.get_precision('Stock Weight'), help="The net weight in Kg."), 'warranty': fields.float('Warranty'), 'sale_ok': fields.boolean('Can be Sold', help="Specify if the product can be selected in a sales order line."), 'pricelist_id': fields.dummy(string='Pricelist', relation='product.pricelist', type='many2one'), 'state': fields.selection([('',''), ('draft', 'In Development'), ('sellable','Normal'), ('end','End of Lifecycle'), ('obsolete','Obsolete')], 'Status'), 'uom_id': fields.many2one('product.uom', 'Unit of Measure', required=True, help="Default Unit of Measure used for all stock operation."), 'uom_po_id': fields.many2one('product.uom', 'Purchase Unit of Measure', required=True, help="Default Unit of Measure used for purchase orders. It must be in the same category than the default unit of measure."), 'uos_id' : fields.many2one('product.uom', 'Unit of Sale', help='Specify a unit of measure here if invoicing is made in another unit of measure than inventory. Keep empty to use the default unit of measure.'), 'uos_coeff': fields.float('Unit of Measure -> UOS Coeff', digits_compute= dp.get_precision('Product UoS'), help='Coefficient to convert default Unit of Measure to Unit of Sale\n' ' uos = uom * coeff'), 'mes_type': fields.selection((('fixed', 'Fixed'), ('variable', 'Variable')), 'Measure Type'), 'company_id': fields.many2one('res.company', 'Company', select=1), # image: all image fields are base64 encoded and PIL-supported 'image': fields.binary("Image", help="This field holds the image used as image for the product, limited to 1024x1024px."), 'image_medium': fields.function(_get_image, fnct_inv=_set_image, string="Medium-sized image", type="binary", multi="_get_image", store={ 'product.template': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10), }, help="Medium-sized image of the product. It is automatically "\ "resized as a 128x128px image, with aspect ratio preserved, "\ "only when the image exceeds one of those sizes. Use this field in form views or some kanban views."), 'image_small': fields.function(_get_image, fnct_inv=_set_image, string="Small-sized image", type="binary", multi="_get_image", store={ 'product.template': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10), }, help="Small-sized image of the product. It is automatically "\ "resized as a 64x64px image, with aspect ratio preserved. "\ "Use this field anywhere a small image is required."), 'packaging_ids': fields.one2many( 'product.packaging', 'product_tmpl_id', 'Logistical Units', help="Gives the different ways to package the same product. This has no impact on " "the picking order and is mainly used if you use the EDI module."), 'seller_ids': fields.one2many('product.supplierinfo', 'product_tmpl_id', 'Supplier'), 'seller_delay': fields.related('seller_ids','delay', type='integer', string='Supplier Lead Time', help="This is the average delay in days between the purchase order confirmation and the receipts for this product and for the default supplier. It is used by the scheduler to order requests based on reordering delays."), 'seller_qty': fields.related('seller_ids','qty', type='float', string='Supplier Quantity', help="This is minimum quantity to purchase from Main Supplier."), 'seller_id': fields.related('seller_ids','name', type='many2one', relation='res.partner', string='Main Supplier', help="Main Supplier who has highest priority in Supplier List."), 'active': fields.boolean('Active', help="If unchecked, it will allow you to hide the product without removing it."), 'color': fields.integer('Color Index'), 'is_product_variant': fields.function( _is_product_variant, type='boolean', string='Is product variant'), 'attribute_line_ids': fields.one2many('product.attribute.line', 'product_tmpl_id', 'Product Attributes'), 'product_variant_ids': fields.one2many('product.product', 'product_tmpl_id', 'Products', required=True), 'product_variant_count': fields.function( _get_product_variant_count, type='integer', string='# of Product Variants'), # related to display product product information if is_product_variant 'ean13': fields.related('product_variant_ids', 'ean13', type='char', string='EAN13 Barcode'), 'default_code': fields.related('product_variant_ids', 'default_code', type='char', string='Internal Reference'), } def _price_get_list_price(self, product): return 0.0 def _price_get(self, cr, uid, products, ptype='list_price', context=None): if context is None: context = {} if 'currency_id' in context: pricetype_obj = self.pool.get('product.price.type') price_type_id = pricetype_obj.search(cr, uid, [('field','=',ptype)])[0] price_type_currency_id = pricetype_obj.browse(cr,uid,price_type_id).currency_id.id res = {} product_uom_obj = self.pool.get('product.uom') for product in products: # standard_price field can only be seen by users in base.group_user # Thus, in order to compute the sale price from the cost price for users not in this group # We fetch the standard price as the superuser if ptype != 'standard_price': res[product.id] = product[ptype] or 0.0 else: company_id = product.env.user.company_id.id product = product.with_context(force_company=company_id) res[product.id] = res[product.id] = product.sudo()[ptype] if ptype == 'list_price': res[product.id] += product._name == "product.product" and product.price_extra or 0.0 if 'uom' in context: uom = product.uom_id or product.uos_id res[product.id] = product_uom_obj._compute_price(cr, uid, uom.id, res[product.id], context['uom']) # Convert from price_type currency to asked one if 'currency_id' in context: # Take the price_type currency from the product field # This is right cause a field cannot be in more than one currency res[product.id] = self.pool.get('res.currency').compute(cr, uid, price_type_currency_id, context['currency_id'], res[product.id],context=context) return res def _get_uom_id(self, cr, uid, *args): return self.pool["product.uom"].search(cr, uid, [], limit=1, order='id')[0] def _default_category(self, cr, uid, context=None): if context is None: context = {} if 'categ_id' in context and context['categ_id']: return context['categ_id'] md = self.pool.get('ir.model.data') res = False try: res = md.get_object_reference(cr, uid, 'product', 'product_category_all')[1] except ValueError: res = False return res def onchange_type(self, cr, uid, ids, type): return {} def onchange_uom(self, cursor, user, ids, uom_id, uom_po_id): if uom_id: return {'value': {'uom_po_id': uom_id}} return {} def create_variant_ids(self, cr, uid, ids, context=None): product_obj = self.pool.get("product.product") ctx = context and context.copy() or {} if ctx.get("create_product_variant"): return None ctx.update(active_test=False, create_product_variant=True) tmpl_ids = self.browse(cr, uid, ids, context=ctx) for tmpl_id in tmpl_ids: # list of values combination variant_alone = [] all_variants = [[]] for variant_id in tmpl_id.attribute_line_ids: if len(variant_id.value_ids) == 1: variant_alone.append(variant_id.value_ids[0]) temp_variants = [] for variant in all_variants: for value_id in variant_id.value_ids: temp_variants.append(sorted(variant + [int(value_id)])) if temp_variants: all_variants = temp_variants # adding an attribute with only one value should not recreate product # write this attribute on every product to make sure we don't lose them for variant_id in variant_alone: product_ids = [] for product_id in tmpl_id.product_variant_ids: if variant_id.id not in map(int, product_id.attribute_value_ids): product_ids.append(product_id.id) product_obj.write(cr, uid, product_ids, {'attribute_value_ids': [(4, variant_id.id)]}, context=ctx) # check product variant_ids_to_active = [] variants_active_ids = [] variants_inactive = [] for product_id in tmpl_id.product_variant_ids: variants = sorted(map(int,product_id.attribute_value_ids)) if variants in all_variants: variants_active_ids.append(product_id.id) all_variants.pop(all_variants.index(variants)) if not product_id.active: variant_ids_to_active.append(product_id.id) else: variants_inactive.append(product_id) if variant_ids_to_active: product_obj.write(cr, uid, variant_ids_to_active, {'active': True}, context=ctx) # create new product for variant_ids in all_variants: values = { 'product_tmpl_id': tmpl_id.id, 'attribute_value_ids': [(6, 0, variant_ids)] } id = product_obj.create(cr, uid, values, context=ctx) variants_active_ids.append(id) # unlink or inactive product for variant_id in map(int,variants_inactive): try: with cr.savepoint(): product_obj.unlink(cr, uid, [variant_id], context=ctx) except (psycopg2.Error, osv.except_osv): product_obj.write(cr, uid, [variant_id], {'active': False}, context=ctx) pass return True def create(self, cr, uid, vals, context=None): ''' Store the initial standard price in order to be able to retrieve the cost of a product template for a given date''' product_template_id = super(product_template, self).create(cr, uid, vals, context=context) if not context or "create_product_product" not in context: self.create_variant_ids(cr, uid, [product_template_id], context=context) self._set_standard_price(cr, uid, product_template_id, vals.get('standard_price', 0.0), context=context) # TODO: this is needed to set given values to first variant after creation # these fields should be moved to product as lead to confusion related_vals = {} if vals.get('ean13'): related_vals['ean13'] = vals['ean13'] if vals.get('default_code'): related_vals['default_code'] = vals['default_code'] if related_vals: self.write(cr, uid, product_template_id, related_vals, context=context) return product_template_id def write(self, cr, uid, ids, vals, context=None): ''' Store the standard price change in order to be able to retrieve the cost of a product template for a given date''' if isinstance(ids, (int, long)): ids = [ids] if 'uom_po_id' in vals: new_uom = self.pool.get('product.uom').browse(cr, uid, vals['uom_po_id'], context=context) for product in self.browse(cr, uid, ids, context=context): old_uom = product.uom_po_id if old_uom.category_id.id != new_uom.category_id.id: raise osv.except_osv(_('Unit of Measure categories Mismatch!'), _("New Unit of Measure '%s' must belong to same Unit of Measure category '%s' as of old Unit of Measure '%s'. If you need to change the unit of measure, you may deactivate this product from the 'Procurements' tab and create a new one.") % (new_uom.name, old_uom.category_id.name, old_uom.name,)) if 'standard_price' in vals: for prod_template_id in ids: self._set_standard_price(cr, uid, prod_template_id, vals['standard_price'], context=context) res = super(product_template, self).write(cr, uid, ids, vals, context=context) if 'attribute_line_ids' in vals or vals.get('active'): self.create_variant_ids(cr, uid, ids, context=context) if 'active' in vals and not vals.get('active'): ctx = context and context.copy() or {} ctx.update(active_test=False) product_ids = [] for product in self.browse(cr, uid, ids, context=ctx): product_ids = map(int,product.product_variant_ids) self.pool.get("product.product").write(cr, uid, product_ids, {'active': vals.get('active')}, context=ctx) return res def copy(self, cr, uid, id, default=None, context=None): if default is None: default = {} template = self.browse(cr, uid, id, context=context) default['name'] = _("%s (copy)") % (template['name']) return super(product_template, self).copy(cr, uid, id, default=default, context=context) _defaults = { 'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'product.template', context=c), 'list_price': 1, 'standard_price': 0.0, 'sale_ok': 1, 'uom_id': _get_uom_id, 'uom_po_id': _get_uom_id, 'uos_coeff': 1.0, 'mes_type': 'fixed', 'categ_id' : _default_category, 'type' : 'consu', 'active': True, } def _check_uom(self, cursor, user, ids, context=None): for product in self.browse(cursor, user, ids, context=context): if product.uom_id.category_id.id != product.uom_po_id.category_id.id: return False return True def _check_uos(self, cursor, user, ids, context=None): for product in self.browse(cursor, user, ids, context=context): if product.uos_id \ and product.uos_id.category_id.id \ == product.uom_id.category_id.id: return False return True _constraints = [ (_check_uom, 'Error: The default Unit of Measure and the purchase Unit of Measure must be in the same category.', ['uom_id']), ] def name_get(self, cr, user, ids, context=None): if context is None: context = {} if 'partner_id' in context: pass return super(product_template, self).name_get(cr, user, ids, context) def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100): # Only use the product.product heuristics if there is a search term and the domain # does not specify a match on `product.template` IDs. if not name or any(term[0] == 'id' for term in (args or [])): return super(product_template, self).name_search( cr, user, name=name, args=args, operator=operator, context=context, limit=limit) product_product = self.pool['product.product'] results = product_product.name_search( cr, user, name, args, operator=operator, context=context, limit=limit) product_ids = [p[0] for p in results] template_ids = [p.product_tmpl_id.id for p in product_product.browse( cr, user, product_ids, context=context)] # re-apply product.template order + name_get return super(product_template, self).name_search( cr, user, '', args=[('id', 'in', template_ids)], operator='ilike', context=context, limit=limit) class product_product(osv.osv): _name = "product.product" _description = "Product" _inherits = {'product.template': 'product_tmpl_id'} _inherit = ['mail.thread'] _order = 'default_code,name_template' def _product_price(self, cr, uid, ids, name, arg, context=None): plobj = self.pool.get('product.pricelist') res = {} if context is None: context = {} quantity = context.get('quantity') or 1.0 pricelist = context.get('pricelist', False) partner = context.get('partner', False) if pricelist: # Support context pricelists specified as display_name or ID for compatibility if isinstance(pricelist, basestring): pricelist_ids = plobj.name_search( cr, uid, pricelist, operator='=', context=context, limit=1) pricelist = pricelist_ids[0][0] if pricelist_ids else pricelist if isinstance(pricelist, (int, long)): products = self.browse(cr, uid, ids, context=context) qtys = map(lambda x: (x, quantity, partner), products) pl = plobj.browse(cr, uid, pricelist, context=context) price = plobj._price_get_multi(cr,uid, pl, qtys, context=context) for id in ids: res[id] = price.get(id, 0.0) for id in ids: res.setdefault(id, 0.0) return res def view_header_get(self, cr, uid, view_id, view_type, context=None): if context is None: context = {} res = super(product_product, self).view_header_get(cr, uid, view_id, view_type, context) if (context.get('categ_id', False)): return _('Products: ') + self.pool.get('product.category').browse(cr, uid, context['categ_id'], context=context).name return res def _product_lst_price(self, cr, uid, ids, name, arg, context=None): product_uom_obj = self.pool.get('product.uom') res = dict.fromkeys(ids, 0.0) for product in self.browse(cr, uid, ids, context=context): if 'uom' in context: uom = product.uos_id or product.uom_id res[product.id] = product_uom_obj._compute_price(cr, uid, uom.id, product.list_price, context['uom']) else: res[product.id] = product.list_price res[product.id] = res[product.id] + product.price_extra return res def _set_product_lst_price(self, cr, uid, id, name, value, args, context=None): product_uom_obj = self.pool.get('product.uom') product = self.browse(cr, uid, id, context=context) if 'uom' in context: uom = product.uos_id or product.uom_id value = product_uom_obj._compute_price(cr, uid, context['uom'], value, uom.id) value = value - product.price_extra return product.write({'list_price': value}) def _get_partner_code_name(self, cr, uid, ids, product, partner_id, context=None): for supinfo in product.seller_ids: if supinfo.name.id == partner_id: return {'code': supinfo.product_code or product.default_code, 'name': supinfo.product_name or product.name} res = {'code': product.default_code, 'name': product.name} return res def _product_code(self, cr, uid, ids, name, arg, context=None): res = {} if context is None: context = {} for p in self.browse(cr, uid, ids, context=context): res[p.id] = self._get_partner_code_name(cr, uid, [], p, context.get('partner_id', None), context=context)['code'] return res def _product_partner_ref(self, cr, uid, ids, name, arg, context=None): res = {} if context is None: context = {} for p in self.browse(cr, uid, ids, context=context): data = self._get_partner_code_name(cr, uid, [], p, context.get('partner_id', None), context=context) if not data['code']: data['code'] = p.code if not data['name']: data['name'] = p.name res[p.id] = (data['code'] and ('['+data['code']+'] ') or '') + (data['name'] or '') return res def _is_product_variant_impl(self, cr, uid, ids, name, arg, context=None): return dict.fromkeys(ids, True) def _get_name_template_ids(self, cr, uid, ids, context=None): template_ids = self.pool.get('product.product').search(cr, uid, [('product_tmpl_id', 'in', ids)]) return list(set(template_ids)) def _get_image_variant(self, cr, uid, ids, name, args, context=None): result = dict.fromkeys(ids, False) for obj in self.browse(cr, uid, ids, context=context): result[obj.id] = obj.image_variant or getattr(obj.product_tmpl_id, name) return result def _set_image_variant(self, cr, uid, id, name, value, args, context=None): image = tools.image_resize_image_big(value) res = self.write(cr, uid, [id], {'image_variant': image}, context=context) product = self.browse(cr, uid, id, context=context) if not product.product_tmpl_id.image: product.write({'image_variant': None}) product.product_tmpl_id.write({'image': image}) return res def _get_price_extra(self, cr, uid, ids, name, args, context=None): result = dict.fromkeys(ids, False) for product in self.browse(cr, uid, ids, context=context): price_extra = 0.0 for variant_id in product.attribute_value_ids: for price_id in variant_id.price_ids: if price_id.product_tmpl_id.id == product.product_tmpl_id.id: price_extra += price_id.price_extra result[product.id] = price_extra return result _columns = { 'price': fields.function(_product_price, type='float', string='Price', digits_compute=dp.get_precision('Product Price')), 'price_extra': fields.function(_get_price_extra, type='float', string='Variant Extra Price', help="This is the sum of the extra price of all attributes", digits_compute=dp.get_precision('Product Price')), 'lst_price': fields.function(_product_lst_price, fnct_inv=_set_product_lst_price, type='float', string='Public Price', digits_compute=dp.get_precision('Product Price')), 'code': fields.function(_product_code, type='char', string='Internal Reference'), 'partner_ref' : fields.function(_product_partner_ref, type='char', string='Customer ref'), 'default_code' : fields.char('Internal Reference', select=True), 'active': fields.boolean('Active', help="If unchecked, it will allow you to hide the product without removing it."), 'product_tmpl_id': fields.many2one('product.template', 'Product Template', required=True, ondelete="cascade", select=True, auto_join=True), 'ean13': fields.char('EAN13 Barcode', size=13, help="International Article Number used for product identification."), 'name_template': fields.related('product_tmpl_id', 'name', string="Template Name", type='char', store={ 'product.template': (_get_name_template_ids, ['name'], 10), 'product.product': (lambda self, cr, uid, ids, c=None: ids, [], 10), }, select=True), 'attribute_value_ids': fields.many2many('product.attribute.value', id1='prod_id', id2='att_id', string='Attributes', readonly=True, ondelete='restrict'), 'is_product_variant': fields.function( _is_product_variant_impl, type='boolean', string='Is product variant'), # image: all image fields are base64 encoded and PIL-supported 'image_variant': fields.binary("Variant Image", help="This field holds the image used as image for the product variant, limited to 1024x1024px."), 'image': fields.function(_get_image_variant, fnct_inv=_set_image_variant, string="Big-sized image", type="binary", help="Image of the product variant (Big-sized image of product template if false). It is automatically "\ "resized as a 1024x1024px image, with aspect ratio preserved."), 'image_small': fields.function(_get_image_variant, fnct_inv=_set_image_variant, string="Small-sized image", type="binary", help="Image of the product variant (Small-sized image of product template if false)."), 'image_medium': fields.function(_get_image_variant, fnct_inv=_set_image_variant, string="Medium-sized image", type="binary", help="Image of the product variant (Medium-sized image of product template if false)."), } _defaults = { 'active': 1, 'color': 0, } def unlink(self, cr, uid, ids, context=None): unlink_ids = [] unlink_product_tmpl_ids = [] for product in self.browse(cr, uid, ids, context=context): # Check if product still exists, in case it has been unlinked by unlinking its template if not product.exists(): continue tmpl_id = product.product_tmpl_id.id # Check if the product is last product of this template other_product_ids = self.search(cr, uid, [('product_tmpl_id', '=', tmpl_id), ('id', '!=', product.id)], context=context) if not other_product_ids: unlink_product_tmpl_ids.append(tmpl_id) unlink_ids.append(product.id) res = super(product_product, self).unlink(cr, uid, unlink_ids, context=context) # delete templates after calling super, as deleting template could lead to deleting # products due to ondelete='cascade' self.pool.get('product.template').unlink(cr, uid, unlink_product_tmpl_ids, context=context) return res def onchange_type(self, cr, uid, ids, type): return {} def onchange_uom(self, cursor, user, ids, uom_id, uom_po_id): if uom_id and uom_po_id: uom_obj=self.pool.get('product.uom') uom=uom_obj.browse(cursor,user,[uom_id])[0] uom_po=uom_obj.browse(cursor,user,[uom_po_id])[0] if uom.category_id.id != uom_po.category_id.id: return {'value': {'uom_po_id': uom_id}} return False def _check_ean_key(self, cr, uid, ids, context=None): for product in self.read(cr, uid, ids, ['ean13'], context=context): if not check_ean(product['ean13']): return False return True _constraints = [(_check_ean_key, 'You provided an invalid "EAN13 Barcode" reference. You may use the "Internal Reference" field instead.', ['ean13'])] def on_order(self, cr, uid, ids, orderline, quantity): pass def name_get(self, cr, user, ids, context=None): if context is None: context = {} if isinstance(ids, (int, long)): ids = [ids] if not len(ids): return [] def _name_get(d): name = d.get('name','') code = context.get('display_default_code', True) and d.get('default_code',False) or False if code: name = '[%s] %s' % (code,name) return (d['id'], name) partner_id = context.get('partner_id', False) if partner_id: partner_ids = [partner_id, self.pool['res.partner'].browse(cr, user, partner_id, context=context).commercial_partner_id.id] else: partner_ids = [] # all user don't have access to seller and partner # check access and use superuser self.check_access_rights(cr, user, "read") self.check_access_rule(cr, user, ids, "read", context=context) result = [] for product in self.browse(cr, SUPERUSER_ID, ids, context=context): variant = ", ".join([v.name for v in product.attribute_value_ids]) name = variant and "%s (%s)" % (product.name, variant) or product.name sellers = [] if partner_ids: sellers = filter(lambda x: x.name.id in partner_ids, product.seller_ids) if sellers: for s in sellers: seller_variant = s.product_name and ( variant and "%s (%s)" % (s.product_name, variant) or s.product_name ) or False mydict = { 'id': product.id, 'name': seller_variant or name, 'default_code': s.product_code or product.default_code, } result.append(_name_get(mydict)) else: mydict = { 'id': product.id, 'name': name, 'default_code': product.default_code, } result.append(_name_get(mydict)) return result def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100): if not args: args = [] if name: positive_operators = ['=', 'ilike', '=ilike', 'like', '=like'] ids = [] if operator in positive_operators: ids = self.search(cr, user, [('default_code','=',name)]+ args, limit=limit, context=context) if not ids: ids = self.search(cr, user, [('ean13','=',name)]+ args, limit=limit, context=context) if not ids and operator not in expression.NEGATIVE_TERM_OPERATORS: # Do not merge the 2 next lines into one single search, SQL search performance would be abysmal # on a database with thousands of matching products, due to the huge merge+unique needed for the # OR operator (and given the fact that the 'name' lookup results come from the ir.translation table # Performing a quick memory merge of ids in Python will give much better performance ids = self.search(cr, user, args + [('default_code', operator, name)], limit=limit, context=context) if not limit or len(ids) < limit: # we may underrun the limit because of dupes in the results, that's fine limit2 = (limit - len(ids)) if limit else False ids += self.search(cr, user, args + [('name', operator, name), ('id', 'not in', ids)], limit=limit2, context=context) elif not ids and operator in expression.NEGATIVE_TERM_OPERATORS: ids = self.search(cr, user, args + ['&', ('default_code', operator, name), ('name', operator, name)], limit=limit, context=context) if not ids and operator in positive_operators: ptrn = re.compile('(\[(.*?)\])') res = ptrn.search(name) if res: ids = self.search(cr, user, [('default_code','=', res.group(2))] + args, limit=limit, context=context) else: ids = self.search(cr, user, args, limit=limit, context=context) result = self.name_get(cr, user, ids, context=context) return result # # Could be overrided for variants matrices prices # def price_get(self, cr, uid, ids, ptype='list_price', context=None): products = self.browse(cr, uid, ids, context=context) return self.pool.get("product.template")._price_get(cr, uid, products, ptype=ptype, context=context) def copy(self, cr, uid, id, default=None, context=None): if context is None: context={} if default is None: default = {} product = self.browse(cr, uid, id, context) if context.get('variant'): # if we copy a variant or create one, we keep the same template default['product_tmpl_id'] = product.product_tmpl_id.id elif 'name' not in default: default['name'] = _("%s (copy)") % (product.name,) return super(product_product, self).copy(cr, uid, id, default=default, context=context) def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False): if context is None: context = {} if context.get('search_default_categ_id'): args.append((('categ_id', 'child_of', context['search_default_categ_id']))) return super(product_product, self).search(cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=count) def open_product_template(self, cr, uid, ids, context=None): """ Utility method used to add an "Open Template" button in product views """ product = self.browse(cr, uid, ids[0], context=context) return {'type': 'ir.actions.act_window', 'res_model': 'product.template', 'view_mode': 'form', 'res_id': product.product_tmpl_id.id, 'target': 'new'} def create(self, cr, uid, vals, context=None): if context is None: context = {} ctx = dict(context or {}, create_product_product=True) return super(product_product, self).create(cr, uid, vals, context=ctx) def need_procurement(self, cr, uid, ids, context=None): return False def _compute_uos_qty(self, cr, uid, ids, uom, qty, uos, context=None): ''' Computes product's invoicing quantity in UoS from quantity in UoM. Takes into account the :param uom: Source unit :param qty: Source quantity :param uos: Target UoS unit. ''' if not uom or not qty or not uos: return qty uom_obj = self.pool['product.uom'] product_id = ids[0] if isinstance(ids, (list, tuple)) else ids product = self.browse(cr, uid, product_id, context=context) if isinstance(uos, (int, long)): uos = uom_obj.browse(cr, uid, uos, context=context) if isinstance(uom, (int, long)): uom = uom_obj.browse(cr, uid, uom, context=context) if product.uos_id: # Product has UoS defined # We cannot convert directly between units even if the units are of the same category # as we need to apply the conversion coefficient which is valid only between quantities # in product's default UoM/UoS qty_default_uom = uom_obj._compute_qty_obj(cr, uid, uom, qty, product.uom_id) # qty in product's default UoM qty_default_uos = qty_default_uom * product.uos_coeff return uom_obj._compute_qty_obj(cr, uid, product.uos_id, qty_default_uos, uos) else: return uom_obj._compute_qty_obj(cr, uid, uom, qty, uos) class product_packaging(osv.osv): _name = "product.packaging" _description = "Packaging" _rec_name = 'ean' _order = 'sequence' _columns = { 'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of packaging."), 'name' : fields.text('Description'), 'qty' : fields.float('Quantity by Package', help="The total number of products you can put by pallet or box."), 'ul' : fields.many2one('product.ul', 'Package Logistic Unit', required=True), 'ul_qty' : fields.integer('Package by layer', help='The number of packages by layer'), 'ul_container': fields.many2one('product.ul', 'Pallet Logistic Unit'), 'rows' : fields.integer('Number of Layers', required=True, help='The number of layers on a pallet or box'), 'product_tmpl_id' : fields.many2one('product.template', 'Product', select=1, ondelete='cascade', required=True), 'ean' : fields.char('EAN', size=14, help="The EAN code of the package unit."), 'code' : fields.char('Code', help="The code of the transport unit."), 'weight': fields.float('Total Package Weight', help='The weight of a full package, pallet or box.'), } def _check_ean_key(self, cr, uid, ids, context=None): for pack in self.browse(cr, uid, ids, context=context): if not check_ean(pack.ean): return False return True _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean'])] def name_get(self, cr, uid, ids, context=None): if not len(ids): return [] res = [] for pckg in self.browse(cr, uid, ids, context=context): p_name = pckg.ean and '[' + pckg.ean + '] ' or '' p_name += pckg.ul.name res.append((pckg.id,p_name)) return res def _get_1st_ul(self, cr, uid, context=None): cr.execute('select id from product_ul order by id asc limit 1') res = cr.fetchone() return (res and res[0]) or False _defaults = { 'rows' : 3, 'sequence' : 1, 'ul' : _get_1st_ul, } def checksum(ean): salt = '31' * 6 + '3' sum = 0 for ean_part, salt_part in zip(ean, salt): sum += int(ean_part) * int(salt_part) return (10 - (sum % 10)) % 10 checksum = staticmethod(checksum) class product_supplierinfo(osv.osv): _name = "product.supplierinfo" _description = "Information about a product supplier" def _calc_qty(self, cr, uid, ids, fields, arg, context=None): result = {} for supplier_info in self.browse(cr, uid, ids, context=context): for field in fields: result[supplier_info.id] = {field:False} qty = supplier_info.min_qty result[supplier_info.id]['qty'] = qty return result _columns = { 'name' : fields.many2one('res.partner', 'Supplier', required=True,domain = [('supplier','=',True)], ondelete='cascade', help="Supplier of this product"), 'product_name': fields.char('Supplier Product Name', help="This supplier's product name will be used when printing a request for quotation. Keep empty to use the internal one."), 'product_code': fields.char('Supplier Product Code', help="This supplier's product code will be used when printing a request for quotation. Keep empty to use the internal one."), 'sequence' : fields.integer('Sequence', help="Assigns the priority to the list of product supplier."), 'product_uom': fields.related('product_tmpl_id', 'uom_po_id', type='many2one', relation='product.uom', string="Supplier Unit of Measure", readonly="1", help="This comes from the product form."), 'min_qty': fields.float('Minimal Quantity', required=True, help="The minimal quantity to purchase to this supplier, expressed in the supplier Product Unit of Measure if not empty, in the default unit of measure of the product otherwise."), 'qty': fields.function(_calc_qty, store=True, type='float', string='Quantity', multi="qty", help="This is a quantity which is converted into Default Unit of Measure."), 'product_tmpl_id' : fields.many2one('product.template', 'Product Template', required=True, ondelete='cascade', select=True, oldname='product_id'), 'delay' : fields.integer('Delivery Lead Time', required=True, help="Lead time in days between the confirmation of the purchase order and the receipt of the products in your warehouse. Used by the scheduler for automatic computation of the purchase order planning."), 'pricelist_ids': fields.one2many('pricelist.partnerinfo', 'suppinfo_id', 'Supplier Pricelist', copy=True), 'company_id':fields.many2one('res.company','Company',select=1), } _defaults = { 'min_qty': 0.0, 'sequence': 1, 'delay': 1, 'company_id': lambda self,cr,uid,c: self.pool.get('res.company')._company_default_get(cr, uid, 'product.supplierinfo', context=c), } _order = 'sequence' class pricelist_partnerinfo(osv.osv): _name = 'pricelist.partnerinfo' _columns = { 'name': fields.char('Description'), 'suppinfo_id': fields.many2one('product.supplierinfo', 'Partner Information', required=True, ondelete='cascade'), 'min_quantity': fields.float('Quantity', required=True, help="The minimal quantity to trigger this rule, expressed in the supplier Unit of Measure if any or in the default Unit of Measure of the product otherrwise."), 'price': fields.float('Unit Price', required=True, digits_compute=dp.get_precision('Product Price'), help="This price will be considered as a price for the supplier Unit of Measure if any or the default Unit of Measure of the product otherwise"), } _order = 'min_quantity asc' class res_currency(osv.osv): _inherit = 'res.currency' def _check_main_currency_rounding(self, cr, uid, ids, context=None): cr.execute('SELECT digits FROM decimal_precision WHERE name like %s',('Account',)) digits = cr.fetchone() if digits and len(digits): digits = digits[0] main_currency = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id for currency_id in ids: if currency_id == main_currency.id: if float_compare(main_currency.rounding, 10 ** -digits, precision_digits=6) == -1: return False return True _constraints = [ (_check_main_currency_rounding, 'Error! You cannot define a rounding factor for the company\'s main currency that is smaller than the decimal precision of \'Account\'.', ['rounding']), ] class decimal_precision(osv.osv): _inherit = 'decimal.precision' def _check_main_currency_rounding(self, cr, uid, ids, context=None): cr.execute('SELECT id, digits FROM decimal_precision WHERE name like %s',('Account',)) res = cr.fetchone() if res and len(res): account_precision_id, digits = res main_currency = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.currency_id for decimal_precision in ids: if decimal_precision == account_precision_id: if float_compare(main_currency.rounding, 10 ** -digits, precision_digits=6) == -1: return False return True _constraints = [ (_check_main_currency_rounding, 'Error! You cannot define the decimal precision of \'Account\' as greater than the rounding factor of the company\'s main currency', ['digits']), ] # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
Keeper-Security/Commander
keepercommander/commands/folder.py
1
27728
#_ __ # | |/ /___ ___ _ __ ___ _ _ ® # | ' </ -_) -_) '_ \/ -_) '_| # |_|\_\___\___| .__/\___|_| # |_| # # Keeper Commander # Copyright 2018 Keeper Security Inc. # Contact: ops@keepersecurity.com # import argparse import collections import re import fnmatch import shutil import functools import os import json from .. import api, display from ..subfolder import BaseFolderNode, try_resolve_path, find_folders from ..record import Record from .base import user_choice, suppress_exit, raise_parse_exception, Command from ..params import LAST_SHARED_FOLDER_UID, LAST_FOLDER_UID from ..error import CommandError def register_commands(commands): commands['ls'] = FolderListCommand() commands['cd'] = FolderCdCommand() commands['tree'] = FolderTreeCommand() commands['mkdir'] = FolderMakeCommand() commands['rmdir'] = FolderRemoveCommand() commands['mv'] = FolderMoveCommand() commands['ln'] = FolderLinkCommand() def register_command_info(aliases, command_info): for p in [cd_parser, ls_parser, tree_parser, mkdir_parser, rmdir_parser, mv_parser, ln_parser]: command_info[p.prog] = p.description ls_parser = argparse.ArgumentParser(prog='ls', description='List folder contents.') ls_parser.add_argument('-l', '--list', dest='detail', action='store_true', help='show detailed list') ls_parser.add_argument('-f', '--folders', dest='folders', action='store_true', help='display folders') ls_parser.add_argument('-r', '--records', dest='records', action='store_true', help='display records') ls_parser.add_argument('-v', '--verbose', dest='verbose', action='store_true', help='verbose output') ls_parser.add_argument('pattern', nargs='?', type=str, action='store', help='search pattern') ls_parser.error = raise_parse_exception ls_parser.exit = suppress_exit cd_parser = argparse.ArgumentParser(prog='cd', description='Change current folder.') cd_parser.add_argument('folder', nargs='?', type=str, action='store', help='folder path or UID') cd_parser.error = raise_parse_exception cd_parser.exit = suppress_exit tree_parser = argparse.ArgumentParser(prog='tree', description='Display the folder structure.') tree_parser.add_argument('folder', nargs='?', type=str, action='store', help='folder path or UID') tree_parser.error = raise_parse_exception tree_parser.exit = suppress_exit rmdir_parser = argparse.ArgumentParser(prog='rmdir', description='Remove a folder and its contents.') rmdir_parser.add_argument('-f', '--force', dest='force', action='store_true', help='remove folder without prompting') rmdir_parser.add_argument('folder', nargs='?', type=str, action='store', help='folder path or UID') rmdir_parser.error = raise_parse_exception rmdir_parser.exit = suppress_exit mkdir_parser = argparse.ArgumentParser(prog='mkdir', description='Create a folder.') mkdir_parser.add_argument('-sf', '--shared-folder', dest='shared_folder', action='store_true', help='create shared folder') mkdir_parser.add_argument('-uf', '--user-folder', dest='user_folder', action='store_true', help='create user folder') mkdir_parser.add_argument('-a', '--all', dest='grant', action='store_true', help='anyone has all permissions by default') mkdir_parser.add_argument('-u', '--manage-users', dest='manage_users', action='store_true', help='anyone can manage users by default') mkdir_parser.add_argument('-r', '--manage-records', dest='manage_records', action='store_true', help='anyone can manage records by default') mkdir_parser.add_argument('-s', '--can-share', dest='can_share', action='store_true', help='anyone can share records by default') mkdir_parser.add_argument('-e', '--can-edit', dest='can_edit', action='store_true', help='anyone can edit records by default') mkdir_parser.add_argument('folder', nargs='?', type=str, action='store', help='folder path') mkdir_parser.error = raise_parse_exception mkdir_parser.exit = suppress_exit mv_parser = argparse.ArgumentParser(prog='mv', description='Move a record or folder to another folder.') mv_parser.add_argument('-f', '--force', dest='force', action='store_true', help='do not prompt') mv_parser.add_argument('-s', '--can-reshare', dest='can_reshare', action='store_true', help='anyone can reshare records') mv_parser.add_argument('-e', '--can-edit', dest='can_edit', action='store_true', help='anyone can edit records') mv_parser.add_argument('src', nargs='?', type=str, action='store', help='source path to folder/record or UID') mv_parser.add_argument('dst', nargs='?', type=str, action='store', help='destination folder or UID') mv_parser.error = raise_parse_exception mv_parser.exit = suppress_exit ln_parser = argparse.ArgumentParser(prog='ln', description='Create a link between a record and a folder.') ln_parser.add_argument('-f', '--force', dest='force', action='store_true', help='do not prompt') ln_parser.add_argument('-s', '--can-reshare', dest='can_reshare', action='store_true', help='anyone can reshare records') ln_parser.add_argument('-e', '--can-edit', dest='can_edit', action='store_true', help='anyone can edit records') ln_parser.add_argument('src', nargs='?', type=str, action='store', help='source path to folder/record or UID') ln_parser.add_argument('dst', nargs='?', type=str, action='store', help='destination folder or UID') ln_parser.error = raise_parse_exception ln_parser.exit = suppress_exit class FolderListCommand(Command): @staticmethod def folder_match_strings(folder): # type: (BaseFolderNode) -> collections.Iterable[str] return filter(lambda f: type(f) == str and len(f) > 0, [folder.name, folder.uid]) @staticmethod def record_match_strings(record): # type: (Record) -> collections.Iterable[str] return filter(lambda f: type(f) == str and len(f) > 0, [record.title, record.record_uid, record.login, record.login_url, record.notes]) @staticmethod def chunk_list(l, n): for i in range(0, len(l), n): yield l[i:i + n] def get_parser(self): return ls_parser def execute(self, params, **kwargs): show_folders = kwargs['folders'] if 'folders' in kwargs else None show_records = kwargs['records'] if 'records' in kwargs else None show_detail = kwargs['detail'] if 'detail' in kwargs else False if not show_folders and not show_records: show_folders = True show_records = True folder = params.folder_cache[params.current_folder] if params.current_folder in params.folder_cache else params.root_folder pattern = kwargs['pattern'] if 'pattern' in kwargs else None if pattern: rs = try_resolve_path(params, kwargs['pattern']) if rs is not None: folder, pattern = rs regex = None if pattern: regex = re.compile(fnmatch.translate(pattern)).match folders = [] records = [] if show_folders: for uid in folder.subfolders: f = params.folder_cache[uid] if any(filter(lambda x: regex(x) is not None, FolderListCommand.folder_match_strings(f))) if regex is not None else True: folders.append(f) if show_records: folder_uid = folder.uid or '' if folder_uid in params.subfolder_record_cache: for uid in params.subfolder_record_cache[folder_uid]: r = api.get_record(params, uid) if any(filter(lambda x: regex(x) is not None, FolderListCommand.record_match_strings(r))) if regex is not None else True: records.append(r) if len(folders) == 0 and len(records) == 0: if pattern: raise CommandError('ls', '{0}: No such folder or record'.format(pattern)) else: if show_detail: if len(folders) > 0: display.formatted_folders(folders) if len(records) > 0: if len(records) < 5: api.get_record_shares(params, [x.record_uid for x in records]) display.formatted_records(records, folder=folder.uid, verbose=kwargs['verbose']) else: names = [] for f in folders: name = f.name or f.uid if len(name) > 40: name = name[:25] + '...' + name[-12:] names.append(name + '/') names.sort() rnames = [] for r in records: name = r.title or r.record_uid if len(name) > 40: name = name[:25] + '...' + name[-12:] rnames.append(name) rnames.sort() names.extend(rnames) width, _ = shutil.get_terminal_size(fallback=(1, 1)) max_name = functools.reduce(lambda val, elem: len(elem) if len(elem) > val else val, names, 0) cols = width // max_name if cols == 0: cols = 1 if cols > 2: if ((max_name * cols) + (cols - 1) * 2) > width: cols = cols - 1 tbl = FolderListCommand.chunk_list([x.ljust(max_name) if cols > 1 else x for x in names], cols) rows = [' '.join(x) for x in tbl] print('\n'.join(rows)) class FolderCdCommand(Command): def get_parser(self): return cd_parser def execute(self, params, **kwargs): folder_name = kwargs['folder'] if 'folder' in kwargs else '' if folder_name: if folder_name in params.folder_cache: params.current_folder = folder_name else: rs = try_resolve_path(params, folder_name) if rs is not None: folder, pattern = rs if len(pattern) == 0: params.current_folder = folder.uid else: raise CommandError('cd', 'Folder {0} not found'.format(folder_name)) class FolderTreeCommand(Command): def get_parser(self): return tree_parser def execute(self, params, **kwargs): folder_name = kwargs['folder'] if 'folder' in kwargs else None if folder_name in params.folder_cache: display.formatted_tree(params, params.folder_cache[folder_name]) else: rs = try_resolve_path(params, folder_name) if rs is not None: folder, pattern = rs if len(pattern) == 0: display.formatted_tree(params, folder) else: raise CommandError('tree', 'Folder %s not found'.format(folder_name)) class FolderMakeCommand(Command): def get_parser(self): return mkdir_parser def execute(self, params, **kwargs): base_folder = params.folder_cache[params.current_folder] if params.current_folder in params.folder_cache else params.root_folder name = kwargs['folder'] if 'folder' in kwargs else None if name: rs = try_resolve_path(params, name) if rs is not None: base_folder, name = rs if len(name) == 0: raise CommandError('mkdir', 'Folder "{0}" already exists'.format(kwargs['folder'])) shared_folder = kwargs['shared_folder'] if 'shared_folder' in kwargs else None user_folder = kwargs['user_folder'] if 'user_folder' in kwargs else None request = {"command": "folder_add"} if shared_folder: if base_folder.type in {BaseFolderNode.RootFolderType, BaseFolderNode.UserFolderType}: request['folder_type'] = 'shared_folder' grant = kwargs['grant'] if 'grant' in kwargs else None for flag in ['manage_users', 'manage_records', 'can_share', 'can_edit']: if grant or (flag in kwargs and kwargs[flag]): request[flag] = True else: raise CommandError('mkdir', 'Shared folders cannot be nested') elif user_folder: if base_folder.type in {BaseFolderNode.SharedFolderType, BaseFolderNode.SharedFolderFolderType}: request['folder_type'] = 'shared_folder_folder' else: request['folder_type'] = 'user_folder' if request.get('folder_type') is None: if base_folder.type in {BaseFolderNode.SharedFolderType, BaseFolderNode.SharedFolderFolderType}: request['folder_type'] = 'shared_folder_folder' if request.get('folder_type') is None: inp = user_choice('Do you want to create a shared folder?', 'yn', default='n') if inp.lower() == 'y': request['folder_type'] = 'shared_folder' pq = 'Default user permissions: (A)ll | Manage (U)sers / (R)ecords; Can (E)dit / (S)hare records?' inp = user_choice(pq, 'aures', multi_choice=True) request['manage_users'] = False request['manage_records'] = False request['can_edit'] = False request['can_share'] = False if len(inp) > 0: s1 = set([x.lower() for x in inp]) if 'a' in s1: request['manage_users'] = True request['manage_records'] = True request['can_edit'] = True request['can_share'] = True else: if 'u' in s1: request['manage_users'] = True if 'r' in s1: request['manage_records'] = True if 'e' in s1: request['can_edit'] = True if 's' in s1: request['can_share'] = True else: request['folder_type'] = 'user_folder' folder_uid = api.generate_record_uid() request['folder_uid'] = folder_uid folder_key = os.urandom(32) encryption_key = params.data_key if request['folder_type'] == 'shared_folder_folder': sf_uid = base_folder.shared_folder_uid if base_folder.type == BaseFolderNode.SharedFolderFolderType else base_folder.uid sf = params.shared_folder_cache[sf_uid] encryption_key = sf['shared_folder_key_unencrypted'] request['shared_folder_uid'] = sf_uid request['key'] = api.encrypt_aes(folder_key, encryption_key) if base_folder.type not in {BaseFolderNode.RootFolderType, BaseFolderNode.SharedFolderType}: request['parent_uid'] = base_folder.uid name = name or '' while len(name.strip()) == 0: name = input("... Folder Name: ") name = name.strip() is_slash = False for x in range(0, len(name)-2): if name[x] == '/': is_slash = not is_slash else: if is_slash: raise CommandError('mkdir', 'Character "/" is reserved. Use "//" inside folder name') name = name.replace('//', '/') if request['folder_type'] == 'shared_folder': request['name'] = api.encrypt_aes(name.encode('utf-8'), folder_key) data = {'name': name} request['data'] = api.encrypt_aes(json.dumps(data).encode('utf-8'), folder_key) api.communicate(params, request) params.sync_data = True params.environment_variables[LAST_FOLDER_UID] = folder_uid if request['folder_type'] == 'shared_folder': params.environment_variables[LAST_SHARED_FOLDER_UID] = folder_uid class FolderRemoveCommand(Command): def get_parser(self): return rmdir_parser def execute(self, params, **kwargs): folder = None name = kwargs['folder'] if 'folder' in kwargs else '' if name: if name in params.folder_cache: folder = params.folder_cache[name] else: rs = try_resolve_path(params, name) if rs is not None: folder, name = rs if len(name or '') > 0: folder = None elif folder.type == BaseFolderNode.RootFolderType: folder = None if folder is None: raise CommandError('rmdir', 'Enter name of the existing folder. ({0})'.format(name)) force = kwargs['force'] if 'force' in kwargs else None parent = params.folder_cache[folder.uid] if folder.uid is not None else None if folder.type == BaseFolderNode.SharedFolderType: if folder.uid in params.shared_folder_cache: sf = params.shared_folder_cache[folder.uid] rq = { 'command': 'shared_folder_update', 'operation': 'delete', 'shared_folder_uid': sf['shared_folder_uid'] } if 'shared_folder_key' not in sf: if 'teams' in sf: for team in sf['teams']: rq['from_team_uid'] = team['team_uid'] break np = 'y' if force else user_choice('Do you want to proceed with deletion?', 'yn', default='n') if np.lower() == 'y': api.communicate(params, rq) params.sync_data = True else: del_obj = { 'delete_resolution': 'unlink', 'object_uid': folder.uid, 'object_type': 'user_folder' if folder.type == BaseFolderNode.UserFolderType else 'shared_folder_folder' } if parent is None: del_obj['from_type'] = 'user_folder' else: del_obj['from_uid'] = parent.uid del_obj['from_type'] = parent.type if parent.type == BaseFolderNode.SharedFolderType: del_obj['from_type'] = 'shared_folder_folder' rq = { 'command': 'pre_delete', 'objects': [del_obj] } rs = api.communicate(params, rq) if rs['result'] == 'success': pdr = rs['pre_delete_response'] np = 'y' if not force: summary = pdr['would_delete']['deletion_summary'] for x in summary: print(x) np = user_choice('Do you like to proceed with deletion?', 'yn', default='n') if np.lower() == 'y': rq = { 'command': 'delete', 'pre_delete_token': pdr['pre_delete_token'] } api.communicate(params, rq) params.sync_data = True class FolderMoveCommand(Command): @staticmethod def prepare_transition_keys(params, folder, keys, encryption_key): for f_uid in folder.subfolders: f = params.folder_cache[f_uid] FolderMoveCommand.prepare_transition_keys(params, f, keys, encryption_key) sf = params.subfolder_cache[folder.uid] transition_key = api.encrypt_aes(sf['folder_key_unencrypted'], encryption_key) keys.append({ 'uid': folder.uid, 'key': transition_key }) if folder.uid in params.subfolder_record_cache: for r_uid in params.subfolder_record_cache[folder.uid]: rec = params.record_cache[r_uid] transition_key = api.encrypt_aes(rec['record_key_unencrypted'], encryption_key) keys.append({ 'uid': r_uid, 'key': transition_key }) def get_parser(self): return mv_parser def is_move(self): return True def execute(self, params, **kwargs): src_path = kwargs['src'] if 'src' in kwargs else None dst_path = kwargs['dst'] if 'dst' in kwargs else None if not src_path or not dst_path: parser = self.get_parser() parser.print_help() return src_record_uid = None src_folder = None if src_path in params.record_cache: src_record_uid = src_path if '' in params.subfolder_record_cache: if src_record_uid in params.subfolder_record_cache['']: src_folder = params.root_folder if src_folder is None: for folder_uid in find_folders(params, src_record_uid): src_folder = params.folder_cache[folder_uid] break if src_folder is None: src_folder = params.root_folder elif src_path in params.folder_cache: src_folder = params.folder_cache[src_path] else: src = try_resolve_path(params, src_path) if src is None: raise CommandError('mv', 'Source path should be existing record or folder') src_folder, name = src if len(name) > 0: src_folder_uid = src_folder.uid or '' if src_folder_uid in params.subfolder_record_cache: for uid in params.subfolder_record_cache[src_folder_uid]: rec = api.get_record(params, uid) if name in {rec.title, rec.record_uid}: src_record_uid = rec.record_uid break if src_record_uid is None: raise CommandError('mv', 'Record "{0}" not found'.format(name)) dst_folder = None if dst_path in params.folder_cache: dst_folder = params.folder_cache[dst_path] else: dst = try_resolve_path(params, dst_path) if dst is None: raise CommandError('mv', 'Destination path should be existing folder') dst_folder, name = dst if len(name) > 0: raise CommandError('mv', 'Destination path should be existing folder') rq = { 'command': 'move', 'link': not self.is_move(), 'move': [] } if dst_folder.type == BaseFolderNode.RootFolderType: rq['to_type'] = BaseFolderNode.UserFolderType else: rq['to_type'] = dst_folder.type rq['to_uid'] = dst_folder.uid if src_record_uid is None: ''' folder ''' if src_folder.type == BaseFolderNode.RootFolderType: raise CommandError('mv', 'Root folder cannot be a source folder') dp = set() f = dst_folder while f is not None: if len(f.uid) > 0: dp.add(f.uid) f = params.folder_cache.get(f.parent_uid) if f.parent_uid is not None else None if src_folder.uid in dp: raise CommandError('mv', 'Cannot move/link folder to self or a child') parent_folder = params.folder_cache[src_folder.parent_uid] if src_folder.parent_uid is not None else None move = { 'uid': src_folder.uid, 'type': src_folder.type, 'cascade': True } if parent_folder is None: move['from_type'] = BaseFolderNode.UserFolderType else: move['from_type'] = parent_folder.type move['from_uid'] = parent_folder.uid rq['move'].append(move) transition_keys = [] if src_folder.type == BaseFolderNode.UserFolderType: if dst_folder.type in {BaseFolderNode.SharedFolderType, BaseFolderNode.SharedFolderFolderType}: shf_uid = dst_folder.uid if dst_folder.type == BaseFolderNode.SharedFolderType else dst_folder.shared_folder_uid shf = params.shared_folder_cache[shf_uid] FolderMoveCommand.prepare_transition_keys(params, src_folder, transition_keys, shf['shared_folder_key_unencrypted']) elif src_folder.type == BaseFolderNode.SharedFolderFolderType: if dst_folder.type in {BaseFolderNode.SharedFolderType, BaseFolderNode.SharedFolderFolderType}: dsf_uid = dst_folder.uid if dst_folder.type == BaseFolderNode.SharedFolderType else dst_folder.shared_folder_uid ssf_uid = src_folder.shared_folder_uid if ssf_uid != dsf_uid: dsf = params.shared_folder_cache[dsf_uid] FolderMoveCommand.prepare_transition_keys(params, src_folder, transition_keys, dsf['shared_folder_key_unencrypted']) else: FolderMoveCommand.prepare_transition_keys(params, src_folder, transition_keys, params.data_key) rq['transition_keys'] = transition_keys else: move = { 'uid': src_record_uid, 'type': 'record', 'cascade': False } if src_folder.type == BaseFolderNode.RootFolderType: move['from_type'] = BaseFolderNode.UserFolderType else: move['from_type'] = src_folder.type move['from_uid'] = src_folder.uid if dst_folder.type in {BaseFolderNode.SharedFolderType, BaseFolderNode.SharedFolderFolderType}: for flag in ['can_reshare', 'can_edit']: if flag in kwargs and kwargs[flag]: move[flag] = True rq['move'].append(move) transition_key = None rec = params.record_cache[src_record_uid] if src_folder.type in {BaseFolderNode.SharedFolderType, BaseFolderNode.SharedFolderFolderType}: if dst_folder.type in {BaseFolderNode.SharedFolderType, BaseFolderNode.SharedFolderFolderType}: ssf_uid = src_folder.uid if src_folder.type == BaseFolderNode.SharedFolderType else src_folder.shared_folder_uid dsf_uid = dst_folder.uid if dst_folder.type == BaseFolderNode.SharedFolderType else dst_folder.shared_folder_uid if ssf_uid != dsf_uid: shf = params.shared_folder_cache[dsf_uid] transition_key = api.encrypt_aes(rec['record_key_unencrypted'], shf['shared_folder_key_unencrypted']) else: transition_key = api.encrypt_aes(rec['record_key_unencrypted'], params.data_key) else: if dst_folder.type in {BaseFolderNode.SharedFolderType, BaseFolderNode.SharedFolderFolderType}: dsf_uid = dst_folder.uid if dst_folder.type == BaseFolderNode.SharedFolderType else \ dst_folder.shared_folder_uid shf = params.shared_folder_cache[dsf_uid] transition_key = api.encrypt_aes(rec['record_key_unencrypted'], shf['shared_folder_key_unencrypted']) transition_keys = [] if transition_key is not None: transition_keys.append({ 'uid': src_record_uid, 'key': transition_key }) rq['transition_keys'] = transition_keys api.communicate(params, rq) params.sync_data = True class FolderLinkCommand(FolderMoveCommand): def is_move(self): return False def get_parser(self): return ln_parser
mit
tkaitchuck/nupic
examples/opf/experiments/anomaly/spatial/2field_few_6040/description.py
10
15991
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have purchased from # Numenta, Inc. a separate commercial license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ Template file used by the OPF Experiment Generator to generate the actual description.py file by replacing $XXXXXXXX tokens with desired values. This description.py file was generated by: '~/nta/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py' """ from nupic.frameworks.opf.expdescriptionapi import ExperimentDescriptionAPI from nupic.frameworks.opf.expdescriptionhelpers import ( updateConfigFromSubConfig, applyValueGettersToContainer, DeferredDictLookup) from nupic.frameworks.opf.clamodelcallbacks import * from nupic.frameworks.opf.metrics import MetricSpec from nupic.frameworks.opf.opfutils import (InferenceType, InferenceElement) from nupic.support import aggregationDivide from nupic.frameworks.opf.opftaskdriver import ( IterationPhaseSpecLearnOnly, IterationPhaseSpecInferOnly, IterationPhaseSpecLearnAndInfer) # Model Configuration Dictionary: # # Define the model parameters and adjust for any modifications if imported # from a sub-experiment. # # These fields might be modified by a sub-experiment; this dict is passed # between the sub-experiment and base experiment # # # NOTE: Use of DEFERRED VALUE-GETTERs: dictionary fields and list elements # within the config dictionary may be assigned futures derived from the # ValueGetterBase class, such as DeferredDictLookup. # This facility is particularly handy for enabling substitution of values in # the config dictionary from other values in the config dictionary, which is # needed by permutation.py-based experiments. These values will be resolved # during the call to applyValueGettersToContainer(), # which we call after the base experiment's config dictionary is updated from # the sub-experiment. See ValueGetterBase and # DeferredDictLookup for more details about value-getters. # # For each custom encoder parameter to be exposed to the sub-experiment/ # permutation overrides, define a variable in this section, using key names # beginning with a single underscore character to avoid collisions with # pre-defined keys (e.g., _dsEncoderFieldName2_N). # # Example: # config = dict( # _dsEncoderFieldName2_N = 70, # _dsEncoderFieldName2_W = 5, # dsEncoderSchema = [ # base=dict( # fieldname='Name2', type='ScalarEncoder', # name='Name2', minval=0, maxval=270, clipInput=True, # n=DeferredDictLookup('_dsEncoderFieldName2_N'), # w=DeferredDictLookup('_dsEncoderFieldName2_W')), # ], # ) # updateConfigFromSubConfig(config) # applyValueGettersToContainer(config) config = { # Type of model that the rest of these parameters apply to. 'model': "CLA", # Version that specifies the format of the config. 'version': 1, # Intermediate variables used to compute fields in modelParams and also # referenced from the control section. 'aggregationInfo': { 'fields': [ ('numericFieldNameA', 'mean'), ('numericFieldNameB', 'sum'), ('categoryFieldNameC', 'first')], 'hours': 0}, 'predictAheadTime': None, # Model parameter dictionary. 'modelParams': { # The type of inference that this model will perform 'inferenceType': 'NontemporalAnomaly', 'sensorParams': { # Sensor diagnostic output verbosity control; # if > 0: sensor region will print out on screen what it's sensing # at each step 0: silent; >=1: some info; >=2: more info; # >=3: even more info (see compute() in py/regions/RecordSensor.py) 'verbosity' : 0, # Example: # dsEncoderSchema = [ # DeferredDictLookup('__field_name_encoder'), # ], # # (value generated from DS_ENCODER_SCHEMA) 'encoders': { 'f0': dict(fieldname='f0', n=100, name='f0', type='SDRCategoryEncoder', w=21), 'f1': dict(fieldname='f1', n=100, name='f1', type='SDRCategoryEncoder', w=21), }, # A dictionary specifying the period for automatically-generated # resets from a RecordSensor; # # None = disable automatically-generated resets (also disabled if # all of the specified values evaluate to 0). # Valid keys is the desired combination of the following: # days, hours, minutes, seconds, milliseconds, microseconds, weeks # # Example for 1.5 days: sensorAutoReset = dict(days=1,hours=12), # # (value generated from SENSOR_AUTO_RESET) 'sensorAutoReset' : None, }, 'spEnable': True, 'spParams': { # SP diagnostic output verbosity control; # 0: silent; >=1: some info; >=2: more info; 'spVerbosity' : 0, 'globalInhibition': 1, # Number of cell columns in the cortical region (same number for # SP and TP) # (see also tpNCellsPerCol) 'columnCount': 2048, 'inputWidth': 0, # SP inhibition control (absolute value); # Maximum number of active columns in the SP region's output (when # there are more, the weaker ones are suppressed) 'numActivePerInhArea': 40, 'seed': 1956, # coincInputPoolPct # What percent of the columns's receptive field is available # for potential synapses. At initialization time, we will # choose coincInputPoolPct * (2*coincInputRadius+1)^2 'coincInputPoolPct': 0.5, # The default connected threshold. Any synapse whose # permanence value is above the connected threshold is # a "connected synapse", meaning it can contribute to the # cell's firing. Typical value is 0.10. Cells whose activity # level before inhibition falls below minDutyCycleBeforeInh # will have their own internal synPermConnectedCell # threshold set below this default value. # (This concept applies to both SP and TP and so 'cells' # is correct here as opposed to 'columns') 'synPermConnected': 0.1, 'synPermActiveInc': 0.1, 'synPermInactiveDec': 0.01, }, # Controls whether TP is enabled or disabled; # TP is necessary for making temporal predictions, such as predicting # the next inputs. Without TP, the model is only capable of # reconstructing missing sensor inputs (via SP). 'tpEnable' : True, 'tpParams': { # TP diagnostic output verbosity control; # 0: silent; [1..6]: increasing levels of verbosity # (see verbosity in nta/trunk/py/nupic/research/TP.py and TP10X*.py) 'verbosity': 0, # Number of cell columns in the cortical region (same number for # SP and TP) # (see also tpNCellsPerCol) 'columnCount': 2048, # The number of cells (i.e., states), allocated per column. 'cellsPerColumn': 32, 'inputWidth': 2048, 'seed': 1960, # Temporal Pooler implementation selector (see _getTPClass in # CLARegion.py). 'temporalImp': 'cpp', # New Synapse formation count # NOTE: If None, use spNumActivePerInhArea # # TODO: need better explanation 'newSynapseCount': 20, # Maximum number of synapses per segment # > 0 for fixed-size CLA # -1 for non-fixed-size CLA # # TODO: for Ron: once the appropriate value is placed in TP # constructor, see if we should eliminate this parameter from # description.py. 'maxSynapsesPerSegment': 32, # Maximum number of segments per cell # > 0 for fixed-size CLA # -1 for non-fixed-size CLA # # TODO: for Ron: once the appropriate value is placed in TP # constructor, see if we should eliminate this parameter from # description.py. 'maxSegmentsPerCell': 128, # Initial Permanence # TODO: need better explanation 'initialPerm': 0.21, # Permanence Increment 'permanenceInc': 0.1, # Permanence Decrement # If set to None, will automatically default to tpPermanenceInc # value. 'permanenceDec' : 0.1, 'globalDecay': 0.0, 'maxAge': 0, # Minimum number of active synapses for a segment to be considered # during search for the best-matching segments. # None=use default # Replaces: tpMinThreshold 'minThreshold': 12, # Segment activation threshold. # A segment is active if it has >= tpSegmentActivationThreshold # connected synapses that are active due to infActiveState # None=use default # Replaces: tpActivationThreshold 'activationThreshold': 16, 'outputType': 'normal', # "Pay Attention Mode" length. This tells the TP how many new # elements to append to the end of a learned sequence at a time. # Smaller values are better for datasets with short sequences, # higher values are better for datasets with long sequences. 'pamLength': 1, }, 'clParams': { 'regionName' : 'CLAClassifierRegion', # Classifier diagnostic output verbosity control; # 0: silent; [1..6]: increasing levels of verbosity 'clVerbosity' : 0, # This controls how fast the classifier learns/forgets. Higher values # make it adapt faster and forget older patterns faster. 'alpha': 0.001, # This is set after the call to updateConfigFromSubConfig and is # computed from the aggregationInfo and predictAheadTime. 'steps': '1', }, 'trainSPNetOnlyIfRequested': False, }, } # end of config dictionary # Adjust base config dictionary for any modifications if imported from a # sub-experiment updateConfigFromSubConfig(config) # Compute predictionSteps based on the predictAheadTime and the aggregation # period, which may be permuted over. if config['predictAheadTime'] is not None: predictionSteps = int(round(aggregationDivide( config['predictAheadTime'], config['aggregationInfo']))) assert (predictionSteps >= 1) config['modelParams']['clParams']['steps'] = str(predictionSteps) # Adjust config by applying ValueGetterBase-derived # futures. NOTE: this MUST be called after updateConfigFromSubConfig() in order # to support value-getter-based substitutions from the sub-experiment (if any) applyValueGettersToContainer(config) ################################################################################ # [optional] A sequence of one or more tasks that describe what to do with the # model. Each task consists of a task label, an input spec., iteration count, # and a task-control spec per opfTaskSchema.json # # NOTE: The tasks are intended for OPF clients that make use of OPFTaskDriver. # Clients that interact with OPFExperiment directly do not make use of # the tasks specification. # control = dict( environment='opfExperiment', tasks = [ { # Task label; this label string may be used for diagnostic logging and for # constructing filenames or directory pathnames for task-specific files, etc. 'taskLabel' : "Anomaly", # Input stream specification per py/nupic/cluster/database/StreamDef.json. # 'dataset' : { 'info': 'test_NoProviders', 'version': 1, 'streams': [ { 'columns': ['*'], 'info': 'my simple dataset', 'source': 'file://'+os.path.join(os.path.dirname(__file__), 'data.csv'), } ], # TODO: Aggregation is not supported yet by OpfRunExperiment.py #'aggregation' : config['aggregationInfo'] }, # Iteration count: maximum number of iterations. Each iteration corresponds # to one record from the (possibly aggregated) dataset. The task is # terminated when either number of iterations reaches iterationCount or # all records in the (possibly aggregated) database have been processed, # whichever occurs first. # # iterationCount of -1 = iterate over the entire dataset 'iterationCount' : -1, # Task Control parameters for OPFTaskDriver (per opfTaskControlSchema.json) 'taskControl' : { # Iteration cycle list consisting of opftaskdriver.IterationPhaseSpecXXXXX # instances. 'iterationCycle' : [ #IterationPhaseSpecLearnOnly(1000), IterationPhaseSpecLearnAndInfer(1000, inferenceArgs=None), #IterationPhaseSpecInferOnly(10, inferenceArgs=None), ], 'metrics' : [ ], # Logged Metrics: A sequence of regular expressions that specify which of # the metrics from the Inference Specifications section MUST be logged for # every prediction. The regex's correspond to the automatically generated # metric labels. This is similar to the way the optimization metric is # specified in permutations.py. 'loggedMetrics': ['.*grokScore.*'], # Callbacks for experimentation/research (optional) 'callbacks' : { # Callbacks to be called at the beginning of a task, before model iterations. # Signature: callback(<reference to OPFExperiment>); returns nothing # 'setup' : [claModelControlEnableSPLearningCb, claModelControlEnableTPLearningCb], # 'setup' : [claModelControlDisableTPLearningCb], 'setup' : [], # Callbacks to be called after every learning/inference iteration # Signature: callback(<reference to OPFExperiment>); returns nothing 'postIter' : [], # Callbacks to be called when the experiment task is finished # Signature: callback(<reference to OPFExperiment>); returns nothing 'finish' : [] } } # End of taskControl }, # End of task ] ) ################################################################################ ################################################################################ descriptionInterface = ExperimentDescriptionAPI(modelConfig=config, control=control)
gpl-3.0
HidinMTA/mtasa-blue
vendor/google-breakpad/src/tools/gyp/test/actions/gyptest-generated-header.py
187
1124
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that dependencies on generated headers work, even if the header has a mixed-case file name. """ import TestGyp test = TestGyp.TestGyp() CHDIR = 'generated-header' test.run_gyp('test.gyp', chdir=CHDIR) test.build('test.gyp', 'program', chdir=CHDIR) test.up_to_date('test.gyp', 'program', chdir=CHDIR) expect = 'foobar output\n' test.run_built_executable('program', chdir=CHDIR, stdout=expect) # Change what's written to the generated header, regyp and rebuild, and check # that the change makes it to the executable and that the build is clean. test.sleep() test.write('generated-header/test.gyp', test.read('generated-header/test.gyp').replace('foobar', 'barbaz')) test.run_gyp('test.gyp', chdir=CHDIR) test.build('test.gyp', 'program', chdir=CHDIR) test.up_to_date('test.gyp', 'program', chdir=CHDIR) expect = 'barbaz output\n' test.run_built_executable('program', chdir=CHDIR, stdout=expect) test.pass_test()
gpl-3.0
SpheMakh/Stimela
stimela/utils/logger.py
1
9243
import os import sys import json import yaml import time import subprocess from io import StringIO import codecs from datetime import datetime import logging class StimelaLogger(object): def __init__(self, lfile, jtype="docker"): self.lfile = lfile # Create file if it does not exist if not os.path.exists(self.lfile): with open(lfile, 'w') as wstd: wstd.write('{}') self.info = self.read(lfile) # First make sure that all fields are # initialised. Initialise if not so changed = False for item in ['images', 'containers', 'processes']: if self.info.get(item, None) is None: self.info[item] = {} changed = True if changed: self.write() self.jtype = jtype def _inspect(self, name): output = subprocess.check_output( "{0:s} inspect {1:s}".format(self.jtype, name), shell=True).decode() if self.jtype in ["docker", "podman"]: output_file = StringIO(output[3:-3]) else: output_file = StringIO(output) jdict = yaml.safe_load(output_file) output_file.close() return jdict def log_image(self, name, image_dir, replace=True, cab=False): info = self._inspect(name) if self.jtype in ["docker", "podman"]: if name not in self.info['images'].keys() or replace: self.info['images'][name] = { 'TIME': info['Created'].split('.')[0].replace('Z', '0'), 'ID': info['Id'].split(':')[-1], 'CAB': cab, 'DIR': image_dir, } else: print('Image {0} has already been logged.'.format(name)) else: if name not in self.info['images'].keys() or replace: self.info['images'][name] = { 'TIME': info['created'].split('.')[0].replace('Z', '0'), 'ID': info['id'], 'CAB': cab, 'DIR': image_dir, } else: print('Image {0} has already been logged.'.format(name)) def log_container(self, name): info = self._inspect(name) if self.jtype in ["docker", "podman"]: if name not in self.info['containers'].keys(): self.info['containers'][name] = { 'TIME': info['Created'].split('.')[0].replace('Z', '0'), 'IMAGE': info['Config']['Image'], 'ID': info['Id'], } else: print('contaier {0} has already been logged.'.format(name)) else: if name not in self.info['containers'].keys(): self.info['containers'][name] = { 'TIME': info['created'].split('.')[0].replace('Z', '0'), 'IMAGE': info['config']['Image'], 'ID': info['id'], } else: print('contaier {0} has already been logged.'.format(name)) def log_process(self, pid, name): pid = str(pid) timestamp = time.strftime('%Y-%m-%dT%H:%M:%S', time.gmtime()) if pid not in self.info['processes'].keys(): self.info['processes'][pid] = { 'NAME': name, 'TIME': timestamp, } else: print('PID {0} has already been logged.'.format(pid)) def remove(self, ltype, name): try: self.info[ltype].pop(str(name)) except: print('WARNING:: Could not remove object \'{0}:{1}\' from logger'.format( ltype, name)) def read(self, lfile=None): try: with open(lfile or self.lfile) as _std: jdict = yaml.safe_load(_std) except IOError: return {} return jdict def write(self, lfile=None): with codecs.open(lfile or self.lfile, 'w', 'utf8') as std: std.write(json.dumps(self.info, ensure_ascii=False, indent=4)) def clear(self, ltype): self.info[ltype] = {} def display(self, ltype): things = sorted(self.info[ltype].items(), key=lambda a: a[1]['TIME']) if ltype == 'images': print('{0:<36} {1:<24} {2:<24}'.format( 'IMAGE', 'ID', 'CREATED/PULLED')) for name, thing in things: print('{0:<36} {1:<24} {2:<24}'.format( name, thing['ID'][:8], thing['TIME'])) if ltype == 'containers': print('{0:<36} {1:<24} {2:<24} {3:<24} {4:<24}'.format( 'CONTAINER', 'CAB IMAGE', 'ID', 'STARTED', 'UPTIME')) for name, thing in things: started = datetime.strptime(thing['TIME'], '%Y-%m-%dT%H:%M:%S') finished = datetime.utcnow() mins = (finished - started).total_seconds()/60 hours, mins = divmod(mins, 60) mins, secs = divmod(mins*60, 60) uptime = '{0:d}:{1:d}:{2:.2f}'.format( int(hours), int(mins), secs) print('{0:<36} {1:<24} {2:<24} {3:<24} {4:<24}'.format( name, thing['IMAGE'], thing['ID'][:8], thing['TIME'], uptime)) if ltype == 'processes': print('{0:<36} {1:<24} {2:<24} {3:24}'.format( 'PID', 'NAME', 'STARTED', 'UPTIME')) for name, thing in things: started = datetime.strptime(thing['TIME'], '%Y-%m-%dT%H:%M:%S') finished = datetime.utcnow() mins = (finished - started).total_seconds()/60 hours, mins = divmod(mins, 60) mins, secs = divmod(mins*60, 60) uptime = '{0:d}:{1:d}:{2:.2f}'.format( int(hours), int(mins), secs) print('{0:<36} {1:<24} {2:<24} {3:24}'.format( name, thing['NAME'], thing['TIME'], uptime)) class MultiplexingHandler(logging.Handler): """handler to send INFO and below to stdout, everything above to stderr""" def __init__(self, info_stream=sys.stdout, err_stream=sys.stderr): super(MultiplexingHandler, self).__init__() self.info_handler = logging.StreamHandler(info_stream) self.err_handler = logging.StreamHandler(err_stream) self.multiplex = True def emit(self, record): handler = self.err_handler if record.levelno > logging.INFO and self.multiplex else self.info_handler handler.emit(record) # ignore broken pipes, this often happens when cleaning up and exiting try: handler.flush() except BrokenPipeError: pass def flush(self): try: self.err_handler.flush() self.info_handler.flush() except BrokenPipeError: pass def close(self): self.err_handler.close() self.info_handler.close() def setFormatter(self, fmt): self.err_handler.setFormatter(fmt) self.info_handler.setFormatter(fmt) class ConsoleColors(): WARNING = '\033[93m' if sys.stdin.isatty() else '' ERROR = '\033[91m' if sys.stdin.isatty() else '' BOLD = '\033[1m' if sys.stdin.isatty() else '' DIM = '\033[2m' if sys.stdin.isatty() else '' GREEN = '\033[92m' if sys.stdin.isatty() else '' ENDC = '\033[0m' if sys.stdin.isatty() else '' BEGIN = "<COLORIZE>" END = "</COLORIZE>" @staticmethod def colorize(msg, *styles): style = "".join(styles) return msg.replace(ConsoleColors.BEGIN, style).replace(ConsoleColors.END, ConsoleColors.ENDC if style else "") class ColorizingFormatter(logging.Formatter): """This Formatter inserts color codes into the string according to severity""" def __init__(self, fmt=None, datefmt=None, style="%", default_color=None): super(ColorizingFormatter, self).__init__(fmt, datefmt, style) self._default_color = default_color or "" def format(self, record): style = ConsoleColors.BOLD if hasattr(record, 'boldface') else "" if hasattr(record, 'color'): style += getattr(ConsoleColors, record.color or "None", "") elif record.levelno >= logging.ERROR: style += ConsoleColors.ERROR elif record.levelno >= logging.WARNING: style += ConsoleColors.WARNING return ConsoleColors.colorize(super(ColorizingFormatter, self).format(record), style or self._default_color) class SelectiveFormatter(logging.Formatter): """Selective formatter. if condition(record) is True, invokes other formatter""" def __init__(self, default_formatter, dispatch_list): self._dispatch_list = dispatch_list self._default_formatter = default_formatter def format(self, record): for condition, formatter in self._dispatch_list: if condition(record): return formatter.format(record) else: return self._default_formatter.format(record)
gpl-2.0
UnrememberMe/pants
src/python/pants/backend/graph_info/tasks/list_owners.py
15
1960
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import json from pants.base.exceptions import TaskError from pants.build_graph.source_mapper import LazySourceMapper from pants.task.console_task import ConsoleTask class ListOwners(ConsoleTask): """Print targets that own a source file. $ pants targets -- path/to/my/source.java path/to/my:target1 another/path:target2 """ @classmethod def register_options(cls, register): super(ListOwners, cls).register_options(register) # TODO: consider refactoring out common output format methods into MultiFormatConsoleTask. register('--output-format', default='text', choices=['text', 'json'], help='Output format of results.') @classmethod def supports_passthru_args(cls): return True def console_output(self, targets): sources = self.get_passthru_args() if not sources: raise TaskError('No source was specified') lazy_source_mapper = LazySourceMapper(self.context.address_mapper, self.context.build_graph) owner_info = {} for source in sources: owner_info[source] = [] target_addresses_for_source = lazy_source_mapper.target_addresses_for_source(source) for address in target_addresses_for_source: owner_info[source].append(address.spec) if self.get_options().output_format == 'json': yield json.dumps(owner_info, indent=4, separators=(',', ': ')) else: if len(sources) > 1: raise TaskError('Too many sources specified for {} output format.' .format(self.get_options().output_format)) if owner_info.values(): for address_spec in owner_info.values()[0]: yield address_spec
apache-2.0
olapaola/olapaola-android-scripting
python/src/Lib/test/test_urllib2_localnet.py
48
16942
#!/usr/bin/env python import mimetools import threading import urlparse import urllib2 import BaseHTTPServer import unittest import hashlib from test import test_support # Loopback http server infrastructure class LoopbackHttpServer(BaseHTTPServer.HTTPServer): """HTTP server w/ a few modifications that make it useful for loopback testing purposes. """ def __init__(self, server_address, RequestHandlerClass): BaseHTTPServer.HTTPServer.__init__(self, server_address, RequestHandlerClass) # Set the timeout of our listening socket really low so # that we can stop the server easily. self.socket.settimeout(1.0) def get_request(self): """BaseHTTPServer method, overridden.""" request, client_address = self.socket.accept() # It's a loopback connection, so setting the timeout # really low shouldn't affect anything, but should make # deadlocks less likely to occur. request.settimeout(10.0) return (request, client_address) class LoopbackHttpServerThread(threading.Thread): """Stoppable thread that runs a loopback http server.""" def __init__(self, request_handler): threading.Thread.__init__(self) self._stop = False self.ready = threading.Event() request_handler.protocol_version = "HTTP/1.0" self.httpd = LoopbackHttpServer(('127.0.0.1', 0), request_handler) #print "Serving HTTP on %s port %s" % (self.httpd.server_name, # self.httpd.server_port) self.port = self.httpd.server_port def stop(self): """Stops the webserver if it's currently running.""" # Set the stop flag. self._stop = True self.join() def run(self): self.ready.set() while not self._stop: self.httpd.handle_request() # Authentication infrastructure class DigestAuthHandler: """Handler for performing digest authentication.""" def __init__(self): self._request_num = 0 self._nonces = [] self._users = {} self._realm_name = "Test Realm" self._qop = "auth" def set_qop(self, qop): self._qop = qop def set_users(self, users): assert isinstance(users, dict) self._users = users def set_realm(self, realm): self._realm_name = realm def _generate_nonce(self): self._request_num += 1 nonce = hashlib.md5(str(self._request_num)).hexdigest() self._nonces.append(nonce) return nonce def _create_auth_dict(self, auth_str): first_space_index = auth_str.find(" ") auth_str = auth_str[first_space_index+1:] parts = auth_str.split(",") auth_dict = {} for part in parts: name, value = part.split("=") name = name.strip() if value[0] == '"' and value[-1] == '"': value = value[1:-1] else: value = value.strip() auth_dict[name] = value return auth_dict def _validate_auth(self, auth_dict, password, method, uri): final_dict = {} final_dict.update(auth_dict) final_dict["password"] = password final_dict["method"] = method final_dict["uri"] = uri HA1_str = "%(username)s:%(realm)s:%(password)s" % final_dict HA1 = hashlib.md5(HA1_str).hexdigest() HA2_str = "%(method)s:%(uri)s" % final_dict HA2 = hashlib.md5(HA2_str).hexdigest() final_dict["HA1"] = HA1 final_dict["HA2"] = HA2 response_str = "%(HA1)s:%(nonce)s:%(nc)s:" \ "%(cnonce)s:%(qop)s:%(HA2)s" % final_dict response = hashlib.md5(response_str).hexdigest() return response == auth_dict["response"] def _return_auth_challenge(self, request_handler): request_handler.send_response(407, "Proxy Authentication Required") request_handler.send_header("Content-Type", "text/html") request_handler.send_header( 'Proxy-Authenticate', 'Digest realm="%s", ' 'qop="%s",' 'nonce="%s", ' % \ (self._realm_name, self._qop, self._generate_nonce())) # XXX: Not sure if we're supposed to add this next header or # not. #request_handler.send_header('Connection', 'close') request_handler.end_headers() request_handler.wfile.write("Proxy Authentication Required.") return False def handle_request(self, request_handler): """Performs digest authentication on the given HTTP request handler. Returns True if authentication was successful, False otherwise. If no users have been set, then digest auth is effectively disabled and this method will always return True. """ if len(self._users) == 0: return True if not request_handler.headers.has_key('Proxy-Authorization'): return self._return_auth_challenge(request_handler) else: auth_dict = self._create_auth_dict( request_handler.headers['Proxy-Authorization'] ) if self._users.has_key(auth_dict["username"]): password = self._users[ auth_dict["username"] ] else: return self._return_auth_challenge(request_handler) if not auth_dict.get("nonce") in self._nonces: return self._return_auth_challenge(request_handler) else: self._nonces.remove(auth_dict["nonce"]) auth_validated = False # MSIE uses short_path in its validation, but Python's # urllib2 uses the full path, so we're going to see if # either of them works here. for path in [request_handler.path, request_handler.short_path]: if self._validate_auth(auth_dict, password, request_handler.command, path): auth_validated = True if not auth_validated: return self._return_auth_challenge(request_handler) return True # Proxy test infrastructure class FakeProxyHandler(BaseHTTPServer.BaseHTTPRequestHandler): """This is a 'fake proxy' that makes it look like the entire internet has gone down due to a sudden zombie invasion. It main utility is in providing us with authentication support for testing. """ digest_auth_handler = DigestAuthHandler() def log_message(self, format, *args): # Uncomment the next line for debugging. #sys.stderr.write(format % args) pass def do_GET(self): (scm, netloc, path, params, query, fragment) = urlparse.urlparse( self.path, 'http') self.short_path = path if self.digest_auth_handler.handle_request(self): self.send_response(200, "OK") self.send_header("Content-Type", "text/html") self.end_headers() self.wfile.write("You've reached %s!<BR>" % self.path) self.wfile.write("Our apologies, but our server is down due to " "a sudden zombie invasion.") # Test cases class ProxyAuthTests(unittest.TestCase): URL = "http://localhost" USER = "tester" PASSWD = "test123" REALM = "TestRealm" def setUp(self): FakeProxyHandler.digest_auth_handler.set_users({ self.USER : self.PASSWD }) FakeProxyHandler.digest_auth_handler.set_realm(self.REALM) self.server = LoopbackHttpServerThread(FakeProxyHandler) self.server.start() self.server.ready.wait() proxy_url = "http://127.0.0.1:%d" % self.server.port handler = urllib2.ProxyHandler({"http" : proxy_url}) self._digest_auth_handler = urllib2.ProxyDigestAuthHandler() self.opener = urllib2.build_opener(handler, self._digest_auth_handler) def tearDown(self): self.server.stop() def test_proxy_with_bad_password_raises_httperror(self): self._digest_auth_handler.add_password(self.REALM, self.URL, self.USER, self.PASSWD+"bad") FakeProxyHandler.digest_auth_handler.set_qop("auth") self.assertRaises(urllib2.HTTPError, self.opener.open, self.URL) def test_proxy_with_no_password_raises_httperror(self): FakeProxyHandler.digest_auth_handler.set_qop("auth") self.assertRaises(urllib2.HTTPError, self.opener.open, self.URL) def test_proxy_qop_auth_works(self): self._digest_auth_handler.add_password(self.REALM, self.URL, self.USER, self.PASSWD) FakeProxyHandler.digest_auth_handler.set_qop("auth") result = self.opener.open(self.URL) while result.read(): pass result.close() def test_proxy_qop_auth_int_works_or_throws_urlerror(self): self._digest_auth_handler.add_password(self.REALM, self.URL, self.USER, self.PASSWD) FakeProxyHandler.digest_auth_handler.set_qop("auth-int") try: result = self.opener.open(self.URL) except urllib2.URLError: # It's okay if we don't support auth-int, but we certainly # shouldn't receive any kind of exception here other than # a URLError. result = None if result: while result.read(): pass result.close() def GetRequestHandler(responses): class FakeHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): server_version = "TestHTTP/" requests = [] headers_received = [] port = 80 def do_GET(self): body = self.send_head() if body: self.wfile.write(body) def do_POST(self): content_length = self.headers['Content-Length'] post_data = self.rfile.read(int(content_length)) self.do_GET() self.requests.append(post_data) def send_head(self): FakeHTTPRequestHandler.headers_received = self.headers self.requests.append(self.path) response_code, headers, body = responses.pop(0) self.send_response(response_code) for (header, value) in headers: self.send_header(header, value % self.port) if body: self.send_header('Content-type', 'text/plain') self.end_headers() return body self.end_headers() def log_message(self, *args): pass return FakeHTTPRequestHandler class TestUrlopen(unittest.TestCase): """Tests urllib2.urlopen using the network. These tests are not exhaustive. Assuming that testing using files does a good job overall of some of the basic interface features. There are no tests exercising the optional 'data' and 'proxies' arguments. No tests for transparent redirection have been written. """ def start_server(self, responses): handler = GetRequestHandler(responses) self.server = LoopbackHttpServerThread(handler) self.server.start() self.server.ready.wait() port = self.server.port handler.port = port return handler def test_redirection(self): expected_response = 'We got here...' responses = [ (302, [('Location', 'http://localhost:%s/somewhere_else')], ''), (200, [], expected_response) ] handler = self.start_server(responses) try: f = urllib2.urlopen('http://localhost:%s/' % handler.port) data = f.read() f.close() self.assertEquals(data, expected_response) self.assertEquals(handler.requests, ['/', '/somewhere_else']) finally: self.server.stop() def test_404(self): expected_response = 'Bad bad bad...' handler = self.start_server([(404, [], expected_response)]) try: try: urllib2.urlopen('http://localhost:%s/weeble' % handler.port) except urllib2.URLError, f: pass else: self.fail('404 should raise URLError') data = f.read() f.close() self.assertEquals(data, expected_response) self.assertEquals(handler.requests, ['/weeble']) finally: self.server.stop() def test_200(self): expected_response = 'pycon 2008...' handler = self.start_server([(200, [], expected_response)]) try: f = urllib2.urlopen('http://localhost:%s/bizarre' % handler.port) data = f.read() f.close() self.assertEquals(data, expected_response) self.assertEquals(handler.requests, ['/bizarre']) finally: self.server.stop() def test_200_with_parameters(self): expected_response = 'pycon 2008...' handler = self.start_server([(200, [], expected_response)]) try: f = urllib2.urlopen('http://localhost:%s/bizarre' % handler.port, 'get=with_feeling') data = f.read() f.close() self.assertEquals(data, expected_response) self.assertEquals(handler.requests, ['/bizarre', 'get=with_feeling']) finally: self.server.stop() def test_sending_headers(self): handler = self.start_server([(200, [], "we don't care")]) try: req = urllib2.Request("http://localhost:%s/" % handler.port, headers={'Range': 'bytes=20-39'}) urllib2.urlopen(req) self.assertEqual(handler.headers_received['Range'], 'bytes=20-39') finally: self.server.stop() def test_basic(self): handler = self.start_server([(200, [], "we don't care")]) try: open_url = urllib2.urlopen("http://localhost:%s" % handler.port) for attr in ("read", "close", "info", "geturl"): self.assert_(hasattr(open_url, attr), "object returned from " "urlopen lacks the %s attribute" % attr) try: self.assert_(open_url.read(), "calling 'read' failed") finally: open_url.close() finally: self.server.stop() def test_info(self): handler = self.start_server([(200, [], "we don't care")]) try: open_url = urllib2.urlopen("http://localhost:%s" % handler.port) info_obj = open_url.info() self.assert_(isinstance(info_obj, mimetools.Message), "object returned by 'info' is not an instance of " "mimetools.Message") self.assertEqual(info_obj.getsubtype(), "plain") finally: self.server.stop() def test_geturl(self): # Make sure same URL as opened is returned by geturl. handler = self.start_server([(200, [], "we don't care")]) try: open_url = urllib2.urlopen("http://localhost:%s" % handler.port) url = open_url.geturl() self.assertEqual(url, "http://localhost:%s" % handler.port) finally: self.server.stop() def test_bad_address(self): # Make sure proper exception is raised when connecting to a bogus # address. self.assertRaises(IOError, # SF patch 809915: In Sep 2003, VeriSign started # highjacking invalid .com and .net addresses to # boost traffic to their own site. This test # started failing then. One hopes the .invalid # domain will be spared to serve its defined # purpose. # urllib2.urlopen, "http://www.sadflkjsasadf.com/") urllib2.urlopen, "http://sadflkjsasf.i.nvali.d/") def test_main(): # We will NOT depend on the network resource flag # (Lib/test/regrtest.py -u network) since all tests here are only # localhost. However, if this is a bad rationale, then uncomment # the next line. #test_support.requires("network") test_support.run_unittest(ProxyAuthTests) test_support.run_unittest(TestUrlopen) if __name__ == "__main__": test_main()
apache-2.0
haeusser/tensorflow
tensorflow/contrib/distributions/python/ops/bijectors/affine_linear_operator.py
25
8719
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """AffineLinearOperator bijector.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.distributions.python.ops.bijectors import bijector from tensorflow.contrib.distributions.python.ops.shape import _DistributionShape from tensorflow.contrib.linalg.python.ops import linear_operator from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import check_ops from tensorflow.python.ops import control_flow_ops __all__ = [ "AffineLinearOperator", ] class AffineLinearOperator(bijector.Bijector): """Compute `Y = g(X; shift, scale) = scale @ X + shift`. `shift` is a numeric `Tensor` and `scale` is a `LinearOperator`. If `X` is a scalar then the forward transformation is: `scale * X + shift` where `*` denotes the scalar product. Note: we don't always simply transpose `X` (but write it this way for brevity). Actually the input `X` undergoes the following transformation before being premultiplied by `scale`: 1. If there are no sample dims, we call `X = tf.expand_dims(X, 0)`, i.e., `new_sample_shape = [1]`. Otherwise do nothing. 2. The sample shape is flattened to have one dimension, i.e., `new_sample_shape = [n]` where `n = tf.reduce_prod(old_sample_shape)`. 3. The sample dim is cyclically rotated left by 1, i.e., `new_shape = [B1,...,Bb, k, n]` where `n` is as above, `k` is the event_shape, and `B1,...,Bb` are the batch shapes for each of `b` batch dimensions. (For more details see `shape.make_batch_of_event_sample_matrices`.) The result of the above transformation is that `X` can be regarded as a batch of matrices where each column is a draw from the distribution. After premultiplying by `scale`, we take the inverse of this procedure. The input `Y` also undergoes the same transformation before/after premultiplying by `inv(scale)`. Example Use: ```python linalg = tf.contrib.linalg x = [1., 2, 3] shift = [-1., 0., 1] diag = [1., 2, 3] scale = linalg.LinearOperatorDiag(diag) affine = AffineLinearOperator(shift, scale) # In this case, `forward` is equivalent to: # y = scale @ x + shift y = affine.forward(x) # [0., 4, 10] shift = [2., 3, 1] tril = [[1., 0, 0], [2, 1, 0], [3, 2, 1]] scale = linalg.LinearOperatorTriL(tril) affine = AffineLinearOperator(shift, scale) # In this case, `forward` is equivalent to: # np.squeeze(np.matmul(tril, np.expand_dims(x, -1)), -1) + shift y = affine.forward(x) # [3., 7, 11] ``` """ def __init__(self, shift=None, scale=None, event_ndims=1, validate_args=False, name="affine_linear_operator"): """Instantiates the `AffineLinearOperator` bijector. Args: shift: Floating-point `Tensor`. scale: Subclass of `LinearOperator`. Represents the (batch) positive definite matrix `M` in `R^{k x k}`. event_ndims: Scalar `integer` `Tensor` indicating the number of dimensions associated with a particular draw from the distribution. Must be 0 or 1. validate_args: Python `bool` indicating whether arguments should be checked for correctness. name: Python `str` name given to ops managed by this object. Raises: ValueError: if `event_ndims` is not 0 or 1. TypeError: if `scale` is not a `LinearOperator`. TypeError: if `shift.dtype` does not match `scale.dtype`. ValueError: if not `scale.is_non_singular`. """ self._graph_parents = [] self._name = name self._validate_args = validate_args graph_parents = [] with self._name_scope("init", values=[shift]): event_ndims = ops.convert_to_tensor(event_ndims, name="event_ndims") if tensor_util.constant_value(event_ndims) is not None: event_ndims = tensor_util.constant_value(event_ndims) if event_ndims not in (0, 1): raise ValueError("event_ndims({}) was not 0 or 1".format(event_ndims)) else: if validate_args: # Shape tool will catch if event_ndims is negative. event_ndims = control_flow_ops.with_dependencies( [check_ops.assert_less( event_ndims, 2, message="event_ndims must be 0 or 1")], event_ndims) graph_parents += [event_ndims] # In the absence of `loc` and `scale`, we'll assume `dtype` is `float32`. dtype = dtypes.float32 if shift is not None: shift = ops.convert_to_tensor(shift, name="shift") graph_parents += [shift] dtype = shift.dtype.base_dtype self._shift = shift if scale is not None: if (shift is not None and shift.dtype.base_dtype != scale.dtype.base_dtype): raise TypeError( "shift.dtype({}) is incompatible with scale.dtype({}).".format( shift.dtype, scale.dtype)) if not isinstance(scale, linear_operator.LinearOperator): raise TypeError("scale is not an instance of tf.LinearOperator") if validate_args and not scale.is_non_singular: raise ValueError("Scale matrix must be non-singular.") graph_parents += scale.graph_parents if scale.tensor_rank is not None: batch_ndims = scale.tensor_rank - 2 else: batch_ndims = scale.tensor_rank_tensor() - 2 graph_parents += [batch_ndims] if scale.dtype is not None: dtype = scale.dtype.base_dtype else: batch_ndims = 0 # We won't need shape inference when scale is None. self._scale = scale self._shaper = _DistributionShape( batch_ndims=batch_ndims, event_ndims=event_ndims, validate_args=validate_args) super(AffineLinearOperator, self).__init__( event_ndims=event_ndims, graph_parents=graph_parents, is_constant_jacobian=True, dtype=dtype, validate_args=validate_args, name=name) @property def shift(self): """The `shift` `Tensor` in `Y = scale @ X + shift`.""" return self._shift @property def scale(self): """The `scale` `LinearOperator` in `Y = scale @ X + shift`.""" return self._scale def _forward(self, x): y = x if self.scale is not None: y, sample_shape = self._shaper.make_batch_of_event_sample_matrices( y, expand_batch_dim=False) with ops.control_dependencies(self._maybe_collect_assertions() if self.validate_args else []): y = self.scale.apply(y) y = self._shaper.undo_make_batch_of_event_sample_matrices( y, sample_shape, expand_batch_dim=False) if self.shift is not None: y += self.shift return y def _inverse(self, y): x = y if self.shift is not None: x -= self.shift if self.scale is not None: x, sample_shape = self._shaper.make_batch_of_event_sample_matrices( x, expand_batch_dim=False) # Solve fails if the op is singular so we may safely skip this assertion. x = self.scale.solve(x) x = self._shaper.undo_make_batch_of_event_sample_matrices( x, sample_shape, expand_batch_dim=False) return x def _inverse_log_det_jacobian(self, y): return -self._forward_log_det_jacobian(y) def _forward_log_det_jacobian(self, x): # pylint: disable=unused-argument if self.scale is None: return constant_op.constant(0, dtype=x.dtype.base_dtype) with ops.control_dependencies(self._maybe_collect_assertions() if self.validate_args else []): return self.scale.log_abs_determinant() def _maybe_collect_assertions(self): try: return [self.scale.assert_non_singular()] except NotImplementedError: pass return []
apache-2.0
Changaco/oh-mainline
vendor/packages/Django/tests/regressiontests/comment_tests/tests/feed_tests.py
47
1915
from __future__ import absolute_import from xml.etree import ElementTree as ET from django.conf import settings from django.contrib.comments.models import Comment from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from . import CommentTestCase from ..models import Article class CommentFeedTests(CommentTestCase): urls = 'regressiontests.comment_tests.urls' feed_url = '/rss/comments/' def setUp(self): site_2 = Site.objects.create(id=settings.SITE_ID+1, domain="example2.com", name="example2.com") # A comment for another site c5 = Comment.objects.create( content_type = ContentType.objects.get_for_model(Article), object_pk = "1", user_name = "Joe Somebody", user_email = "jsomebody@example.com", user_url = "http://example.com/~joe/", comment = "A comment for the second site.", site = site_2, ) def test_feed(self): response = self.client.get(self.feed_url) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/rss+xml; charset=utf-8') rss_elem = ET.fromstring(response.content) self.assertEqual(rss_elem.tag, "rss") self.assertEqual(rss_elem.attrib, {"version": "2.0"}) channel_elem = rss_elem.find("channel") title_elem = channel_elem.find("title") self.assertEqual(title_elem.text, "example.com comments") link_elem = channel_elem.find("link") self.assertEqual(link_elem.text, "http://example.com/") atomlink_elem = channel_elem.find("{http://www.w3.org/2005/Atom}link") self.assertEqual(atomlink_elem.attrib, {"href": "http://example.com/rss/comments/", "rel": "self"}) self.assertNotContains(response, "A comment for the second site.")
agpl-3.0
40223108/w18
static/Brython3.1.3-20150514-095342/Lib/unittest/test/test_runner.py
785
10718
import io import os import sys import pickle import subprocess import unittest from .support import LoggingResult, ResultWithNoStartTestRunStopTestRun class TestCleanUp(unittest.TestCase): def testCleanUp(self): class TestableTest(unittest.TestCase): def testNothing(self): pass test = TestableTest('testNothing') self.assertEqual(test._cleanups, []) cleanups = [] def cleanup1(*args, **kwargs): cleanups.append((1, args, kwargs)) def cleanup2(*args, **kwargs): cleanups.append((2, args, kwargs)) test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye') test.addCleanup(cleanup2) self.assertEqual(test._cleanups, [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')), (cleanup2, (), {})]) self.assertTrue(test.doCleanups()) self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))]) def testCleanUpWithErrors(self): class TestableTest(unittest.TestCase): def testNothing(self): pass class MockOutcome(object): success = True errors = [] test = TestableTest('testNothing') test._outcomeForDoCleanups = MockOutcome exc1 = Exception('foo') exc2 = Exception('bar') def cleanup1(): raise exc1 def cleanup2(): raise exc2 test.addCleanup(cleanup1) test.addCleanup(cleanup2) self.assertFalse(test.doCleanups()) self.assertFalse(MockOutcome.success) (Type1, instance1, _), (Type2, instance2, _) = reversed(MockOutcome.errors) self.assertEqual((Type1, instance1), (Exception, exc1)) self.assertEqual((Type2, instance2), (Exception, exc2)) def testCleanupInRun(self): blowUp = False ordering = [] class TestableTest(unittest.TestCase): def setUp(self): ordering.append('setUp') if blowUp: raise Exception('foo') def testNothing(self): ordering.append('test') def tearDown(self): ordering.append('tearDown') test = TestableTest('testNothing') def cleanup1(): ordering.append('cleanup1') def cleanup2(): ordering.append('cleanup2') test.addCleanup(cleanup1) test.addCleanup(cleanup2) def success(some_test): self.assertEqual(some_test, test) ordering.append('success') result = unittest.TestResult() result.addSuccess = success test.run(result) self.assertEqual(ordering, ['setUp', 'test', 'tearDown', 'cleanup2', 'cleanup1', 'success']) blowUp = True ordering = [] test = TestableTest('testNothing') test.addCleanup(cleanup1) test.run(result) self.assertEqual(ordering, ['setUp', 'cleanup1']) def testTestCaseDebugExecutesCleanups(self): ordering = [] class TestableTest(unittest.TestCase): def setUp(self): ordering.append('setUp') self.addCleanup(cleanup1) def testNothing(self): ordering.append('test') def tearDown(self): ordering.append('tearDown') test = TestableTest('testNothing') def cleanup1(): ordering.append('cleanup1') test.addCleanup(cleanup2) def cleanup2(): ordering.append('cleanup2') test.debug() self.assertEqual(ordering, ['setUp', 'test', 'tearDown', 'cleanup1', 'cleanup2']) class Test_TextTestRunner(unittest.TestCase): """Tests for TextTestRunner.""" def test_init(self): runner = unittest.TextTestRunner() self.assertFalse(runner.failfast) self.assertFalse(runner.buffer) self.assertEqual(runner.verbosity, 1) self.assertEqual(runner.warnings, None) self.assertTrue(runner.descriptions) self.assertEqual(runner.resultclass, unittest.TextTestResult) def testBufferAndFailfast(self): class Test(unittest.TestCase): def testFoo(self): pass result = unittest.TestResult() runner = unittest.TextTestRunner(stream=io.StringIO(), failfast=True, buffer=True) # Use our result object runner._makeResult = lambda: result runner.run(Test('testFoo')) self.assertTrue(result.failfast) self.assertTrue(result.buffer) def testRunnerRegistersResult(self): class Test(unittest.TestCase): def testFoo(self): pass originalRegisterResult = unittest.runner.registerResult def cleanup(): unittest.runner.registerResult = originalRegisterResult self.addCleanup(cleanup) result = unittest.TestResult() runner = unittest.TextTestRunner(stream=io.StringIO()) # Use our result object runner._makeResult = lambda: result self.wasRegistered = 0 def fakeRegisterResult(thisResult): self.wasRegistered += 1 self.assertEqual(thisResult, result) unittest.runner.registerResult = fakeRegisterResult runner.run(unittest.TestSuite()) self.assertEqual(self.wasRegistered, 1) def test_works_with_result_without_startTestRun_stopTestRun(self): class OldTextResult(ResultWithNoStartTestRunStopTestRun): separator2 = '' def printErrors(self): pass class Runner(unittest.TextTestRunner): def __init__(self): super(Runner, self).__init__(io.StringIO()) def _makeResult(self): return OldTextResult() runner = Runner() runner.run(unittest.TestSuite()) def test_startTestRun_stopTestRun_called(self): class LoggingTextResult(LoggingResult): separator2 = '' def printErrors(self): pass class LoggingRunner(unittest.TextTestRunner): def __init__(self, events): super(LoggingRunner, self).__init__(io.StringIO()) self._events = events def _makeResult(self): return LoggingTextResult(self._events) events = [] runner = LoggingRunner(events) runner.run(unittest.TestSuite()) expected = ['startTestRun', 'stopTestRun'] self.assertEqual(events, expected) def test_pickle_unpickle(self): # Issue #7197: a TextTestRunner should be (un)pickleable. This is # required by test_multiprocessing under Windows (in verbose mode). stream = io.StringIO("foo") runner = unittest.TextTestRunner(stream) for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1): s = pickle.dumps(runner, protocol) obj = pickle.loads(s) # StringIO objects never compare equal, a cheap test instead. self.assertEqual(obj.stream.getvalue(), stream.getvalue()) def test_resultclass(self): def MockResultClass(*args): return args STREAM = object() DESCRIPTIONS = object() VERBOSITY = object() runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY, resultclass=MockResultClass) self.assertEqual(runner.resultclass, MockResultClass) expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY) self.assertEqual(runner._makeResult(), expectedresult) def test_warnings(self): """ Check that warnings argument of TextTestRunner correctly affects the behavior of the warnings. """ # see #10535 and the _test_warnings file for more information def get_parse_out_err(p): return [b.splitlines() for b in p.communicate()] opts = dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(__file__)) ae_msg = b'Please use assertEqual instead.' at_msg = b'Please use assertTrue instead.' # no args -> all the warnings are printed, unittest warnings only once p = subprocess.Popen([sys.executable, '_test_warnings.py'], **opts) out, err = get_parse_out_err(p) self.assertIn(b'OK', err) # check that the total number of warnings in the output is correct self.assertEqual(len(out), 12) # check that the numbers of the different kind of warnings is correct for msg in [b'dw', b'iw', b'uw']: self.assertEqual(out.count(msg), 3) for msg in [ae_msg, at_msg, b'rw']: self.assertEqual(out.count(msg), 1) args_list = ( # passing 'ignore' as warnings arg -> no warnings [sys.executable, '_test_warnings.py', 'ignore'], # -W doesn't affect the result if the arg is passed [sys.executable, '-Wa', '_test_warnings.py', 'ignore'], # -W affects the result if the arg is not passed [sys.executable, '-Wi', '_test_warnings.py'] ) # in all these cases no warnings are printed for args in args_list: p = subprocess.Popen(args, **opts) out, err = get_parse_out_err(p) self.assertIn(b'OK', err) self.assertEqual(len(out), 0) # passing 'always' as warnings arg -> all the warnings printed, # unittest warnings only once p = subprocess.Popen([sys.executable, '_test_warnings.py', 'always'], **opts) out, err = get_parse_out_err(p) self.assertIn(b'OK', err) self.assertEqual(len(out), 14) for msg in [b'dw', b'iw', b'uw', b'rw']: self.assertEqual(out.count(msg), 3) for msg in [ae_msg, at_msg]: self.assertEqual(out.count(msg), 1) def testStdErrLookedUpAtInstantiationTime(self): # see issue 10786 old_stderr = sys.stderr f = io.StringIO() sys.stderr = f try: runner = unittest.TextTestRunner() self.assertTrue(runner.stream.stream is f) finally: sys.stderr = old_stderr def testSpecifiedStreamUsed(self): # see issue 10786 f = io.StringIO() runner = unittest.TextTestRunner(f) self.assertTrue(runner.stream.stream is f)
gpl-3.0
betatim/BlackBox
skopt/benchmarks.py
2
2905
# -*- coding: utf-8 -*- """A collection of benchmark problems.""" import numpy as np def bench1(x): """A benchmark function for test purposes. f(x) = x ** 2 It has a single minima with f(x*) = 0 at x* = 0. """ return x[0] ** 2 def bench1_with_time(x): """Same as bench1 but returns the computation time (constant).""" return x[0] ** 2, 2.22 def bench2(x): """A benchmark function for test purposes. f(x) = x ** 2 if x < 0 (x-5) ** 2 - 5 otherwise. It has a global minima with f(x*) = -5 at x* = 5. """ if x[0] < 0: return x[0] ** 2 else: return (x[0] - 5) ** 2 - 5 def bench3(x): """A benchmark function for test purposes. f(x) = sin(5*x) * (1 - tanh(x ** 2)) It has a global minima with f(x*) ~= -0.9 at x* ~= -0.3. """ return np.sin(5 * x[0]) * (1 - np.tanh(x[0] ** 2)) def bench4(x): """A benchmark function for test purposes. f(x) = float(x) ** 2 where x is a string. It has a single minima with f(x*) = 0 at x* = "0". This benchmark is used for checking support of categorical variables. """ return float(x[0]) ** 2 def bench5(x): """A benchmark function for test purposes. f(x) = float(x[0]) ** 2 + x[1] ** 2 where x is a string. It has a single minima with f(x) = 0 at x[0] = "0" and x[1] = "0" This benchmark is used for checking support of mixed spaces. """ return float(x[0]) ** 2 + x[1] ** 2 def branin(x, a=1, b=5.1 / (4 * np.pi**2), c=5. / np.pi, r=6, s=10, t=1. / (8 * np.pi)): """Branin-Hoo function is defined on the square x1 ∈ [-5, 10], x2 ∈ [0, 15]. It has three minima with f(x*) = 0.397887 at x* = (-pi, 12.275), (+pi, 2.275), and (9.42478, 2.475). More details: <http://www.sfu.ca/~ssurjano/branin.html> """ return (a * (x[1] - b * x[0] ** 2 + c * x[0] - r) ** 2 + s * (1 - t) * np.cos(x[0]) + s) def hart6(x, alpha=np.asarray([1.0, 1.2, 3.0, 3.2]), P=10**-4 * np.asarray([[1312, 1696, 5569, 124, 8283, 5886], [2329, 4135, 8307, 3736, 1004, 9991], [2348, 1451, 3522, 2883, 3047, 6650], [4047, 8828, 8732, 5743, 1091, 381]]), A=np.asarray([[10, 3, 17, 3.50, 1.7, 8], [0.05, 10, 17, 0.1, 8, 14], [3, 3.5, 1.7, 10, 17, 8], [17, 8, 0.05, 10, 0.1, 14]])): """The six dimensional Hartmann function is defined on the unit hypercube. It has six local minima and one global minimum f(x*) = -3.32237 at x* = (0.20169, 0.15001, 0.476874, 0.275332, 0.311652, 0.6573). More details: <http://www.sfu.ca/~ssurjano/hart6.html> """ return -np.sum(alpha * np.exp(-np.sum(A * (np.array(x) - P)**2, axis=1)))
bsd-3-clause
primiano/udoo_kernel_imx
tools/perf/scripts/python/failed-syscalls-by-pid.py
11180
2058
# failed system call counts, by pid # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Displays system-wide failed system call totals, broken down by pid. # If a [comm] arg is specified, only syscalls called by [comm] are displayed. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * usage = "perf script -s syscall-counts-by-pid.py [comm|pid]\n"; for_comm = None for_pid = None if len(sys.argv) > 2: sys.exit(usage) if len(sys.argv) > 1: try: for_pid = int(sys.argv[1]) except: for_comm = sys.argv[1] syscalls = autodict() def trace_begin(): print "Press control+C to stop and show the summary" def trace_end(): print_error_totals() def raw_syscalls__sys_exit(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, ret): if (for_comm and common_comm != for_comm) or \ (for_pid and common_pid != for_pid ): return if ret < 0: try: syscalls[common_comm][common_pid][id][ret] += 1 except TypeError: syscalls[common_comm][common_pid][id][ret] = 1 def print_error_totals(): if for_comm is not None: print "\nsyscall errors for %s:\n\n" % (for_comm), else: print "\nsyscall errors:\n\n", print "%-30s %10s\n" % ("comm [pid]", "count"), print "%-30s %10s\n" % ("------------------------------", \ "----------"), comm_keys = syscalls.keys() for comm in comm_keys: pid_keys = syscalls[comm].keys() for pid in pid_keys: print "\n%s [%d]\n" % (comm, pid), id_keys = syscalls[comm][pid].keys() for id in id_keys: print " syscall: %-16s\n" % syscall_name(id), ret_keys = syscalls[comm][pid][id].keys() for ret, val in sorted(syscalls[comm][pid][id].iteritems(), key = lambda(k, v): (v, k), reverse = True): print " err = %-20s %10d\n" % (strerror(ret), val),
gpl-2.0