This file is indexed.

/usr/share/pyshared/pycalendar/recurrence.py is in python-pycalendar 2.0~svn188-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
##
#    Copyright (c) 2007-2011 Cyrus Daboo. All rights reserved.
#    
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#    
#        http://www.apache.org/licenses/LICENSE-2.0
#    
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.
##

from pycalendar import definitions
from pycalendar import xmldefs
from pycalendar.datetime import PyCalendarDateTime
from pycalendar.period import PyCalendarPeriod
from pycalendar.valueutils import ValueMixin
import cStringIO as StringIO
import xml.etree.cElementTree as XML

def WeekDayNumCompare_compare(w1, w2):

    if w1[0] < w2[0]:
        return -1
    elif w1[0] > w2[0]:
        return 1
    elif w1[1] < w2[1]:
        return -1
    elif w1[1] > w2[1]:
        return 1
    else:
        return 0
        
def WeekDayNumSort_less_than(w1, w2):

    return (w1[0] < w2[0]) or (w1[0] == w2[0]) and (w1[1] < w2[1])

class PyCalendarRecurrence(ValueMixin):

    cFreqMap = {
        definitions.cICalValue_RECUR_SECONDLY : definitions.eRecurrence_SECONDLY,
        definitions.cICalValue_RECUR_MINUTELY : definitions.eRecurrence_MINUTELY,
        definitions.cICalValue_RECUR_HOURLY   : definitions.eRecurrence_HOURLY,
        definitions.cICalValue_RECUR_DAILY    : definitions.eRecurrence_DAILY,
        definitions.cICalValue_RECUR_WEEKLY   : definitions.eRecurrence_WEEKLY,
        definitions.cICalValue_RECUR_MONTHLY  : definitions.eRecurrence_MONTHLY,
        definitions.cICalValue_RECUR_YEARLY   : definitions.eRecurrence_YEARLY,
    }

    cFreqToXMLMap = {
        definitions.eRecurrence_SECONDLY: xmldefs.recur_freq_secondly,
        definitions.eRecurrence_MINUTELY: xmldefs.recur_freq_minutely,
        definitions.eRecurrence_HOURLY: xmldefs.recur_freq_hourly,
        definitions.eRecurrence_DAILY: xmldefs.recur_freq_daily,
        definitions.eRecurrence_WEEKLY: xmldefs.recur_freq_weekly,
        definitions.eRecurrence_MONTHLY: xmldefs.recur_freq_monthly,
        definitions.eRecurrence_YEARLY: xmldefs.recur_freq_yearly,
    }
    
    cRecurMap = {
        definitions.cICalValue_RECUR_FREQ       : definitions.eRecurrence_FREQ,
        definitions.cICalValue_RECUR_UNTIL      : definitions.eRecurrence_UNTIL,
        definitions.cICalValue_RECUR_COUNT      : definitions.eRecurrence_COUNT,
        definitions.cICalValue_RECUR_INTERVAL   : definitions.eRecurrence_INTERVAL,
        definitions.cICalValue_RECUR_BYSECOND   : definitions.eRecurrence_BYSECOND,
        definitions.cICalValue_RECUR_BYMINUTE   : definitions.eRecurrence_BYMINUTE,
        definitions.cICalValue_RECUR_BYHOUR     : definitions.eRecurrence_BYHOUR,
        definitions.cICalValue_RECUR_BYDAY      : definitions.eRecurrence_BYDAY,
        definitions.cICalValue_RECUR_BYMONTHDAY : definitions.eRecurrence_BYMONTHDAY,
        definitions.cICalValue_RECUR_BYYEARDAY  : definitions.eRecurrence_BYYEARDAY,
        definitions.cICalValue_RECUR_BYWEEKNO   : definitions.eRecurrence_BYWEEKNO,
        definitions.cICalValue_RECUR_BYMONTH    : definitions.eRecurrence_BYMONTH,
        definitions.cICalValue_RECUR_BYSETPOS   : definitions.eRecurrence_BYSETPOS,
        definitions.cICalValue_RECUR_WKST       : definitions.eRecurrence_WKST,
    }
    
    cWeekdayMap = {
        definitions.cICalValue_RECUR_WEEKDAY_SU : definitions.eRecurrence_WEEKDAY_SU,
        definitions.cICalValue_RECUR_WEEKDAY_MO : definitions.eRecurrence_WEEKDAY_MO,
        definitions.cICalValue_RECUR_WEEKDAY_TU : definitions.eRecurrence_WEEKDAY_TU,
        definitions.cICalValue_RECUR_WEEKDAY_WE : definitions.eRecurrence_WEEKDAY_WE,
        definitions.cICalValue_RECUR_WEEKDAY_TH : definitions.eRecurrence_WEEKDAY_TH,
        definitions.cICalValue_RECUR_WEEKDAY_FR : definitions.eRecurrence_WEEKDAY_FR,
        definitions.cICalValue_RECUR_WEEKDAY_SA : definitions.eRecurrence_WEEKDAY_SA,
    }
    
    cWeekdayRecurMap = dict([(v, k) for k, v in cWeekdayMap.items()])
         
    cUnknownIndex = -1

    def __init__(self):
        self.init_PyCalendarRecurrence()

    def duplicate(self):
        other = PyCalendarRecurrence()

        other.mFreq = self.mFreq

        other.mUseCount = self.mUseCount
        other.mCount = self.mCount
        other.mUseUntil = self.mUseUntil
        if other.mUseUntil:
            other.mUntil = self.mUntil.duplicate()

        other.mInterval = self.mInterval
        if self.mBySeconds is not None:
            other.mBySeconds = self.mBySeconds[:]
        if self.mByMinutes is not None:
            other.mByMinutes = self.mByMinutes[:]
        if self.mByHours is not None:
            other.mByHours = self.mByHours[:]
        if self.mByDay is not None:
            other.mByDay = self.mByDay[:]
        if self.mByMonthDay is not None:
            other.mByMonthDay = self.mByMonthDay[:]
        if self.mByYearDay is not None:
            other.mByYearDay = self.mByYearDay[:]
        if self.mByWeekNo is not None:
            other.mByWeekNo = self.mByWeekNo[:]
        if self.mByMonth is not None:
            other.mByMonth = self.mByMonth[:]
        if self.mBySetPos is not None:
            other.mBySetPos = self.mBySetPos[:]
        other.mWeekstart = self.mWeekstart

        other.mCached = self.mCached
        if self.mCacheStart:
            other.mCacheStart = self.mCacheStart.duplicate()
        if self.mCacheUpto:
            other.mCacheUpto = self.mCacheUpto.duplicate()
        other.mFullyCached = self.mFullyCached
        if self.mRecurrences:
            other.mRecurrences = self.mRecurrences[:]

        return other

    def init_PyCalendarRecurrence(self):
        self.mFreq = definitions.eRecurrence_YEARLY

        self.mUseCount = False
        self.mCount = 0

        self.mUseUntil = False
        self.mUntil = None

        self.mInterval = 1
        self.mBySeconds = None
        self.mByMinutes = None
        self.mByHours = None
        self.mByDay = None
        self.mByMonthDay = None
        self.mByYearDay = None
        self.mByWeekNo = None
        self.mByMonth = None
        self.mBySetPos = None
        self.mWeekstart = definitions.eRecurrence_WEEKDAY_MO

        self.mCached = False
        self.mCacheStart = None
        self.mCacheUpto = None
        self.mFullyCached = False
        self.mRecurrences = None

    def __hash__(self):
        return hash((
            self.mFreq,
            self.mUseCount,
            self.mCount,
            self.mUseUntil,
            self.mUntil,
            self.mInterval,
            tuple(self.mBySeconds) if self.mBySeconds else None,
            tuple(self.mByMinutes) if self.mByMinutes else None,
            tuple(self.mByHours) if self.mByHours else None,
            tuple(self.mByDay) if self.mByDay else None,
            tuple(self.mByMonthDay) if self.mByMonthDay else None,
            tuple(self.mByYearDay) if self.mByYearDay else None,
            tuple(self.mByWeekNo) if self.mByWeekNo else None,
            tuple(self.mByMonth) if self.mByMonth else None,
            tuple(self.mBySetPos) if self.mBySetPos else None,
            self.mWeekstart,
        ))

    def __ne__(self, other): return not self.__eq__(other)
    def __eq__(self, other):
        if not isinstance(other, PyCalendarRecurrence): return False
        return self.equals(other)

    def equals(self, comp):
        return (self.mFreq == comp.mFreq) \
                and (self.mUseCount == comp.mUseCount) and (self.mCount == comp.mCount) \
                and (self.mUseUntil == comp.mUseUntil) and (self.mUntil == comp.mUntil) \
                and (self.mInterval == comp.mInterval) \
                and self.equalsNum(self.mBySeconds, comp.mBySeconds) \
                and self.equalsNum(self.mByMinutes, comp.mByMinutes) \
                and self.equalsNum(self.mByHours, comp.mByHours) \
                and self.equalsDayNum(self.mByDay, comp.mByDay) \
                and self.equalsNum(self.mByMonthDay, comp.mByMonthDay) \
                and self.equalsNum(self.mByYearDay, comp.mByYearDay) \
                and self.equalsNum(self.mByWeekNo, comp.mByWeekNo) \
                and self.equalsNum(self.mByMonth, comp.mByMonth) \
                and self.equalsNum(self.mBySetPos, comp.mBySetPos) \
                and (self.mWeekstart == comp.mWeekstart)

    def equalsNum(self, items1, items2):
        # Check sizes first
        if items1 is None:
            items1 = []
        if items2 is None:
            items2 = []
        if len(items1) != len(items2):
            return False
        elif len(items1) == 0:
            return True

        # Copy and sort each one for comparison
        temp1 = items1[:]
        temp2 = items2[:]
        temp1.sort()
        temp2.sort()

        for i in range(0, len(temp1)):
            if temp1[i] != temp2[i]:
                return False
        return True

    def equalsDayNum(self, items1, items2):
        # Check sizes first
        if items1 is None:
            items1 = []
        if items2 is None:
            items2 = []
        if len(items1) != len(items2):
            return False
        elif len(items1) == 0:
            return True

        # Copy and sort each one for comparison
        temp1 = items1[:]
        temp2 = items2[:]
        temp1.sort()
        temp2.sort()

        for i in range(0, len(temp1)):
            if temp1[i] != temp2[i]:
                return False
        return True

    def getFreq(self):
        return self.mFreq

    def setFreq(self, freq):
        self.mFreq = freq

    def getUseUntil(self):
        return self.mUseUntil

    def setUseUntil(self, use_until):
        self.mUseUntil = use_until

    def getUntil(self):
        return self.mUntil

    def setUntil(self, until):
        self.mUntil = until

    def getUseCount(self):
        return self.mUseCount

    def setUseCount(self, use_count):
        self.mUseCount = use_count

    def getCount(self):
        return self.mCount

    def setCount(self, count):
        self.mCount = count

    def getInterval(self):
        return self.mInterval

    def setInterval(self, interval):
        self.mInterval = interval

    def getByMonth(self):
        return self.mByMonth

    def setByMonth(self, by):
        self.mByMonth = by[:]

    def getByMonthDay(self):
        return self.mByMonthDay

    def setByMonthDay(self, by):
        self.mByMonthDay = by[:]

    def getByYearDay(self):
        return self.mByYearDay

    def setByYearDay(self, by):
        self.mByYearDay = by[:]

    def getByDay(self):
        return self.mByDay

    def setByDay(self, by):
        self.mByDay = by[:]


    def getBySetPos(self):
        return self.mBySetPos

    def setBySetPos(self, by):
        self.mBySetPos = by

    def parse(self, data):
        self.init_PyCalendarRecurrence()

        # Tokenise using ''
        tokens = data.split(";")
        tokens.reverse()
           
        if len(tokens) == 0:
            raise ValueError("PyCalendarRecurrence: Invalid recurrence rule value")

        while len(tokens) != 0:
            # Get next token
            token = tokens.pop()
            try:
                tname, tvalue = token.split("=")
            except ValueError:
                raise ValueError("PyCalendarRecurrence: Invalid token '%s'" % (token,))

            # Determine token type
            index = PyCalendarRecurrence.cRecurMap.get(tname, PyCalendarRecurrence.cUnknownIndex)
            if index == PyCalendarRecurrence.cUnknownIndex:
                raise ValueError("PyCalendarRecurrence: Invalid token '%s'" % (tname,))

            # Parse remainder based on index
            if index == definitions.eRecurrence_FREQ:
                # Get the FREQ value
                index = PyCalendarRecurrence.cFreqMap.get(tvalue, PyCalendarRecurrence.cUnknownIndex)
                if index == PyCalendarRecurrence.cUnknownIndex:
                    raise ValueError("PyCalendarRecurrence: Invalid FREQ value")
                self.mFreq = index

            elif index == definitions.eRecurrence_UNTIL:
                if self.mUseCount:
                    raise ValueError("PyCalendarRecurrence: Can't have both UNTIL and COUNT")
                self.mUseUntil = True
                if self.mUntil is None:
                    self.mUntil = PyCalendarDateTime()
                try:
                    self.mUntil.parse(tvalue)
                except ValueError:
                    raise ValueError("PyCalendarRecurrence: Invalid UNTIL value")

            elif index == definitions.eRecurrence_COUNT:
                if self.mUseUntil:
                    raise ValueError("PyCalendarRecurrence: Can't have both UNTIL and COUNT")
                self.mUseCount = True
                try:
                    self.mCount = int(tvalue)
                except ValueError:
                    raise ValueError("PyCalendarRecurrence: Invalid COUNT value")

                # Must not be less than one
                if self.mCount < 1:
                    raise ValueError("PyCalendarRecurrence: Invalid COUNT value")

            elif index == definitions.eRecurrence_INTERVAL:
                try:
                    self.mInterval = int(tvalue)
                except ValueError:
                    raise ValueError("PyCalendarRecurrence: Invalid INTERVAL value")

                # Must NOT be less than one
                if self.mInterval < 1:
                    raise ValueError("PyCalendarRecurrence: Invalid INTERVAL value")
 
            elif index == definitions.eRecurrence_BYSECOND:
                if self.mBySeconds is not None:
                    raise ValueError("PyCalendarRecurrence: Only one BYSECOND allowed")
                self.mBySeconds = []
                self.parseList(tvalue, self.mBySeconds, 0, 60, errmsg="PyCalendarRecurrence: Invalid BYSECOND value")

            elif index == definitions.eRecurrence_BYMINUTE:
                if self.mByMinutes is not None:
                    raise ValueError("PyCalendarRecurrence: Only one BYMINUTE allowed")
                self.mByMinutes = []
                self.parseList(tvalue, self.mByMinutes, 0, 59, errmsg="PyCalendarRecurrence: Invalid BYMINUTE value")

            elif index == definitions.eRecurrence_BYHOUR:
                if self.mByHours is not None:
                    raise ValueError("PyCalendarRecurrence: Only one BYHOUR allowed")
                self.mByHours = []
                self.parseList(tvalue, self.mByHours, 0, 23, errmsg="PyCalendarRecurrence: Invalid BYHOUR value")                    

            elif index == definitions.eRecurrence_BYDAY:
                if self.mByDay is not None:
                    raise ValueError("PyCalendarRecurrence: Only one BYDAY allowed")
                self.mByDay = []
                self.parseListDW(tvalue, self.mByDay, errmsg="PyCalendarRecurrence: Invalid BYDAY value")                    

            elif index == definitions.eRecurrence_BYMONTHDAY:
                if self.mByMonthDay is not None:
                    raise ValueError("PyCalendarRecurrence: Only one BYMONTHDAY allowed")
                self.mByMonthDay = []
                self.parseList(tvalue, self.mByMonthDay, 1, 31, True, errmsg="PyCalendarRecurrence: Invalid BYMONTHDAY value")                    

            elif index == definitions.eRecurrence_BYYEARDAY:
                if self.mByYearDay is not None:
                    raise ValueError("PyCalendarRecurrence: Only one BYYEARDAY allowed")
                self.mByYearDay = []
                self.parseList(tvalue, self.mByYearDay, 1, 366, True, errmsg="PyCalendarRecurrence: Invalid BYYEARDAY value")                    

            elif index == definitions.eRecurrence_BYWEEKNO:
                if self.mByWeekNo is not None:
                    raise ValueError("PyCalendarRecurrence: Only one BYWEEKNO allowed")
                self.mByWeekNo = []
                self.parseList(tvalue, self.mByWeekNo, 1, 53, True, errmsg="PyCalendarRecurrence: Invalid BYWEEKNO value")                    

            elif index == definitions.eRecurrence_BYMONTH:
                if self.mByMonth is not None:
                    raise ValueError("PyCalendarRecurrence: Only one BYMONTH allowed")
                self.mByMonth = []
                self.parseList(tvalue, self.mByMonth, 1, 12, errmsg="PyCalendarRecurrence: Invalid BYMONTH value")                    

            elif index == definitions.eRecurrence_BYSETPOS:
                if self.mBySetPos is not None:
                    raise ValueError("PyCalendarRecurrence: Only one BYSETPOS allowed")
                self.mBySetPos = []
                self.parseList(tvalue, self.mBySetPos, allowNegative=True, errmsg="PyCalendarRecurrence: Invalid BYSETPOS value")                    

            elif index == definitions.eRecurrence_WKST:
                index = PyCalendarRecurrence.cWeekdayMap.get(tvalue, PyCalendarRecurrence.cUnknownIndex)
                if (index == PyCalendarRecurrence.cUnknownIndex):
                    raise ValueError("PyCalendarRecurrence: Invalid WKST value")
                self.mWeekstart = index        

    def parseList(self, txt, list, min=None, max=None, allowNegative=False, errmsg=""):
        
        if "," in txt:
            tokens = txt.split(",")
        else:
            tokens = (txt,)

        for token in tokens:
            value = int(token)
            if not allowNegative and value < 0:
                raise ValueError(errmsg)
            avalue = abs(value)
            if min is not None and avalue < min:
                raise ValueError(errmsg)
            if max is not None  and avalue > max:
                raise ValueError(errmsg)
            list.append(value)

    def parseListDW(self, txt, list, errmsg=""):

        if "," in txt:
            tokens = txt.split(",")
        else:
            tokens = (txt,)

        for token in tokens:
            # Get number if present
            num = 0
            if (len(token) > 0) and token[0] in "+-1234567890":
                offset = 0
                while (offset < len(token)) and token[offset] in "+-1234567890":
                    offset += 1
            
                num = int(token[0:offset])
                token = token[offset:]
                
                anum = abs(num)
                if anum < 1:
                    raise ValueError(errmsg)
                if anum > 53:
                    raise ValueError(errmsg)

            # Get day
            index = PyCalendarRecurrence.cWeekdayMap.get(token, PyCalendarRecurrence.cUnknownIndex)
            if (index == PyCalendarRecurrence.cUnknownIndex):
                raise ValueError(errmsg)
            wday = index

            list.append((num, wday))
    
    def generate(self, os):
        try:
            os.write(definitions.cICalValue_RECUR_FREQ)
            os.write("=")

            if self.mFreq ==  definitions.eRecurrence_SECONDLY:
                os.write(definitions.cICalValue_RECUR_SECONDLY)

            elif self.mFreq ==  definitions.eRecurrence_MINUTELY:
                os.write(definitions.cICalValue_RECUR_MINUTELY)

            elif self.mFreq ==  definitions.eRecurrence_HOURLY:
                os.write(definitions.cICalValue_RECUR_HOURLY)

            elif self.mFreq ==  definitions.eRecurrence_DAILY:
                os.write(definitions.cICalValue_RECUR_DAILY)

            elif self.mFreq ==  definitions.eRecurrence_WEEKLY:
                os.write(definitions.cICalValue_RECUR_WEEKLY)

            elif self.mFreq ==  definitions.eRecurrence_MONTHLY:
                os.write(definitions.cICalValue_RECUR_MONTHLY)

            elif self.mFreq ==  definitions.eRecurrence_YEARLY:
                os.write(definitions.cICalValue_RECUR_YEARLY)

            if self.mUseCount:
                os.write(";")
                os.write(definitions.cICalValue_RECUR_COUNT)
                os.write("=")
                os.write(str(self.mCount))
            elif self.mUseUntil:
                os.write(";")
                os.write(definitions.cICalValue_RECUR_UNTIL)
                os.write("=")
                self.mUntil.generate(os)
        

            if self.mInterval > 1:
                os.write(";")
                os.write(definitions.cICalValue_RECUR_INTERVAL)
                os.write("=")
                os.write(str(self.mInterval))
        

            self.generateList(os, definitions.cICalValue_RECUR_BYSECOND, self.mBySeconds)
            self.generateList(os, definitions.cICalValue_RECUR_BYMINUTE, self.mByMinutes)
            self.generateList(os, definitions.cICalValue_RECUR_BYHOUR, self.mByHours)

            if (self.mByDay is not None) and (len(self.mByDay) != 0):
                os.write(";")
                os.write(definitions.cICalValue_RECUR_BYDAY)
                os.write("=")
                comma = False
                for iter in self.mByDay:
                    if comma:
                        os.write(",")
                    comma = True

                    if iter[0] != 0:
                        os.write(str(iter[0]))

                    if iter[1] == definitions.eRecurrence_WEEKDAY_SU:
                        os.write(definitions.cICalValue_RECUR_WEEKDAY_SU)

                    elif iter[1] == definitions.eRecurrence_WEEKDAY_MO:
                        os.write(definitions.cICalValue_RECUR_WEEKDAY_MO)

                    elif iter[1] ==  definitions.eRecurrence_WEEKDAY_TU:
                        os.write(definitions.cICalValue_RECUR_WEEKDAY_TU)

                    elif iter[1] ==  definitions.eRecurrence_WEEKDAY_WE:
                        os.write(definitions.cICalValue_RECUR_WEEKDAY_WE)

                    elif iter[1] ==  definitions.eRecurrence_WEEKDAY_TH:
                        os.write(definitions.cICalValue_RECUR_WEEKDAY_TH)

                    elif iter[1] ==  definitions.eRecurrence_WEEKDAY_FR:
                        os.write(definitions.cICalValue_RECUR_WEEKDAY_FR)

                    elif iter[1] ==  definitions.eRecurrence_WEEKDAY_SA:
                        os.write(definitions.cICalValue_RECUR_WEEKDAY_SA)

            self.generateList(os, definitions.cICalValue_RECUR_BYMONTHDAY, self.mByMonthDay)
            self.generateList(os, definitions.cICalValue_RECUR_BYYEARDAY, self.mByYearDay)
            self.generateList(os, definitions.cICalValue_RECUR_BYWEEKNO, self.mByWeekNo)
            self.generateList(os, definitions.cICalValue_RECUR_BYMONTH, self.mByMonth)
            self.generateList(os, definitions.cICalValue_RECUR_BYSETPOS, self.mBySetPos)

            # MO is the default so we do not need it
            if self.mWeekstart != definitions.eRecurrence_WEEKDAY_MO:
                os.write(";")
                os.write(definitions.cICalValue_RECUR_WKST)
                os.write("=")

                if self.mWeekstart ==  definitions.eRecurrence_WEEKDAY_SU:
                    os.write(definitions.cICalValue_RECUR_WEEKDAY_SU)

                elif self.mWeekstart == definitions.eRecurrence_WEEKDAY_MO:
                    os.write(definitions.cICalValue_RECUR_WEEKDAY_MO)

                elif self.mWeekstart == definitions.eRecurrence_WEEKDAY_TU:
                    os.write(definitions.cICalValue_RECUR_WEEKDAY_TU)

                elif self.mWeekstart == definitions.eRecurrence_WEEKDAY_WE:
                    os.write(definitions.cICalValue_RECUR_WEEKDAY_WE)

                elif self.mWeekstart == definitions.eRecurrence_WEEKDAY_TH:
                    os.write(definitions.cICalValue_RECUR_WEEKDAY_TH)

                elif self.mWeekstart == definitions.eRecurrence_WEEKDAY_FR:
                    os.write(definitions.cICalValue_RECUR_WEEKDAY_FR)

                elif self.mWeekstart == definitions.eRecurrence_WEEKDAY_SA:
                    os.write(definitions.cICalValue_RECUR_WEEKDAY_SA)

        except:
            pass

    def generateList(self, os, title, items):

        if (items is not None) and (len(items) != 0):
            os.write(";")
            os.write(title)
            os.write("=")
            comma = False
            for e in items:
                if comma:
                    os.write(",")
                comma = True
                os.write(str(e))

    def writeXML(self, node, namespace):

        recur = XML.SubElement(node, xmldefs.makeTag(namespace, xmldefs.value_recur))

        freq = XML.SubElement(recur, xmldefs.makeTag(namespace, xmldefs.recur_freq))
        freq.text = self.cFreqToXMLMap[self.mFreq]

        if self.mUseCount:
            count = XML.SubElement(recur, xmldefs.makeTag(namespace, xmldefs.recur_count))
            count.text = str(self.mCount)
        elif self.mUseUntil:
            until = XML.SubElement(recur, xmldefs.makeTag(namespace, xmldefs.recur_until))
            self.mUntil.writeXML(until, namespace)

        if self.mInterval > 1:
            interval = XML.SubElement(recur, xmldefs.makeTag(namespace, xmldefs.recur_interval))
            interval.text = str(self.mInterval)

        self.writeXMLList(recur, namespace, xmldefs.recur_bysecond, self.mBySeconds)
        self.writeXMLList(recur, namespace, xmldefs.recur_byminute, self.mByMinutes)
        self.writeXMLList(recur, namespace, xmldefs.recur_byhour, self.mByHours)
            
        if self.mByDay is not None and len(self.mByDay) != 0:
            for iter in self.mByDay:
                byday = XML.SubElement(recur, xmldefs.makeTag(namespace, xmldefs.recur_byday))
                data = ""
                if iter[0] != 0:
                    data = str(iter[0])
                data += self.cWeekdayRecurMap.get(iter[1], "")
                byday.text = data

        self.writeXMLList(recur, namespace, xmldefs.recur_bymonthday, self.mByMonthDay)
        self.writeXMLList(recur, namespace, xmldefs.recur_byyearday, self.mByYearDay)
        self.writeXMLList(recur, namespace, xmldefs.recur_byweekno, self.mByWeekNo)
        self.writeXMLList(recur, namespace, xmldefs.recur_bymonth, self.mByMonth)
        self.writeXMLList(recur, namespace, xmldefs.recur_bysetpos, self.mBySetPos)

        # MO is the default so we do not need it
        if self.mWeekstart != definitions.eRecurrence_WEEKDAY_MO:
            wkst = XML.SubElement(recur, xmldefs.makeTag(namespace, xmldefs.recur_wkst))
            wkst.text = self.cWeekdayRecurMap.get(self.mWeekstart, definitions.cICalValue_RECUR_WEEKDAY_MO)

    def writeXMLList(self, node, namespace, name, items):
        if items is not None and len(items) != 0:
            for item in items:
                child = XML.SubElement(node, xmldefs.makeTag(namespace, name))
                child.text = str(item)
                
    
    def hasBy(self):
        return (self.mBySeconds is not None) and (len(self.mBySeconds) != 0) \
                or (self.mByMinutes is not None) and (len(self.mByMinutes) != 0) \
                or (self.mByHours is not None) and (len(self.mByHours) != 0) \
                or (self.mByDay is not None) and (len(self.mByDay) != 0) \
                or (self.mByMonthDay is not None) and (len(self.mByMonthDay) != 0) \
                or (self.mByYearDay is not None) and (len(self.mByYearDay) != 0) \
                or (self.mByWeekNo is not None) and (len(self.mByWeekNo) != 0) \
                or (self.mByMonth is not None) and (len(self.mByMonth) != 0) \
                or (self.mBySetPos is not None) and (len(self.mBySetPos) != 0)


    def isSimpleRule(self):
        # One that has no BYxxx rules
        return not self.hasBy()


    def isAdvancedRule(self):
        # One that has BYMONTH,
        # BYMONTHDAY (with no negative value),
        # BYDAY (with multiple unumbered, or numbered with all the same number
        # (1..4, -2, -1)
        # BYSETPOS with +1, or -1 only
        # no others

        # First checks the ones we do not handle at all
        if ((self.mBySeconds is not None) and (len(self.mBySeconds) != 0) \
                or (self.mByMinutes is not None) and (len(self.mByMinutes) != 0) \
                or (self.mByHours is not None) and (len(self.mByHours) != 0) \
                or (self.mByYearDay is not None) and (len(self.mByYearDay) != 0) \
                or (self.mByWeekNo is not None) and (len(self.mByWeekNo) != 0)):
            return False

        # Check BYMONTHDAY numbers (we can handle -7...-1, 1..31)
        if self.mByMonthDay is not None:
            for iter in self.mByMonthDay:
                if (iter < -7) or (iter > 31) or (iter == 0):
                    return False

        # Check BYDAY numbers
        if self.mByDay is not None:
            number = 0
            first = True
            for iter in self.mByDay:

                # Get the first number
                if (first):
                    number = iter[0]
                    first = False

                    # Check number range
                    if (number > 4) or (number < -2):
                        return False
            

                # If current differs from last, then we have an error
                elif number != iter[0]:
                    return False

        # Check BYSETPOS numbers
        if self.mBySetPos is not None:
            if len(self.mBySetPos) > 1:
                return False
            if (len(self.mBySetPos) == 1) and (self.mBySetPos[0] != -1) and (self.mBySetPos[0] != 1):
                return False
    

        # If we get here it must be OK
        return True


    def getUIDescription(self):
        try:
            # For now just use iCal item
            sout = StringIO()
            self.generate(sout)
            result = sout.getvalue()
        except:
            result = ""
    
        return result


    def expand(self, start, range, items, float_offset=0):

        # Must have recurrence list at this point
        if self.mRecurrences is None:
            self.mRecurrences = []

        # Wipe cache if start is different
        if self.mCached and (start != self.mCacheStart):
            self.mCached = False
            self.mFullyCached = False
            self.mRecurrences = []
    
        # Is the current cache complete or does it extend past the requested
        # range end
        if not self.mCached or not self.mFullyCached \
                and (self.mCacheUpto is None or self.mCacheUpto < range.getEnd()):
            cache_range = range.duplicate()

            # If partially cached just cache from previous cache end up to new
            # end
            if self.mCached:
                cache_range = PyCalendarPeriod(self.mCacheUpto, range.getEnd())

            # Simple expansion is one where there is no BYXXX rule part
            if not self.hasBy():
                self.mFullyCached = self.simpleExpand(start, cache_range, self.mRecurrences, float_offset)
            else:
                self.mFullyCached = self.complexExpand(start, cache_range, self.mRecurrences, float_offset)

            # Set cache values
            self.mCached = True
            self.mCacheStart = start
            self.mCacheUpto = range.getEnd()
    
        # Just return the cached items in the requested range
        limited = not self.mFullyCached
        for iter in self.mRecurrences:
            if range.isDateWithinPeriod(iter):
                items.append(iter)
            else:
                limited = True
        return limited
    
    def simpleExpand(self, start, range, items, float_offset):
        start_iter = start.duplicate()
        ctr = 0

        if self.mUseUntil:
            float_until = self.mUntil.duplicate()
            if start.floating():
                float_until.setTimezoneID(0)
                float_until.offsetSeconds(float_offset)

        while True:
            # Exit if after period we want
            if range.isDateAfterPeriod(start_iter):
                return False

            # Add current one to list
            items.append(start_iter.duplicate())

            # Get next item
            start_iter.recur(self.mFreq, self.mInterval)

            # Check limits
            if self.mUseCount:
                # Bump counter and exit if over
                ctr += 1
                if ctr >= self.mCount:
                    return True
            elif self.mUseUntil:
                # Exit if next item is after until (its OK if its the same as
                # UNTIL as UNTIL is inclusive)
                if start_iter > float_until:
                    return True

    def complexExpand(self, start, range, items, float_offset):
        start_iter = start.duplicate()
        ctr = 0

        if self.mUseUntil:
            float_until = self.mUntil.duplicate()
            if start.floating():
                float_until.setTimezoneID(None)
                float_until.offsetSeconds(float_offset)

        # Always add the initial instance DTSTART
        items.append(start.duplicate())
        if self.mUseCount:
            # Bump counter and exit if over
            ctr += 1
            if ctr >= self.mCount:
                return True

        # Need to re-initialise start based on BYxxx rules
        while True:
            # Behaviour is based on frequency
            set_items = []

            if self.mFreq == definitions.eRecurrence_SECONDLY:
                self.generateSecondlySet(start_iter, set_items)

            elif self.mFreq == definitions.eRecurrence_MINUTELY:
                self.generateMinutelySet(start_iter, set_items)

            elif self.mFreq == definitions.eRecurrence_HOURLY:
                self.generateHourlySet(start_iter, set_items)

            elif self.mFreq == definitions.eRecurrence_DAILY:
                self.generateDailySet(start_iter, set_items)

            elif self.mFreq == definitions.eRecurrence_WEEKLY:
                self.generateWeeklySet(start_iter, set_items)

            elif self.mFreq == definitions.eRecurrence_MONTHLY:
                self.generateMonthlySet(start_iter, set_items)

            elif self.mFreq == definitions.eRecurrence_YEARLY:
                self.generateYearlySet(start_iter, set_items)        

            # Always sort the set as BYxxx rules may not be sorted
            #set_items.sort(cmp=PyCalendarDateTime.sort)
            set_items.sort(key=lambda x:x.getPosixTime())

            # Process each one in the generated set
            for iter in set_items:

                # Ignore if it is before the actual start - we need this
                # because the expansion
                # can go back in time from the real start, but we must exclude
                # those when counting
                # even if they are not within the requested range
                if iter < start:
                    continue

                # Exit if after period we want
                if range.isDateAfterPeriod(iter):
                    return False

                # Exit if beyond the UNTIL limit
                if self.mUseUntil:
                    # Exit if next item is after until (its OK if its the same
                    # as UNTIL as UNTIL is inclusive)
                    if iter > float_until:
                        return True

                # Special for start instance
                if (ctr == 1) and (start == iter):
                    continue

                # Add current one to list
                items.append(iter)

                # Check limits
                if self.mUseCount:
                    # Bump counter and exit if over
                    ctr += 1
                    if ctr >= self.mCount:
                        return True

            # Exit if after period we want
            if range.isDateAfterPeriod(start_iter):
                return False

            # Get next item
            start_iter.recur(self.mFreq, self.mInterval)

    def clear(self):
        self.mCached = False
        self.mFullyCached = False
        if self.mRecurrences is not None:
            self.mRecurrences = []


    # IMPORTANT ExcludeFutureRecurrence assumes mCacheStart is setup with the
    # owning VEVENT's DTSTART
    # Currently this method is only called when a recurrence is being removed
    # so
    # the recurrence data should be cached

    # Exclude dates on or after the chosen one
    def excludeFutureRecurrence(self, exclude):
        # Expand the rule upto the exclude date
        items = []
        period = PyCalendarPeriod()
        period.init(self.mCacheStart, exclude)
        self.expand(self.mCacheStart, period, items)

        # Adjust UNTIL or add one if no COUNT
        if self.getUseUntil() or not self.getUseCount():
            # The last one is just less than the exclude date
            if len(items) != 0:
                # Now use the data as the UNTIL
                self.mUseUntil = True
                self.mUntil = items[-1]

        # Adjust COUNT
        elif self.getUseCount():
            # The last one is just less than the exclude date
            self.mUseCount = True
            self.mCount = len(items)
    
        # Now clear out the cached set after making changes
        self.clear()

    def generateYearlySet(self, start, items):
        # All possible BYxxx are valid, though some combinations are not

        # Start with initial date-time
        items.append(start.duplicate())

        if (self.mByMonth is not None) and (len(self.mByMonth) != 0):
            items[:] = self.byMonthExpand(items)
    

        if (self.mByWeekNo is not None) and (len(self.mByWeekNo) != 0):
            items[:] = self.byWeekNoExpand(items)
    

        if (self.mByYearDay is not None) and (len(self.mByYearDay) != 0):
            items[:] = self.byYearDayExpand(items)
    

        if (self.mByMonthDay is not None) and (len(self.mByMonthDay) != 0):
            items[:] = self.byMonthDayExpand(items)
    

        if (self.mByDay is not None) and (len(self.mByDay) != 0):
            # BYDAY is complicated:
            # if BYDAY is included with BYYEARDAY or BYMONTHDAY then it
            # contracts the recurrence set
            # else it expands it, but the expansion depends on the frequency
            # and other BYxxx periodicities

            if ((self.mByYearDay is not None) and (len(self.mByYearDay) != 0)) \
                    or ((self.mByMonthDay is not None) and (len(self.mByMonthDay) != 0)):
                items[:] = self.byDayLimit(items)
            elif (self.mByWeekNo is not None) and (len(self.mByWeekNo) != 0):
                items[:] = self.byDayExpandWeekly(items)
            elif (self.mByMonth is not None) and (len(self.mByMonth) != 0):
                items[:] = self.byDayExpandMonthly(items)
            else:
                items[:] = self.byDayExpandYearly(items)

        if (self.mByHours is not None) and (len(self.mByHours) != 0):
            items[:] = self.byHourExpand(items)
    
        if (self.mByMinutes is not None) and (len(self.mByMinutes) != 0):
            items[:] = self.byMinuteExpand(items)
    
        if (self.mBySeconds is not None) and (len(self.mBySeconds) != 0):
            items[:] = self.bySecondExpand(items)
    
        if (self.mBySetPos is not None) and (len(self.mBySetPos) != 0):
            items[:] = self.bySetPosLimit(items)
    
    def generateMonthlySet(self, start, items):
        # Cannot have BYYEARDAY and BYWEEKNO

        # Start with initial date-time
        items.append(start.duplicate())

        if (self.mByMonth is not None) and (len(self.mByMonth) != 0):
            # BYMONTH limits the range of possible values
            items[:] = self.byMonthLimit(items)
            if (len(items) == 0):
                return
    
        # No BYWEEKNO

        # No BYYEARDAY

        if (self.mByMonthDay is not None) and (len(self.mByMonthDay) != 0):
            items[:] = self.byMonthDayExpand(items)
    
        if (self.mByDay is not None) and (len(self.mByDay) != 0):
            # BYDAY is complicated:
            # if BYDAY is included with BYYEARDAY or BYMONTHDAY then it
            # contracts the recurrence set
            # else it expands it, but the expansion depends on the frequency
            # and other BYxxx periodicities

            if ((self.mByYearDay is not None) and (len(self.mByYearDay) != 0)) \
                    or ((self.mByMonthDay is not None) and (len(self.mByMonthDay) != 0)):
                items[:] = self.byDayLimit(items)
            else:
                items[:] = self.byDayExpandMonthly(items)
    
        if ((self.mByHours is not None) and (len(self.mByHours) != 0)):
            items[:] = self.byHourExpand(items)
    
        if ((self.mByMinutes is not None) and (len(self.mByMinutes) != 0)):
            items[:] = self.byMinuteExpand(items)
    
        if ((self.mBySeconds is not None) and (len(self.mBySeconds) != 0)):
            items[:] = self.bySecondExpand(items)
    
        if ((self.mBySetPos is not None) and (len(self.mBySetPos) != 0)):
            items[:] = self.bySetPosLimit(items)
    
    def generateWeeklySet(self, start,  items):
        # Cannot have BYYEARDAY and BYMONTHDAY

        # Start with initial date-time
        items.append(start.duplicate())

        if (self.mByMonth is not None) and (len(self.mByMonth) != 0):
            # BYMONTH limits the range of possible values
            items[:] = self.byMonthLimit(items)
            if (len(items) == 0):
                return
    
        if (self.mByWeekNo is not None) and (len(self.mByWeekNo) != 0):
            items[:] = self.byWeekNoLimit(items)
            if (len(items) == 0):
                return
    
        # No BYYEARDAY

        # No BYMONTHDAY

        if (self.mByDay is not None) and (len(self.mByDay) != 0):
            items[:] = self.byDayExpandWeekly(items)
    
        if (self.mByHours is not None) and (len(self.mByHours) != 0):
            items[:] = self.byHourExpand(items)
    
        if (self.mByMinutes is not None) and (len(self.mByMinutes) != 0):
            items[:] = self.byMinuteExpand(items)
    
        if (self.mBySeconds is not None) and (len(self.mBySeconds) != 0):
            items[:] = self.bySecondExpand(items)
    
        if (self.mBySetPos is not None) and (len(self.mBySetPos) != 0):
            items[:] = self.bySetPosLimit(items)
    
    def generateDailySet(self, start,  items):
        # Cannot have BYYEARDAY

        # Start with initial date-time
        items.append(start.duplicate())

        if (self.mByMonth is not None) and (len(self.mByMonth) != 0):
            # BYMONTH limits the range of possible values
            items[:] = self.byMonthLimit(items)
            if (len(items) == 0):
                return
    

        if (self.mByWeekNo is not None) and (len(self.mByWeekNo) != 0):
            items[:] = self.byWeekNoLimit(items)
            if (len(items) == 0):
                return
    

        # No BYYEARDAY

        if (self.mByMonthDay is not None) and (len(self.mByMonthDay) != 0):
            items[:] = self.byMonthDayLimit(items)
            if (len(items) == 0):
                return
    

        if (self.mByDay is not None) and (len(self.mByDay) != 0):
            items[:] = self.byDayLimit(items)
            if (len(items) == 0):
                return
    

        if (self.mByHours is not None) and (len(self.mByHours) != 0):
            items[:] = self.byHourExpand(items)
    

        if (self.mByMinutes is not None) and (len(self.mByMinutes) != 0):
            items[:] = self.byMinuteExpand(items)
    

        if (self.mBySeconds is not None) and (len(self.mBySeconds) != 0):
            items[:] = self.bySecondExpand(items)
    

        if (self.mBySetPos is not None) and (len(self.mBySetPos) != 0):
            items[:] = self.bySetPosLimit(items)
    
    def generateHourlySet(self, start, items):
        # Cannot have BYYEARDAY

        # Start with initial date-time
        items.append(start.duplicate())

        if (self.mByMonth is not None) and (len(self.mByMonth) != 0):
            # BYMONTH limits the range of possible values
            items[:] = self.byMonthLimit(items)
            if (len(items) == 0):
                return
    

        if (self.mByWeekNo is not None) and (len(self.mByWeekNo) != 0):
            items[:] = self.byWeekNoLimit(items)
            if (len(items) == 0):
                return
    

        # No BYYEARDAY

        if (self.mByMonthDay is not None) and (len(self.mByMonthDay) != 0):
            items[:] = self.byMonthDayLimit(items)
            if (len(items) == 0):
                return
    

        if (self.mByDay is not None) and (len(self.mByDay) != 0):
            items[:] = self.byDayLimit(items)
            if (len(items) == 0):
                return
    

        if (self.mByHours is not None) and (len(self.mByHours) != 0):
            items[:] = self.byHourLimit(items)
            if (len(items) == 0):
                return
    
        if (self.mByMinutes is not None) and (len(self.mByMinutes) != 0):
            items[:] = self.byMinuteExpand(items)
    

        if (self.mBySeconds is not None) and (len(self.mBySeconds) != 0):
            items[:] = self.bySecondExpand(items)
    

        if (self.mBySetPos is not None) and (len(self.mBySetPos) != 0):
            items[:] = self.bySetPosLimit(items)

    def generateMinutelySet(self, start, items):
        # Cannot have BYYEARDAY

        # Start with initial date-time
        items.append(start.duplicate())

        if (self.mByMonth is not None) and (len(self.mByMonth) != 0):
            # BYMONTH limits the range of possible values
            items[:] = self.byMonthLimit(items)
            if (len(items) == 0):
                return
    
        if (self.mByWeekNo is not None) and (len(self.mByWeekNo) != 0):
            items[:] = self.byWeekNoLimit(items)
            if (len(items) == 0):
                return
    
        # No BYYEARDAY

        if (self.mByMonthDay is not None) and (len(self.mByMonthDay) != 0):
            items[:] = self.byMonthDayLimit(items)
            if (len(items) == 0):
                return
    
        if (self.mByDay is not None) and (len(self.mByDay) != 0):
            items[:] = self.byDayLimit(items)
            if (len(items) == 0):
                return
    
        if (self.mByHours is not None) and (len(self.mByHours) != 0):
            items[:] = self.byHourLimit(items)
            if (len(items) == 0):
                return
    
        if (self.mByMinutes is not None) and (len(self.mByMinutes) != 0):
            items[:] = self.byMinuteLimit(items)
            if (len(items) == 0):
                return
    
        if (self.mBySeconds is not None) and (len(self.mBySeconds) != 0):
            items[:] = self.bySecondExpand(items)
    
        if (self.mBySetPos is not None) and (len(self.mBySetPos) != 0):
            items[:] = self.bySetPosLimit(items)
    
    def generateSecondlySet(self, start,  items):
        # Cannot have BYYEARDAY

        # Start with initial date-time
        items.append(start.duplicate())

        if (self.mByMonth is not None) and (len(self.mByMonth) != 0):
            # BYMONTH limits the range of possible values
            items[:] = self.byMonthLimit(items)
            if (len(items) == 0):
                return
    
        if (self.mByWeekNo is not None) and (len(self.mByWeekNo) != 0):
            items[:] = self.byWeekNoLimit(items)
            if (len(items) == 0):
                return
    
        # No BYYEARDAY

        if (self.mByMonthDay is not None) and (len(self.mByMonthDay) != 0):
            items[:] = self.byMonthDayLimit(items)
            if (len(items) == 0):
                return
    
        if (self.mByDay is not None) and (len(self.mByDay) != 0):
            items[:] = self.byDayLimit(items)
            if (len(items) == 0):
                return
    
        if (self.mByHours is not None) and (len(self.mByHours) != 0):
            items[:] = self.byHourLimit(items)
            if (len(items) == 0):
                return
    
        if (self.mByMinutes is not None) and (len(self.mByMinutes) != 0):
            items[:] = self.byMinuteLimit(items)
            if (len(items) == 0):
                return
    
        if (self.mBySeconds is not None) and (len(self.mBySeconds) != 0):
            items[:] = self.bySecondLimit(items)
            if (len(items) == 0):
                return
    
        if (self.mBySetPos is not None) and (len(self.mBySetPos) != 0):
            items[:] = self.bySetPosLimit(items)

    def byMonthExpand(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYMONTH and generating a new date-time for it and
            # insert into output
            for iter2 in self.mByMonth:
                temp = iter1.duplicate()
                temp.setMonth(iter2)
                output.append(temp)

        return output

    def byWeekNoExpand(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYWEEKNO and generating a new date-time for it and
            # insert into output
            for iter2 in self.mByWeekNo:
                temp = iter1.duplicate()
                temp.setWeekNo(iter2)
                output.append(temp)
                
        return output

    def byYearDayExpand(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYYEARDAY and generating a new date-time for it
            # and insert into output
            for iter2 in self.mByYearDay:
                temp = iter1.duplicate()
                temp.setYearDay(iter2)
                output.append(temp)

        return output

    def byMonthDayExpand(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYMONTHDAY and generating a new date-time for it
            # and insert into output
            for iter2 in self.mByMonthDay:
                temp = iter1.duplicate()
                temp.setMonthDay(iter2)
                output.append(temp)

        return output

    def byDayExpandYearly(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYDAY and generating a new date-time for it and
            # insert into output
            for iter2 in self.mByDay:
                # Numeric value means specific instance
                if iter2[0] != 0:
                    temp = iter1.duplicate()
                    temp.setDayOfWeekInYear(iter2[0], iter2[1])
                    output.append(temp)
                else:
                    # Every matching day in the year
                    for  i in range(1, 54):
                        temp = iter1.duplicate()
                        temp.setDayOfWeekInYear(i, iter2[1])
                        if temp.getYear() == (iter1).getYear():
                            output.append(temp)

        return output

    def byDayExpandMonthly(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYDAY and generating a new date-time for it and
            # insert into output
            for iter2 in self.mByDay:
                # Numeric value means specific instance
                if iter2[0] != 0:
                    temp = iter1.duplicate()
                    temp.setDayOfWeekInMonth(iter2[0], iter2[1])
                    output.append(temp)
                else:
                    # Every matching day in the month
                    for i in range(1, 7):
                        temp = iter1.duplicate()
                        temp.setDayOfWeekInMonth(i, iter2[1])
                        if temp.getMonth() == iter1.getMonth():
                            output.append(temp)

        return output

    def byDayExpandWeekly(self, dates):
        # Must take into account the WKST value

        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYDAY and generating a new date-time for it and
            # insert into output
            for iter2 in self.mByDay:
                # Numeric values are meaningless so ignore them
                if iter2[0] == 0:
                    temp = iter1.duplicate()

                    # Determine amount of offset to apply to temp to shift it
                    # to the start of the week (backwards)
                    week_start_offset = self.mWeekstart - temp.getDayOfWeek()
                    if week_start_offset > 0:
                        week_start_offset -= 7

                    # Determine amount of offset from the start of the week to
                    # the day we want (forwards)
                    day_in_week_offset = iter2[1] - self.mWeekstart
                    if day_in_week_offset < 0:
                        day_in_week_offset += 7

                    # Apply offsets
                    temp.offsetDay(week_start_offset + day_in_week_offset)
                    output.append(temp)

        return output

    def byHourExpand(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYHOUR and generating a new date-time for it and
            # insert into output
            for iter2 in self.mByHours:
                temp = iter1.duplicate()
                temp.setHours(iter2)
                output.append(temp)

        return output

    def byMinuteExpand(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYMINUTE and generating a new date-time for it and
            # insert into output
            for iter2 in self.mByMinutes:
                temp = iter1.duplicate()
                temp.setMinutes(iter2)
                output.append(temp)

        return output

    def bySecondExpand(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYSECOND and generating a new date-time for it and
            # insert into output
            for iter2 in self.mBySeconds:
                temp = iter1.duplicate()
                temp.setSeconds(iter2)
                output.append(temp)

        return output

    def byMonthLimit(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYMONTH and indicate keep if input month matches
            keep = False
            for iter2 in self.mByMonth:
                keep = (iter1.getMonth() == iter2)
                if keep:
                    break
        
            if keep:
                output.append(iter1)

        return output

    def byWeekNoLimit(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYWEEKNO and indicate keep if input month matches
            keep = False
            for iter2 in self.mByWeekNo:
                keep = iter1.isWeekNo(iter2)
                if keep:
                    break
        
            if keep:
                output.append(iter1)
    
        return output

    def byMonthDayLimit(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYMONTHDAY and indicate keep if input month
            # matches
            keep = False
            for iter2 in self.mByMonthDay:
                keep = iter1.isMonthDay(iter2)
                if keep:
                    break
        
            if keep:
                output.append(iter1)
    
        return output

    def byDayLimit(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYDAY and indicate keep if input month matches
            keep = False
            for iter2 in self.mByDay:
                keep = iter1.isDayOfWeekInMonth(iter2[0], iter2[1])
                if keep:
                    break
        
            if keep:
                output.append(iter1)

        return output

    def byHourLimit(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYHOUR and indicate keep if input hour matches
            keep = False
            for iter2 in self.mByHours:
                keep = (iter1.getHours() == iter2)
                if keep:
                    break
        
            if keep:
                output.append(iter1)
    
        return output

    def byMinuteLimit(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYMINUTE and indicate keep if input minute matches
            keep = False
            for iter2 in self.mByMinutes:
                keep = (iter1.getMinutes() == iter2)
                if keep:
                    break
        
            if keep:
                output.append(iter1)

        return output

    def bySecondLimit(self, dates):
        # Loop over all input items
        output = []
        for iter1 in dates:
            # Loop over each BYSECOND and indicate keep if input second matches
            keep = False
            for iter2 in self.mBySeconds:
                keep = (iter1.getSeconds() == iter2)
                if keep:
                    break
        
            if keep:
                output.append(iter1)
    
        return output

    def bySetPosLimit(self, dates):
        # The input dates MUST be sorted in order for this to work properly
        #dates.sort(cmp=PyCalendarDateTime.sort)
        dates.sort(key=lambda x:x.getPosixTime())

        # Loop over each BYSETPOS and extract the relevant component from the
        # input array and add to the output
        output = []
        input_size = len(dates)
        for iter in self.mBySetPos:
            if iter > 0:
                # Positive values are offset from the start
                if iter <= input_size:
                    output.append(dates[iter - 1])
            elif iter < 0:
                # Negative values are offset from the end
                if -iter <= input_size:
                    output.append(dates[input_size + iter])
 
        return output