prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>test_funcs.py<|end_file_name|><|fim▁begin|>import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0], "StdPy") assert findTxt(recPaths["Department"][1], "standard") assert findTxt(repPaths["ListWindowReport"][0], "base") assert findTxt(repPaths["ExpensesList"][0], "StdPy") assert findTxt(repPaths["ExpensesList"][1], "standard") assert findTxt(rouPaths["GenNLT"][0], "StdPy") assert findTxt(rouPaths["GenNLT"][1], "standard") assert findTxt(corePaths["Field"][0], "embedded") self.assertFalse([k for (k, v) in rouPaths.iteritems() if findTxt(v[0], "base")]) #no routines in base def test_recordInheritance(self): recf, recd = getRecordInheritance("Invoice") assert all([f1 in recf for f1 in ("SalesMan", "InvoiceDate", "CustCode", "Currency", "ShiftDate", "OriginNr", "SerNr", "attachFlag")]) assert all([d in recd for d in ("CompoundItemCosts", "Payments", "Items", "Taxes", "Installs")]) recf, recd = getRecordInheritance("AccessGroup") assert all([f2 in recf for f2 in ("PurchaseItemsAccessType", "InitialModule", "Closed", "internalId")]) assert all([d in recd for d in ("PurchaseItems", "Customs", "Modules")]) def test_recordsInfo(self): recf, recd = getRecordsInfo("Department", RECORD) assert recf["Department"]["AutoCashCancel"] == "integer" #From StdPy assert recf["Department"]["DeptName"] == "string" #From standard assert recf["Department"]["Closed"] == "Boolean" #From Master assert recf["Department"]["internalId"] == "internalid" #From Record assert recd["Department"]["OfficePayModes"] == "DepartmentOfficePayModeRow" #Recordname from detail repf, repd = getRecordsInfo("Balance", REPORT) assert repf["Balance"]["LabelType"] == "string" #StdPy assert repf["Balance"]["ExplodeByLabel"] == "boolean" #Standard assert repf["Balance"]["internalId"] == "internalid" #Record assert not repd["Balance"] #Empty dict, no detail rouf, roud = getRecordsInfo("GenNLT", ROUTINE) assert rouf["GenNLT"]["ExcludeInvalid"] == "boolean" assert rouf["GenNLT"]["Table"] == "string" assert not roud["GenNLT"] rouf, roud = getRecordsInfo("LoginDialog", RECORD) assert rouf["LoginDialog"]["Password"] == "string" #embedded assert not roud["LoginDialog"] def test_classInfo(self): attr, meth = getClassInfo("Invoice") assert attr["DEBITNOTE"] == 2 assert attr["ATTACH_NOTE"] == 3 assert attr["rowNr"] == 0 assert attr["ParentInvoice"] == "SuperClass" assert isinstance(attr["DocTypes"], list) assert isinstance(attr["Origin"], dict) assert all([m in meth for m in ("getCardReader", "logTransactionAction", "updateCredLimit", "generateTaxes", "roundValue", "getOriginType", "bring", "getXML", "createField")]) assert meth["fieldIsEditable"][0] == "self" assert meth["fieldIsEditable"][1] == "fieldname" assert meth["fieldIsEditable"][2] == {"rowfieldname":'None'} assert meth["fieldIsEditable"][3] == {"rownr":'None'} attr, meth = getClassInfo("User") assert attr["buffer"] == "RecordBuffer" assert all([m in meth for m in ("store", "save", "load", "hasField")]) def test_suite(): <|fim_middle|> if __name__ == '__main__': unittest.main(defaultTest='test_suite') <|fim▁end|>
suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFuncs)) return suite
<|file_name|>test_funcs.py<|end_file_name|><|fim▁begin|>import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0], "StdPy") assert findTxt(recPaths["Department"][1], "standard") assert findTxt(repPaths["ListWindowReport"][0], "base") assert findTxt(repPaths["ExpensesList"][0], "StdPy") assert findTxt(repPaths["ExpensesList"][1], "standard") assert findTxt(rouPaths["GenNLT"][0], "StdPy") assert findTxt(rouPaths["GenNLT"][1], "standard") assert findTxt(corePaths["Field"][0], "embedded") self.assertFalse([k for (k, v) in rouPaths.iteritems() if findTxt(v[0], "base")]) #no routines in base def test_recordInheritance(self): recf, recd = getRecordInheritance("Invoice") assert all([f1 in recf for f1 in ("SalesMan", "InvoiceDate", "CustCode", "Currency", "ShiftDate", "OriginNr", "SerNr", "attachFlag")]) assert all([d in recd for d in ("CompoundItemCosts", "Payments", "Items", "Taxes", "Installs")]) recf, recd = getRecordInheritance("AccessGroup") assert all([f2 in recf for f2 in ("PurchaseItemsAccessType", "InitialModule", "Closed", "internalId")]) assert all([d in recd for d in ("PurchaseItems", "Customs", "Modules")]) def test_recordsInfo(self): recf, recd = getRecordsInfo("Department", RECORD) assert recf["Department"]["AutoCashCancel"] == "integer" #From StdPy assert recf["Department"]["DeptName"] == "string" #From standard assert recf["Department"]["Closed"] == "Boolean" #From Master assert recf["Department"]["internalId"] == "internalid" #From Record assert recd["Department"]["OfficePayModes"] == "DepartmentOfficePayModeRow" #Recordname from detail repf, repd = getRecordsInfo("Balance", REPORT) assert repf["Balance"]["LabelType"] == "string" #StdPy assert repf["Balance"]["ExplodeByLabel"] == "boolean" #Standard assert repf["Balance"]["internalId"] == "internalid" #Record assert not repd["Balance"] #Empty dict, no detail rouf, roud = getRecordsInfo("GenNLT", ROUTINE) assert rouf["GenNLT"]["ExcludeInvalid"] == "boolean" assert rouf["GenNLT"]["Table"] == "string" assert not roud["GenNLT"] rouf, roud = getRecordsInfo("LoginDialog", RECORD) assert rouf["LoginDialog"]["Password"] == "string" #embedded assert not roud["LoginDialog"] def test_classInfo(self): attr, meth = getClassInfo("Invoice") assert attr["DEBITNOTE"] == 2 assert attr["ATTACH_NOTE"] == 3 assert attr["rowNr"] == 0 assert attr["ParentInvoice"] == "SuperClass" assert isinstance(attr["DocTypes"], list) assert isinstance(attr["Origin"], dict) assert all([m in meth for m in ("getCardReader", "logTransactionAction", "updateCredLimit", "generateTaxes", "roundValue", "getOriginType", "bring", "getXML", "createField")]) assert meth["fieldIsEditable"][0] == "self" assert meth["fieldIsEditable"][1] == "fieldname" assert meth["fieldIsEditable"][2] == {"rowfieldname":'None'} assert meth["fieldIsEditable"][3] == {"rownr":'None'} attr, meth = getClassInfo("User") assert attr["buffer"] == "RecordBuffer" assert all([m in meth for m in ("store", "save", "load", "hasField")]) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFuncs)) return suite if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
unittest.main(defaultTest='test_suite')
<|file_name|>test_funcs.py<|end_file_name|><|fim▁begin|>import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def <|fim_middle|>(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0], "StdPy") assert findTxt(recPaths["Department"][1], "standard") assert findTxt(repPaths["ListWindowReport"][0], "base") assert findTxt(repPaths["ExpensesList"][0], "StdPy") assert findTxt(repPaths["ExpensesList"][1], "standard") assert findTxt(rouPaths["GenNLT"][0], "StdPy") assert findTxt(rouPaths["GenNLT"][1], "standard") assert findTxt(corePaths["Field"][0], "embedded") self.assertFalse([k for (k, v) in rouPaths.iteritems() if findTxt(v[0], "base")]) #no routines in base def test_recordInheritance(self): recf, recd = getRecordInheritance("Invoice") assert all([f1 in recf for f1 in ("SalesMan", "InvoiceDate", "CustCode", "Currency", "ShiftDate", "OriginNr", "SerNr", "attachFlag")]) assert all([d in recd for d in ("CompoundItemCosts", "Payments", "Items", "Taxes", "Installs")]) recf, recd = getRecordInheritance("AccessGroup") assert all([f2 in recf for f2 in ("PurchaseItemsAccessType", "InitialModule", "Closed", "internalId")]) assert all([d in recd for d in ("PurchaseItems", "Customs", "Modules")]) def test_recordsInfo(self): recf, recd = getRecordsInfo("Department", RECORD) assert recf["Department"]["AutoCashCancel"] == "integer" #From StdPy assert recf["Department"]["DeptName"] == "string" #From standard assert recf["Department"]["Closed"] == "Boolean" #From Master assert recf["Department"]["internalId"] == "internalid" #From Record assert recd["Department"]["OfficePayModes"] == "DepartmentOfficePayModeRow" #Recordname from detail repf, repd = getRecordsInfo("Balance", REPORT) assert repf["Balance"]["LabelType"] == "string" #StdPy assert repf["Balance"]["ExplodeByLabel"] == "boolean" #Standard assert repf["Balance"]["internalId"] == "internalid" #Record assert not repd["Balance"] #Empty dict, no detail rouf, roud = getRecordsInfo("GenNLT", ROUTINE) assert rouf["GenNLT"]["ExcludeInvalid"] == "boolean" assert rouf["GenNLT"]["Table"] == "string" assert not roud["GenNLT"] rouf, roud = getRecordsInfo("LoginDialog", RECORD) assert rouf["LoginDialog"]["Password"] == "string" #embedded assert not roud["LoginDialog"] def test_classInfo(self): attr, meth = getClassInfo("Invoice") assert attr["DEBITNOTE"] == 2 assert attr["ATTACH_NOTE"] == 3 assert attr["rowNr"] == 0 assert attr["ParentInvoice"] == "SuperClass" assert isinstance(attr["DocTypes"], list) assert isinstance(attr["Origin"], dict) assert all([m in meth for m in ("getCardReader", "logTransactionAction", "updateCredLimit", "generateTaxes", "roundValue", "getOriginType", "bring", "getXML", "createField")]) assert meth["fieldIsEditable"][0] == "self" assert meth["fieldIsEditable"][1] == "fieldname" assert meth["fieldIsEditable"][2] == {"rowfieldname":'None'} assert meth["fieldIsEditable"][3] == {"rownr":'None'} attr, meth = getClassInfo("User") assert attr["buffer"] == "RecordBuffer" assert all([m in meth for m in ("store", "save", "load", "hasField")]) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFuncs)) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite') <|fim▁end|>
test_buildPaths
<|file_name|>test_funcs.py<|end_file_name|><|fim▁begin|>import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0], "StdPy") assert findTxt(recPaths["Department"][1], "standard") assert findTxt(repPaths["ListWindowReport"][0], "base") assert findTxt(repPaths["ExpensesList"][0], "StdPy") assert findTxt(repPaths["ExpensesList"][1], "standard") assert findTxt(rouPaths["GenNLT"][0], "StdPy") assert findTxt(rouPaths["GenNLT"][1], "standard") assert findTxt(corePaths["Field"][0], "embedded") self.assertFalse([k for (k, v) in rouPaths.iteritems() if findTxt(v[0], "base")]) #no routines in base def <|fim_middle|>(self): recf, recd = getRecordInheritance("Invoice") assert all([f1 in recf for f1 in ("SalesMan", "InvoiceDate", "CustCode", "Currency", "ShiftDate", "OriginNr", "SerNr", "attachFlag")]) assert all([d in recd for d in ("CompoundItemCosts", "Payments", "Items", "Taxes", "Installs")]) recf, recd = getRecordInheritance("AccessGroup") assert all([f2 in recf for f2 in ("PurchaseItemsAccessType", "InitialModule", "Closed", "internalId")]) assert all([d in recd for d in ("PurchaseItems", "Customs", "Modules")]) def test_recordsInfo(self): recf, recd = getRecordsInfo("Department", RECORD) assert recf["Department"]["AutoCashCancel"] == "integer" #From StdPy assert recf["Department"]["DeptName"] == "string" #From standard assert recf["Department"]["Closed"] == "Boolean" #From Master assert recf["Department"]["internalId"] == "internalid" #From Record assert recd["Department"]["OfficePayModes"] == "DepartmentOfficePayModeRow" #Recordname from detail repf, repd = getRecordsInfo("Balance", REPORT) assert repf["Balance"]["LabelType"] == "string" #StdPy assert repf["Balance"]["ExplodeByLabel"] == "boolean" #Standard assert repf["Balance"]["internalId"] == "internalid" #Record assert not repd["Balance"] #Empty dict, no detail rouf, roud = getRecordsInfo("GenNLT", ROUTINE) assert rouf["GenNLT"]["ExcludeInvalid"] == "boolean" assert rouf["GenNLT"]["Table"] == "string" assert not roud["GenNLT"] rouf, roud = getRecordsInfo("LoginDialog", RECORD) assert rouf["LoginDialog"]["Password"] == "string" #embedded assert not roud["LoginDialog"] def test_classInfo(self): attr, meth = getClassInfo("Invoice") assert attr["DEBITNOTE"] == 2 assert attr["ATTACH_NOTE"] == 3 assert attr["rowNr"] == 0 assert attr["ParentInvoice"] == "SuperClass" assert isinstance(attr["DocTypes"], list) assert isinstance(attr["Origin"], dict) assert all([m in meth for m in ("getCardReader", "logTransactionAction", "updateCredLimit", "generateTaxes", "roundValue", "getOriginType", "bring", "getXML", "createField")]) assert meth["fieldIsEditable"][0] == "self" assert meth["fieldIsEditable"][1] == "fieldname" assert meth["fieldIsEditable"][2] == {"rowfieldname":'None'} assert meth["fieldIsEditable"][3] == {"rownr":'None'} attr, meth = getClassInfo("User") assert attr["buffer"] == "RecordBuffer" assert all([m in meth for m in ("store", "save", "load", "hasField")]) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFuncs)) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite') <|fim▁end|>
test_recordInheritance
<|file_name|>test_funcs.py<|end_file_name|><|fim▁begin|>import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0], "StdPy") assert findTxt(recPaths["Department"][1], "standard") assert findTxt(repPaths["ListWindowReport"][0], "base") assert findTxt(repPaths["ExpensesList"][0], "StdPy") assert findTxt(repPaths["ExpensesList"][1], "standard") assert findTxt(rouPaths["GenNLT"][0], "StdPy") assert findTxt(rouPaths["GenNLT"][1], "standard") assert findTxt(corePaths["Field"][0], "embedded") self.assertFalse([k for (k, v) in rouPaths.iteritems() if findTxt(v[0], "base")]) #no routines in base def test_recordInheritance(self): recf, recd = getRecordInheritance("Invoice") assert all([f1 in recf for f1 in ("SalesMan", "InvoiceDate", "CustCode", "Currency", "ShiftDate", "OriginNr", "SerNr", "attachFlag")]) assert all([d in recd for d in ("CompoundItemCosts", "Payments", "Items", "Taxes", "Installs")]) recf, recd = getRecordInheritance("AccessGroup") assert all([f2 in recf for f2 in ("PurchaseItemsAccessType", "InitialModule", "Closed", "internalId")]) assert all([d in recd for d in ("PurchaseItems", "Customs", "Modules")]) def <|fim_middle|>(self): recf, recd = getRecordsInfo("Department", RECORD) assert recf["Department"]["AutoCashCancel"] == "integer" #From StdPy assert recf["Department"]["DeptName"] == "string" #From standard assert recf["Department"]["Closed"] == "Boolean" #From Master assert recf["Department"]["internalId"] == "internalid" #From Record assert recd["Department"]["OfficePayModes"] == "DepartmentOfficePayModeRow" #Recordname from detail repf, repd = getRecordsInfo("Balance", REPORT) assert repf["Balance"]["LabelType"] == "string" #StdPy assert repf["Balance"]["ExplodeByLabel"] == "boolean" #Standard assert repf["Balance"]["internalId"] == "internalid" #Record assert not repd["Balance"] #Empty dict, no detail rouf, roud = getRecordsInfo("GenNLT", ROUTINE) assert rouf["GenNLT"]["ExcludeInvalid"] == "boolean" assert rouf["GenNLT"]["Table"] == "string" assert not roud["GenNLT"] rouf, roud = getRecordsInfo("LoginDialog", RECORD) assert rouf["LoginDialog"]["Password"] == "string" #embedded assert not roud["LoginDialog"] def test_classInfo(self): attr, meth = getClassInfo("Invoice") assert attr["DEBITNOTE"] == 2 assert attr["ATTACH_NOTE"] == 3 assert attr["rowNr"] == 0 assert attr["ParentInvoice"] == "SuperClass" assert isinstance(attr["DocTypes"], list) assert isinstance(attr["Origin"], dict) assert all([m in meth for m in ("getCardReader", "logTransactionAction", "updateCredLimit", "generateTaxes", "roundValue", "getOriginType", "bring", "getXML", "createField")]) assert meth["fieldIsEditable"][0] == "self" assert meth["fieldIsEditable"][1] == "fieldname" assert meth["fieldIsEditable"][2] == {"rowfieldname":'None'} assert meth["fieldIsEditable"][3] == {"rownr":'None'} attr, meth = getClassInfo("User") assert attr["buffer"] == "RecordBuffer" assert all([m in meth for m in ("store", "save", "load", "hasField")]) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFuncs)) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite') <|fim▁end|>
test_recordsInfo
<|file_name|>test_funcs.py<|end_file_name|><|fim▁begin|>import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0], "StdPy") assert findTxt(recPaths["Department"][1], "standard") assert findTxt(repPaths["ListWindowReport"][0], "base") assert findTxt(repPaths["ExpensesList"][0], "StdPy") assert findTxt(repPaths["ExpensesList"][1], "standard") assert findTxt(rouPaths["GenNLT"][0], "StdPy") assert findTxt(rouPaths["GenNLT"][1], "standard") assert findTxt(corePaths["Field"][0], "embedded") self.assertFalse([k for (k, v) in rouPaths.iteritems() if findTxt(v[0], "base")]) #no routines in base def test_recordInheritance(self): recf, recd = getRecordInheritance("Invoice") assert all([f1 in recf for f1 in ("SalesMan", "InvoiceDate", "CustCode", "Currency", "ShiftDate", "OriginNr", "SerNr", "attachFlag")]) assert all([d in recd for d in ("CompoundItemCosts", "Payments", "Items", "Taxes", "Installs")]) recf, recd = getRecordInheritance("AccessGroup") assert all([f2 in recf for f2 in ("PurchaseItemsAccessType", "InitialModule", "Closed", "internalId")]) assert all([d in recd for d in ("PurchaseItems", "Customs", "Modules")]) def test_recordsInfo(self): recf, recd = getRecordsInfo("Department", RECORD) assert recf["Department"]["AutoCashCancel"] == "integer" #From StdPy assert recf["Department"]["DeptName"] == "string" #From standard assert recf["Department"]["Closed"] == "Boolean" #From Master assert recf["Department"]["internalId"] == "internalid" #From Record assert recd["Department"]["OfficePayModes"] == "DepartmentOfficePayModeRow" #Recordname from detail repf, repd = getRecordsInfo("Balance", REPORT) assert repf["Balance"]["LabelType"] == "string" #StdPy assert repf["Balance"]["ExplodeByLabel"] == "boolean" #Standard assert repf["Balance"]["internalId"] == "internalid" #Record assert not repd["Balance"] #Empty dict, no detail rouf, roud = getRecordsInfo("GenNLT", ROUTINE) assert rouf["GenNLT"]["ExcludeInvalid"] == "boolean" assert rouf["GenNLT"]["Table"] == "string" assert not roud["GenNLT"] rouf, roud = getRecordsInfo("LoginDialog", RECORD) assert rouf["LoginDialog"]["Password"] == "string" #embedded assert not roud["LoginDialog"] def <|fim_middle|>(self): attr, meth = getClassInfo("Invoice") assert attr["DEBITNOTE"] == 2 assert attr["ATTACH_NOTE"] == 3 assert attr["rowNr"] == 0 assert attr["ParentInvoice"] == "SuperClass" assert isinstance(attr["DocTypes"], list) assert isinstance(attr["Origin"], dict) assert all([m in meth for m in ("getCardReader", "logTransactionAction", "updateCredLimit", "generateTaxes", "roundValue", "getOriginType", "bring", "getXML", "createField")]) assert meth["fieldIsEditable"][0] == "self" assert meth["fieldIsEditable"][1] == "fieldname" assert meth["fieldIsEditable"][2] == {"rowfieldname":'None'} assert meth["fieldIsEditable"][3] == {"rownr":'None'} attr, meth = getClassInfo("User") assert attr["buffer"] == "RecordBuffer" assert all([m in meth for m in ("store", "save", "load", "hasField")]) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFuncs)) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite') <|fim▁end|>
test_classInfo
<|file_name|>test_funcs.py<|end_file_name|><|fim▁begin|>import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0], "StdPy") assert findTxt(recPaths["Department"][1], "standard") assert findTxt(repPaths["ListWindowReport"][0], "base") assert findTxt(repPaths["ExpensesList"][0], "StdPy") assert findTxt(repPaths["ExpensesList"][1], "standard") assert findTxt(rouPaths["GenNLT"][0], "StdPy") assert findTxt(rouPaths["GenNLT"][1], "standard") assert findTxt(corePaths["Field"][0], "embedded") self.assertFalse([k for (k, v) in rouPaths.iteritems() if findTxt(v[0], "base")]) #no routines in base def test_recordInheritance(self): recf, recd = getRecordInheritance("Invoice") assert all([f1 in recf for f1 in ("SalesMan", "InvoiceDate", "CustCode", "Currency", "ShiftDate", "OriginNr", "SerNr", "attachFlag")]) assert all([d in recd for d in ("CompoundItemCosts", "Payments", "Items", "Taxes", "Installs")]) recf, recd = getRecordInheritance("AccessGroup") assert all([f2 in recf for f2 in ("PurchaseItemsAccessType", "InitialModule", "Closed", "internalId")]) assert all([d in recd for d in ("PurchaseItems", "Customs", "Modules")]) def test_recordsInfo(self): recf, recd = getRecordsInfo("Department", RECORD) assert recf["Department"]["AutoCashCancel"] == "integer" #From StdPy assert recf["Department"]["DeptName"] == "string" #From standard assert recf["Department"]["Closed"] == "Boolean" #From Master assert recf["Department"]["internalId"] == "internalid" #From Record assert recd["Department"]["OfficePayModes"] == "DepartmentOfficePayModeRow" #Recordname from detail repf, repd = getRecordsInfo("Balance", REPORT) assert repf["Balance"]["LabelType"] == "string" #StdPy assert repf["Balance"]["ExplodeByLabel"] == "boolean" #Standard assert repf["Balance"]["internalId"] == "internalid" #Record assert not repd["Balance"] #Empty dict, no detail rouf, roud = getRecordsInfo("GenNLT", ROUTINE) assert rouf["GenNLT"]["ExcludeInvalid"] == "boolean" assert rouf["GenNLT"]["Table"] == "string" assert not roud["GenNLT"] rouf, roud = getRecordsInfo("LoginDialog", RECORD) assert rouf["LoginDialog"]["Password"] == "string" #embedded assert not roud["LoginDialog"] def test_classInfo(self): attr, meth = getClassInfo("Invoice") assert attr["DEBITNOTE"] == 2 assert attr["ATTACH_NOTE"] == 3 assert attr["rowNr"] == 0 assert attr["ParentInvoice"] == "SuperClass" assert isinstance(attr["DocTypes"], list) assert isinstance(attr["Origin"], dict) assert all([m in meth for m in ("getCardReader", "logTransactionAction", "updateCredLimit", "generateTaxes", "roundValue", "getOriginType", "bring", "getXML", "createField")]) assert meth["fieldIsEditable"][0] == "self" assert meth["fieldIsEditable"][1] == "fieldname" assert meth["fieldIsEditable"][2] == {"rowfieldname":'None'} assert meth["fieldIsEditable"][3] == {"rownr":'None'} attr, meth = getClassInfo("User") assert attr["buffer"] == "RecordBuffer" assert all([m in meth for m in ("store", "save", "load", "hasField")]) def <|fim_middle|>(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFuncs)) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite') <|fim▁end|>
test_suite
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs<|fim▁hole|> kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs)<|fim▁end|>
elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port:
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): <|fim_middle|> def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
"""Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): <|fim_middle|> <|fim▁end|>
driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: <|fim_middle|> if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: <|fim_middle|> username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
username, password = username.split(':') password = unquote(password)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: <|fim_middle|> database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
host, port = host.split(':') port = int(port)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': <|fim_middle|> elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
return SQLiteDriver, [dsn.path], {}
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': <|fim_middle|> elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: <|fim_middle|> if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
kwargs['port'] = port
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: <|fim_middle|> if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
kwargs['host'] = host
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: <|fim_middle|> return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
kwargs['passwd'] = password
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': <|fim_middle|> else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: <|fim_middle|> if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
kwargs['port'] = port
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: <|fim_middle|> elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
kwargs['host'] = kwargs.pop('unix_socket')
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: <|fim_middle|> if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
kwargs['host'] = host
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: <|fim_middle|> return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
kwargs['password'] = password
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: <|fim_middle|> def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
raise ValueError('Unknown driver %s' % dsn_string)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def <|fim_middle|>(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def get_driver(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
parse_dsn
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" Gauged https://github.com/chriso/gauged (MIT Licensed) Copyright 2014 (c) Chris O'Hara <[email protected]> """ from urlparse import urlparse, parse_qsl from urllib import unquote from .mysql import MySQLDriver from .sqlite import SQLiteDriver from .postgresql import PostgreSQLDriver def parse_dsn(dsn_string): """Parse a connection string and return the associated driver""" dsn = urlparse(dsn_string) scheme = dsn.scheme.split('+')[0] username = password = host = port = None host = dsn.netloc if '@' in host: username, host = host.split('@') if ':' in username: username, password = username.split(':') password = unquote(password) username = unquote(username) if ':' in host: host, port = host.split(':') port = int(port) database = dsn.path.split('?')[0][1:] query = dsn.path.split('?')[1] if '?' in dsn.path else dsn.query kwargs = dict(parse_qsl(query, True)) if scheme == 'sqlite': return SQLiteDriver, [dsn.path], {} elif scheme == 'mysql': kwargs['user'] = username or 'root' kwargs['db'] = database if port: kwargs['port'] = port if host: kwargs['host'] = host if password: kwargs['passwd'] = password return MySQLDriver, [], kwargs elif scheme == 'postgresql': kwargs['user'] = username or 'postgres' kwargs['database'] = database if port: kwargs['port'] = port if 'unix_socket' in kwargs: kwargs['host'] = kwargs.pop('unix_socket') elif host: kwargs['host'] = host if password: kwargs['password'] = password return PostgreSQLDriver, [], kwargs else: raise ValueError('Unknown driver %s' % dsn_string) def <|fim_middle|>(dsn_string): driver, args, kwargs = parse_dsn(dsn_string) return driver(*args, **kwargs) <|fim▁end|>
get_driver
<|file_name|>01-run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (C) 2017 Francisco Acosta <[email protected]> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import os import sys sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner')) import testrunner from datetime import datetime class InvalidTimeout(Exception): pass def testfunc(child): exp_diff1 = 1000000 exp_diff5 = 5000000 exp_diff10 = 10000000<|fim▁hole|> child.expect(u"\r\n") child.expect(u"<======== If using pyterm, this is the time when started.") child.expect(u"\r\n") m = 9 while (m): n = 3 while (n): if n == 3: exp_diff = exp_diff1 if n == 2: exp_diff = exp_diff5 elif n == 1: exp_diff = exp_diff10 start = datetime.now() child.expect(u"Slept for \\d+ sec...", timeout=11) stop = datetime.now() diff = (stop - start) diff = (diff.seconds * 1000000) + diff.microseconds # fail within 5% of expected if diff > (exp_diff + (exp_diff1 * 0.05)) or \ diff < (exp_diff - (exp_diff1 * 0.05)): raise InvalidTimeout("Invalid timeout %d (expected %d)" % (diff, exp_diff)); else: print("Timed out correctly: %d (expected %d)" % (diff, exp_diff)) n = n - 1 m = m -1 child.expect(u"Test end.", timeout=15) if __name__ == "__main__": sys.exit(testrunner.run(testfunc))<|fim▁end|>
child.expect(u"This test will print \"Slept for X sec...\" every 1, 5 and 10 seconds.\r\n")
<|file_name|>01-run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (C) 2017 Francisco Acosta <[email protected]> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import os import sys sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner')) import testrunner from datetime import datetime class InvalidTimeout(Exception): <|fim_middle|> def testfunc(child): exp_diff1 = 1000000 exp_diff5 = 5000000 exp_diff10 = 10000000 child.expect(u"This test will print \"Slept for X sec...\" every 1, 5 and 10 seconds.\r\n") child.expect(u"\r\n") child.expect(u"<======== If using pyterm, this is the time when started.") child.expect(u"\r\n") m = 9 while (m): n = 3 while (n): if n == 3: exp_diff = exp_diff1 if n == 2: exp_diff = exp_diff5 elif n == 1: exp_diff = exp_diff10 start = datetime.now() child.expect(u"Slept for \\d+ sec...", timeout=11) stop = datetime.now() diff = (stop - start) diff = (diff.seconds * 1000000) + diff.microseconds # fail within 5% of expected if diff > (exp_diff + (exp_diff1 * 0.05)) or \ diff < (exp_diff - (exp_diff1 * 0.05)): raise InvalidTimeout("Invalid timeout %d (expected %d)" % (diff, exp_diff)); else: print("Timed out correctly: %d (expected %d)" % (diff, exp_diff)) n = n - 1 m = m -1 child.expect(u"Test end.", timeout=15) if __name__ == "__main__": sys.exit(testrunner.run(testfunc)) <|fim▁end|>
pass
<|file_name|>01-run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (C) 2017 Francisco Acosta <[email protected]> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import os import sys sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner')) import testrunner from datetime import datetime class InvalidTimeout(Exception): pass def testfunc(child): <|fim_middle|> if __name__ == "__main__": sys.exit(testrunner.run(testfunc)) <|fim▁end|>
exp_diff1 = 1000000 exp_diff5 = 5000000 exp_diff10 = 10000000 child.expect(u"This test will print \"Slept for X sec...\" every 1, 5 and 10 seconds.\r\n") child.expect(u"\r\n") child.expect(u"<======== If using pyterm, this is the time when started.") child.expect(u"\r\n") m = 9 while (m): n = 3 while (n): if n == 3: exp_diff = exp_diff1 if n == 2: exp_diff = exp_diff5 elif n == 1: exp_diff = exp_diff10 start = datetime.now() child.expect(u"Slept for \\d+ sec...", timeout=11) stop = datetime.now() diff = (stop - start) diff = (diff.seconds * 1000000) + diff.microseconds # fail within 5% of expected if diff > (exp_diff + (exp_diff1 * 0.05)) or \ diff < (exp_diff - (exp_diff1 * 0.05)): raise InvalidTimeout("Invalid timeout %d (expected %d)" % (diff, exp_diff)); else: print("Timed out correctly: %d (expected %d)" % (diff, exp_diff)) n = n - 1 m = m -1 child.expect(u"Test end.", timeout=15)
<|file_name|>01-run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (C) 2017 Francisco Acosta <[email protected]> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import os import sys sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner')) import testrunner from datetime import datetime class InvalidTimeout(Exception): pass def testfunc(child): exp_diff1 = 1000000 exp_diff5 = 5000000 exp_diff10 = 10000000 child.expect(u"This test will print \"Slept for X sec...\" every 1, 5 and 10 seconds.\r\n") child.expect(u"\r\n") child.expect(u"<======== If using pyterm, this is the time when started.") child.expect(u"\r\n") m = 9 while (m): n = 3 while (n): if n == 3: <|fim_middle|> if n == 2: exp_diff = exp_diff5 elif n == 1: exp_diff = exp_diff10 start = datetime.now() child.expect(u"Slept for \\d+ sec...", timeout=11) stop = datetime.now() diff = (stop - start) diff = (diff.seconds * 1000000) + diff.microseconds # fail within 5% of expected if diff > (exp_diff + (exp_diff1 * 0.05)) or \ diff < (exp_diff - (exp_diff1 * 0.05)): raise InvalidTimeout("Invalid timeout %d (expected %d)" % (diff, exp_diff)); else: print("Timed out correctly: %d (expected %d)" % (diff, exp_diff)) n = n - 1 m = m -1 child.expect(u"Test end.", timeout=15) if __name__ == "__main__": sys.exit(testrunner.run(testfunc)) <|fim▁end|>
exp_diff = exp_diff1
<|file_name|>01-run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (C) 2017 Francisco Acosta <[email protected]> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import os import sys sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner')) import testrunner from datetime import datetime class InvalidTimeout(Exception): pass def testfunc(child): exp_diff1 = 1000000 exp_diff5 = 5000000 exp_diff10 = 10000000 child.expect(u"This test will print \"Slept for X sec...\" every 1, 5 and 10 seconds.\r\n") child.expect(u"\r\n") child.expect(u"<======== If using pyterm, this is the time when started.") child.expect(u"\r\n") m = 9 while (m): n = 3 while (n): if n == 3: exp_diff = exp_diff1 if n == 2: <|fim_middle|> elif n == 1: exp_diff = exp_diff10 start = datetime.now() child.expect(u"Slept for \\d+ sec...", timeout=11) stop = datetime.now() diff = (stop - start) diff = (diff.seconds * 1000000) + diff.microseconds # fail within 5% of expected if diff > (exp_diff + (exp_diff1 * 0.05)) or \ diff < (exp_diff - (exp_diff1 * 0.05)): raise InvalidTimeout("Invalid timeout %d (expected %d)" % (diff, exp_diff)); else: print("Timed out correctly: %d (expected %d)" % (diff, exp_diff)) n = n - 1 m = m -1 child.expect(u"Test end.", timeout=15) if __name__ == "__main__": sys.exit(testrunner.run(testfunc)) <|fim▁end|>
exp_diff = exp_diff5
<|file_name|>01-run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (C) 2017 Francisco Acosta <[email protected]> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import os import sys sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner')) import testrunner from datetime import datetime class InvalidTimeout(Exception): pass def testfunc(child): exp_diff1 = 1000000 exp_diff5 = 5000000 exp_diff10 = 10000000 child.expect(u"This test will print \"Slept for X sec...\" every 1, 5 and 10 seconds.\r\n") child.expect(u"\r\n") child.expect(u"<======== If using pyterm, this is the time when started.") child.expect(u"\r\n") m = 9 while (m): n = 3 while (n): if n == 3: exp_diff = exp_diff1 if n == 2: exp_diff = exp_diff5 elif n == 1: <|fim_middle|> start = datetime.now() child.expect(u"Slept for \\d+ sec...", timeout=11) stop = datetime.now() diff = (stop - start) diff = (diff.seconds * 1000000) + diff.microseconds # fail within 5% of expected if diff > (exp_diff + (exp_diff1 * 0.05)) or \ diff < (exp_diff - (exp_diff1 * 0.05)): raise InvalidTimeout("Invalid timeout %d (expected %d)" % (diff, exp_diff)); else: print("Timed out correctly: %d (expected %d)" % (diff, exp_diff)) n = n - 1 m = m -1 child.expect(u"Test end.", timeout=15) if __name__ == "__main__": sys.exit(testrunner.run(testfunc)) <|fim▁end|>
exp_diff = exp_diff10
<|file_name|>01-run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (C) 2017 Francisco Acosta <[email protected]> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import os import sys sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner')) import testrunner from datetime import datetime class InvalidTimeout(Exception): pass def testfunc(child): exp_diff1 = 1000000 exp_diff5 = 5000000 exp_diff10 = 10000000 child.expect(u"This test will print \"Slept for X sec...\" every 1, 5 and 10 seconds.\r\n") child.expect(u"\r\n") child.expect(u"<======== If using pyterm, this is the time when started.") child.expect(u"\r\n") m = 9 while (m): n = 3 while (n): if n == 3: exp_diff = exp_diff1 if n == 2: exp_diff = exp_diff5 elif n == 1: exp_diff = exp_diff10 start = datetime.now() child.expect(u"Slept for \\d+ sec...", timeout=11) stop = datetime.now() diff = (stop - start) diff = (diff.seconds * 1000000) + diff.microseconds # fail within 5% of expected if diff > (exp_diff + (exp_diff1 * 0.05)) or \ diff < (exp_diff - (exp_diff1 * 0.05)): <|fim_middle|> else: print("Timed out correctly: %d (expected %d)" % (diff, exp_diff)) n = n - 1 m = m -1 child.expect(u"Test end.", timeout=15) if __name__ == "__main__": sys.exit(testrunner.run(testfunc)) <|fim▁end|>
raise InvalidTimeout("Invalid timeout %d (expected %d)" % (diff, exp_diff));
<|file_name|>01-run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (C) 2017 Francisco Acosta <[email protected]> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import os import sys sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner')) import testrunner from datetime import datetime class InvalidTimeout(Exception): pass def testfunc(child): exp_diff1 = 1000000 exp_diff5 = 5000000 exp_diff10 = 10000000 child.expect(u"This test will print \"Slept for X sec...\" every 1, 5 and 10 seconds.\r\n") child.expect(u"\r\n") child.expect(u"<======== If using pyterm, this is the time when started.") child.expect(u"\r\n") m = 9 while (m): n = 3 while (n): if n == 3: exp_diff = exp_diff1 if n == 2: exp_diff = exp_diff5 elif n == 1: exp_diff = exp_diff10 start = datetime.now() child.expect(u"Slept for \\d+ sec...", timeout=11) stop = datetime.now() diff = (stop - start) diff = (diff.seconds * 1000000) + diff.microseconds # fail within 5% of expected if diff > (exp_diff + (exp_diff1 * 0.05)) or \ diff < (exp_diff - (exp_diff1 * 0.05)): raise InvalidTimeout("Invalid timeout %d (expected %d)" % (diff, exp_diff)); else: <|fim_middle|> n = n - 1 m = m -1 child.expect(u"Test end.", timeout=15) if __name__ == "__main__": sys.exit(testrunner.run(testfunc)) <|fim▁end|>
print("Timed out correctly: %d (expected %d)" % (diff, exp_diff))
<|file_name|>01-run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (C) 2017 Francisco Acosta <[email protected]> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import os import sys sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner')) import testrunner from datetime import datetime class InvalidTimeout(Exception): pass def testfunc(child): exp_diff1 = 1000000 exp_diff5 = 5000000 exp_diff10 = 10000000 child.expect(u"This test will print \"Slept for X sec...\" every 1, 5 and 10 seconds.\r\n") child.expect(u"\r\n") child.expect(u"<======== If using pyterm, this is the time when started.") child.expect(u"\r\n") m = 9 while (m): n = 3 while (n): if n == 3: exp_diff = exp_diff1 if n == 2: exp_diff = exp_diff5 elif n == 1: exp_diff = exp_diff10 start = datetime.now() child.expect(u"Slept for \\d+ sec...", timeout=11) stop = datetime.now() diff = (stop - start) diff = (diff.seconds * 1000000) + diff.microseconds # fail within 5% of expected if diff > (exp_diff + (exp_diff1 * 0.05)) or \ diff < (exp_diff - (exp_diff1 * 0.05)): raise InvalidTimeout("Invalid timeout %d (expected %d)" % (diff, exp_diff)); else: print("Timed out correctly: %d (expected %d)" % (diff, exp_diff)) n = n - 1 m = m -1 child.expect(u"Test end.", timeout=15) if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
sys.exit(testrunner.run(testfunc))
<|file_name|>01-run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright (C) 2017 Francisco Acosta <[email protected]> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import os import sys sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner')) import testrunner from datetime import datetime class InvalidTimeout(Exception): pass def <|fim_middle|>(child): exp_diff1 = 1000000 exp_diff5 = 5000000 exp_diff10 = 10000000 child.expect(u"This test will print \"Slept for X sec...\" every 1, 5 and 10 seconds.\r\n") child.expect(u"\r\n") child.expect(u"<======== If using pyterm, this is the time when started.") child.expect(u"\r\n") m = 9 while (m): n = 3 while (n): if n == 3: exp_diff = exp_diff1 if n == 2: exp_diff = exp_diff5 elif n == 1: exp_diff = exp_diff10 start = datetime.now() child.expect(u"Slept for \\d+ sec...", timeout=11) stop = datetime.now() diff = (stop - start) diff = (diff.seconds * 1000000) + diff.microseconds # fail within 5% of expected if diff > (exp_diff + (exp_diff1 * 0.05)) or \ diff < (exp_diff - (exp_diff1 * 0.05)): raise InvalidTimeout("Invalid timeout %d (expected %d)" % (diff, exp_diff)); else: print("Timed out correctly: %d (expected %d)" % (diff, exp_diff)) n = n - 1 m = m -1 child.expect(u"Test end.", timeout=15) if __name__ == "__main__": sys.exit(testrunner.run(testfunc)) <|fim▁end|>
testfunc
<|file_name|>build_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import argparse<|fim▁hole|>from os import path as os_path import demo_project as demo import traceback def set_host_url_arg(): parser.add_argument('--host', required=True, help='the url for the Materials Commons server') def set_datapath_arg(): parser.add_argument('--datapath', required=True, help='the path to the directory containing the files used by the build') def set_apikey_arg(): parser.add_argument('--apikey', required=True, help='rapikey for the user building the demo project') parser = argparse.ArgumentParser(description='Build Demo Project.') set_host_url_arg() set_datapath_arg() set_apikey_arg() args = parser.parse_args() host = args.host path = os_path.abspath(args.datapath) key = args.apikey # log_messages # print "Running script to build demo project: " # print " host = " + host + ", " # print " key = " + key + ", " # print " path = " + path try: builder = demo.DemoProject(host, path, key) # a basic get request that makes no changes; will fail if there is a problem with the host or key flag = builder.does_project_exist() project = builder.build_project() if flag: print "Refreshed project with name = " + project.name else: print "Built project with name = " + project.name except Exception as err: traceback.print_exc() print 'Error: ', err<|fim▁end|>
<|file_name|>build_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import argparse from os import path as os_path import demo_project as demo import traceback def set_host_url_arg(): <|fim_middle|> def set_datapath_arg(): parser.add_argument('--datapath', required=True, help='the path to the directory containing the files used by the build') def set_apikey_arg(): parser.add_argument('--apikey', required=True, help='rapikey for the user building the demo project') parser = argparse.ArgumentParser(description='Build Demo Project.') set_host_url_arg() set_datapath_arg() set_apikey_arg() args = parser.parse_args() host = args.host path = os_path.abspath(args.datapath) key = args.apikey # log_messages # print "Running script to build demo project: " # print " host = " + host + ", " # print " key = " + key + ", " # print " path = " + path try: builder = demo.DemoProject(host, path, key) # a basic get request that makes no changes; will fail if there is a problem with the host or key flag = builder.does_project_exist() project = builder.build_project() if flag: print "Refreshed project with name = " + project.name else: print "Built project with name = " + project.name except Exception as err: traceback.print_exc() print 'Error: ', err <|fim▁end|>
parser.add_argument('--host', required=True, help='the url for the Materials Commons server')
<|file_name|>build_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import argparse from os import path as os_path import demo_project as demo import traceback def set_host_url_arg(): parser.add_argument('--host', required=True, help='the url for the Materials Commons server') def set_datapath_arg(): <|fim_middle|> def set_apikey_arg(): parser.add_argument('--apikey', required=True, help='rapikey for the user building the demo project') parser = argparse.ArgumentParser(description='Build Demo Project.') set_host_url_arg() set_datapath_arg() set_apikey_arg() args = parser.parse_args() host = args.host path = os_path.abspath(args.datapath) key = args.apikey # log_messages # print "Running script to build demo project: " # print " host = " + host + ", " # print " key = " + key + ", " # print " path = " + path try: builder = demo.DemoProject(host, path, key) # a basic get request that makes no changes; will fail if there is a problem with the host or key flag = builder.does_project_exist() project = builder.build_project() if flag: print "Refreshed project with name = " + project.name else: print "Built project with name = " + project.name except Exception as err: traceback.print_exc() print 'Error: ', err <|fim▁end|>
parser.add_argument('--datapath', required=True, help='the path to the directory containing the files used by the build')
<|file_name|>build_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import argparse from os import path as os_path import demo_project as demo import traceback def set_host_url_arg(): parser.add_argument('--host', required=True, help='the url for the Materials Commons server') def set_datapath_arg(): parser.add_argument('--datapath', required=True, help='the path to the directory containing the files used by the build') def set_apikey_arg(): <|fim_middle|> parser = argparse.ArgumentParser(description='Build Demo Project.') set_host_url_arg() set_datapath_arg() set_apikey_arg() args = parser.parse_args() host = args.host path = os_path.abspath(args.datapath) key = args.apikey # log_messages # print "Running script to build demo project: " # print " host = " + host + ", " # print " key = " + key + ", " # print " path = " + path try: builder = demo.DemoProject(host, path, key) # a basic get request that makes no changes; will fail if there is a problem with the host or key flag = builder.does_project_exist() project = builder.build_project() if flag: print "Refreshed project with name = " + project.name else: print "Built project with name = " + project.name except Exception as err: traceback.print_exc() print 'Error: ', err <|fim▁end|>
parser.add_argument('--apikey', required=True, help='rapikey for the user building the demo project')
<|file_name|>build_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import argparse from os import path as os_path import demo_project as demo import traceback def set_host_url_arg(): parser.add_argument('--host', required=True, help='the url for the Materials Commons server') def set_datapath_arg(): parser.add_argument('--datapath', required=True, help='the path to the directory containing the files used by the build') def set_apikey_arg(): parser.add_argument('--apikey', required=True, help='rapikey for the user building the demo project') parser = argparse.ArgumentParser(description='Build Demo Project.') set_host_url_arg() set_datapath_arg() set_apikey_arg() args = parser.parse_args() host = args.host path = os_path.abspath(args.datapath) key = args.apikey # log_messages # print "Running script to build demo project: " # print " host = " + host + ", " # print " key = " + key + ", " # print " path = " + path try: builder = demo.DemoProject(host, path, key) # a basic get request that makes no changes; will fail if there is a problem with the host or key flag = builder.does_project_exist() project = builder.build_project() if flag: <|fim_middle|> else: print "Built project with name = " + project.name except Exception as err: traceback.print_exc() print 'Error: ', err <|fim▁end|>
print "Refreshed project with name = " + project.name
<|file_name|>build_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import argparse from os import path as os_path import demo_project as demo import traceback def set_host_url_arg(): parser.add_argument('--host', required=True, help='the url for the Materials Commons server') def set_datapath_arg(): parser.add_argument('--datapath', required=True, help='the path to the directory containing the files used by the build') def set_apikey_arg(): parser.add_argument('--apikey', required=True, help='rapikey for the user building the demo project') parser = argparse.ArgumentParser(description='Build Demo Project.') set_host_url_arg() set_datapath_arg() set_apikey_arg() args = parser.parse_args() host = args.host path = os_path.abspath(args.datapath) key = args.apikey # log_messages # print "Running script to build demo project: " # print " host = " + host + ", " # print " key = " + key + ", " # print " path = " + path try: builder = demo.DemoProject(host, path, key) # a basic get request that makes no changes; will fail if there is a problem with the host or key flag = builder.does_project_exist() project = builder.build_project() if flag: print "Refreshed project with name = " + project.name else: <|fim_middle|> except Exception as err: traceback.print_exc() print 'Error: ', err <|fim▁end|>
print "Built project with name = " + project.name
<|file_name|>build_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import argparse from os import path as os_path import demo_project as demo import traceback def <|fim_middle|>(): parser.add_argument('--host', required=True, help='the url for the Materials Commons server') def set_datapath_arg(): parser.add_argument('--datapath', required=True, help='the path to the directory containing the files used by the build') def set_apikey_arg(): parser.add_argument('--apikey', required=True, help='rapikey for the user building the demo project') parser = argparse.ArgumentParser(description='Build Demo Project.') set_host_url_arg() set_datapath_arg() set_apikey_arg() args = parser.parse_args() host = args.host path = os_path.abspath(args.datapath) key = args.apikey # log_messages # print "Running script to build demo project: " # print " host = " + host + ", " # print " key = " + key + ", " # print " path = " + path try: builder = demo.DemoProject(host, path, key) # a basic get request that makes no changes; will fail if there is a problem with the host or key flag = builder.does_project_exist() project = builder.build_project() if flag: print "Refreshed project with name = " + project.name else: print "Built project with name = " + project.name except Exception as err: traceback.print_exc() print 'Error: ', err <|fim▁end|>
set_host_url_arg
<|file_name|>build_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import argparse from os import path as os_path import demo_project as demo import traceback def set_host_url_arg(): parser.add_argument('--host', required=True, help='the url for the Materials Commons server') def <|fim_middle|>(): parser.add_argument('--datapath', required=True, help='the path to the directory containing the files used by the build') def set_apikey_arg(): parser.add_argument('--apikey', required=True, help='rapikey for the user building the demo project') parser = argparse.ArgumentParser(description='Build Demo Project.') set_host_url_arg() set_datapath_arg() set_apikey_arg() args = parser.parse_args() host = args.host path = os_path.abspath(args.datapath) key = args.apikey # log_messages # print "Running script to build demo project: " # print " host = " + host + ", " # print " key = " + key + ", " # print " path = " + path try: builder = demo.DemoProject(host, path, key) # a basic get request that makes no changes; will fail if there is a problem with the host or key flag = builder.does_project_exist() project = builder.build_project() if flag: print "Refreshed project with name = " + project.name else: print "Built project with name = " + project.name except Exception as err: traceback.print_exc() print 'Error: ', err <|fim▁end|>
set_datapath_arg
<|file_name|>build_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python import argparse from os import path as os_path import demo_project as demo import traceback def set_host_url_arg(): parser.add_argument('--host', required=True, help='the url for the Materials Commons server') def set_datapath_arg(): parser.add_argument('--datapath', required=True, help='the path to the directory containing the files used by the build') def <|fim_middle|>(): parser.add_argument('--apikey', required=True, help='rapikey for the user building the demo project') parser = argparse.ArgumentParser(description='Build Demo Project.') set_host_url_arg() set_datapath_arg() set_apikey_arg() args = parser.parse_args() host = args.host path = os_path.abspath(args.datapath) key = args.apikey # log_messages # print "Running script to build demo project: " # print " host = " + host + ", " # print " key = " + key + ", " # print " path = " + path try: builder = demo.DemoProject(host, path, key) # a basic get request that makes no changes; will fail if there is a problem with the host or key flag = builder.does_project_exist() project = builder.build_project() if flag: print "Refreshed project with name = " + project.name else: print "Built project with name = " + project.name except Exception as err: traceback.print_exc() print 'Error: ', err <|fim▁end|>
set_apikey_arg
<|file_name|>workspaceloader.py<|end_file_name|><|fim▁begin|># Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + # This file is part of the mantidqt package # from __future__ import (absolute_import, division, print_function, unicode_literals) from os import path from mantid import logger class WorkspaceLoader(object): @staticmethod def load_workspaces(directory, workspaces_to_load): """ The method that is called to load in workspaces. From the given directory and the workspace names provided. :param directory: String or string castable object; The project directory :param workspaces_to_load: List of Strings; of the workspaces to load """ if workspaces_to_load is None: return<|fim▁hole|> from mantid.simpleapi import Load # noqa for workspace in workspaces_to_load: try: Load(path.join(directory, (workspace + ".nxs")), OutputWorkspace=workspace) except Exception: logger.warning("Couldn't load file in project: " + workspace + ".nxs")<|fim▁end|>
<|file_name|>workspaceloader.py<|end_file_name|><|fim▁begin|># Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + # This file is part of the mantidqt package # from __future__ import (absolute_import, division, print_function, unicode_literals) from os import path from mantid import logger class WorkspaceLoader(object): <|fim_middle|> <|fim▁end|>
@staticmethod def load_workspaces(directory, workspaces_to_load): """ The method that is called to load in workspaces. From the given directory and the workspace names provided. :param directory: String or string castable object; The project directory :param workspaces_to_load: List of Strings; of the workspaces to load """ if workspaces_to_load is None: return from mantid.simpleapi import Load # noqa for workspace in workspaces_to_load: try: Load(path.join(directory, (workspace + ".nxs")), OutputWorkspace=workspace) except Exception: logger.warning("Couldn't load file in project: " + workspace + ".nxs")
<|file_name|>workspaceloader.py<|end_file_name|><|fim▁begin|># Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + # This file is part of the mantidqt package # from __future__ import (absolute_import, division, print_function, unicode_literals) from os import path from mantid import logger class WorkspaceLoader(object): @staticmethod def load_workspaces(directory, workspaces_to_load): <|fim_middle|> <|fim▁end|>
""" The method that is called to load in workspaces. From the given directory and the workspace names provided. :param directory: String or string castable object; The project directory :param workspaces_to_load: List of Strings; of the workspaces to load """ if workspaces_to_load is None: return from mantid.simpleapi import Load # noqa for workspace in workspaces_to_load: try: Load(path.join(directory, (workspace + ".nxs")), OutputWorkspace=workspace) except Exception: logger.warning("Couldn't load file in project: " + workspace + ".nxs")
<|file_name|>workspaceloader.py<|end_file_name|><|fim▁begin|># Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + # This file is part of the mantidqt package # from __future__ import (absolute_import, division, print_function, unicode_literals) from os import path from mantid import logger class WorkspaceLoader(object): @staticmethod def load_workspaces(directory, workspaces_to_load): """ The method that is called to load in workspaces. From the given directory and the workspace names provided. :param directory: String or string castable object; The project directory :param workspaces_to_load: List of Strings; of the workspaces to load """ if workspaces_to_load is None: <|fim_middle|> from mantid.simpleapi import Load # noqa for workspace in workspaces_to_load: try: Load(path.join(directory, (workspace + ".nxs")), OutputWorkspace=workspace) except Exception: logger.warning("Couldn't load file in project: " + workspace + ".nxs") <|fim▁end|>
return
<|file_name|>workspaceloader.py<|end_file_name|><|fim▁begin|># Mantid Repository : https://github.com/mantidproject/mantid # # Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, # NScD Oak Ridge National Laboratory, European Spallation Source # & Institut Laue - Langevin # SPDX - License - Identifier: GPL - 3.0 + # This file is part of the mantidqt package # from __future__ import (absolute_import, division, print_function, unicode_literals) from os import path from mantid import logger class WorkspaceLoader(object): @staticmethod def <|fim_middle|>(directory, workspaces_to_load): """ The method that is called to load in workspaces. From the given directory and the workspace names provided. :param directory: String or string castable object; The project directory :param workspaces_to_load: List of Strings; of the workspaces to load """ if workspaces_to_load is None: return from mantid.simpleapi import Load # noqa for workspace in workspaces_to_load: try: Load(path.join(directory, (workspace + ".nxs")), OutputWorkspace=workspace) except Exception: logger.warning("Couldn't load file in project: " + workspace + ".nxs") <|fim▁end|>
load_workspaces
<|file_name|>0008_auto_20151224_1528.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-24 15:28 from __future__ import unicode_literals from django.db import migrations, models <|fim▁hole|> class Migration(migrations.Migration): dependencies = [ ('emailer', '0007_auto_20150509_1922'), ] operations = [ migrations.AlterField( model_name='email', name='recipient', field=models.EmailField(db_index=True, max_length=254), ), ]<|fim▁end|>
<|file_name|>0008_auto_20151224_1528.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-24 15:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): <|fim_middle|> <|fim▁end|>
dependencies = [ ('emailer', '0007_auto_20150509_1922'), ] operations = [ migrations.AlterField( model_name='email', name='recipient', field=models.EmailField(db_index=True, max_length=254), ), ]
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import logging logging.basicConfig() <|fim▁hole|>logger.setLevel(logging.INFO) class Result(Enum): runfinished = 1 runerrored = 2 unrouted = 3 error = 4 # vim: set expandtab sw=4 sts=4 ts=4<|fim▁end|>
from enum import Enum logger = logging.getLogger('loopabull')
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import logging logging.basicConfig() from enum import Enum logger = logging.getLogger('loopabull') logger.setLevel(logging.INFO) class Result(Enum): <|fim_middle|> # vim: set expandtab sw=4 sts=4 ts=4 <|fim▁end|>
runfinished = 1 runerrored = 2 unrouted = 3 error = 4
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n')<|fim▁hole|> input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True<|fim▁end|>
input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read()
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): <|fim_middle|> def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.")
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): <|fim_middle|> def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): <|fim_middle|> def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): <|fim_middle|> <|fim▁end|>
global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': <|fim_middle|> elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
return True
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': <|fim_middle|> elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
sys.exit()
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': <|fim_middle|> elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
restart_apache()
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': <|fim_middle|> elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
add_website()
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': <|fim_middle|> else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
add_ssl()
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: <|fim_middle|> def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
print("Invalid input.")
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: <|fim_middle|> current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n')
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': <|fim_middle|> else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.'
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: <|fim_middle|> # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
print("Generating cert for %s" % (site_name,)) wildcard = ''
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def <|fim_middle|>(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
main
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def <|fim_middle|>(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
restart_apache
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def <|fim_middle|>(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def add_ssl(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
add_website
<|file_name|>configure_websites.py<|end_file_name|><|fim▁begin|>import os import re import sys """ * Perform initial configuration to ensure that the server is set up to work with Burton's format sudo chown -R ubuntu:ubuntu /var/www mkdir -p /var/www/default/public_html mv /var/www/html/index.html /var/www/default/public_html # Ubuntu >=14.04 mv /var/www/index.html /var/www/default/public_html # Ubuntu <14.04 rm -rf /var/www/html sudo vim /etc/apache2/sites-available/000-default.conf # Ubuntu >=14.04 sudo vim /etc/apache2/sites-available/default # Ubuntu <14.04 sudo a2enmod ssl sudo service apache2 restart * Enable / disable .htaccess for a site * PHP configuration """ environment = '' def main(env): global environment environment = env while True: print("\nConfigure Websites\n") print("Please select an operation:") print(" 1. Restart Apache") print(" 2. Add a new website") print(" 3. Add SSL to website") print(" 0. Go Back") print(" -. Exit") operation = input(environment.prompt) if operation == '0': return True elif operation == '-': sys.exit() elif operation == '1': restart_apache() elif operation == '2': add_website() elif operation == '3': add_ssl() else: print("Invalid input.") def restart_apache(): print("\nAttempting to restart Apache:") # TODO: Print an error when the user does not have permissions to perform the action. result = os.system("sudo service apache2 restart") print(result) return True def add_website(): global environment print('\nAdd website.\n') input_file = open('./example-files/apache-site', 'r') input_file_text = input_file.read() input_file.close() site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) # TODO: Check that site_name is legal for both a domain name and a filename. while os.path.isfile(new_filename): print('Site exists! Please choose another.') site_name = input('Website name (without www or http)' + environment.prompt) new_filename = '/etc/apache2/sites-available/%s.conf' % (site_name,) tmp_filename = '/tmp/%s.conf' % (site_name,) new_config = re.sub('SITE', site_name, input_file_text) try: output_file = open(tmp_filename, 'w') output_file.write(new_config) output_file.close() tmp_move = os.system("sudo mv %s %s" % (tmp_filename, new_filename)) except PermissionError as e: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') if tmp_move != 0: print('\n\nError!') print('The current user does not have permission to perform this action.') #print('Please run Burton with elevated permissions to resolve this error.\n\n') current_user = str(os.getuid()) result = os.system('sudo mkdir -p /var/www/%s/public_html/' % (site_name,)) result = os.system('sudo mkdir -p /var/www/%s/logs/' % (site_name,)) result = os.system('sudo chown -R %s:%s /var/www/%s/' % (current_user, current_user,)) result = os.system('sudo a2ensite %s.conf' % (site_name,)) restart_apache() return True def <|fim_middle|>(): global environment print("\nAdd SSL to website.\n") print("Please enter the URL of the website.\n") site_name = input(environment.prompt) print("Is this a wildcard certificate? (y/N)\n") wildcard = input(environment.prompt) if wildcard.lower()=='y': print("Generating wildcard cert for *.%s" % (site_name,)) wildcard = '*.' else: print("Generating cert for %s" % (site_name,)) wildcard = '' # http://serverfault.com/questions/649990/non-interactive-creation-of-ssl-certificate-requests #command_template = 'openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout foobar.com.key -out foobar.com.csr -subj "/C=US/ST=New foobar/L=foobar/O=foobar foobar, Inc./CN=foobar.com/[email protected]"' command_template = "openssl req -new -newkey rsa:2048 -nodes -sha256 -keyout %s.key -out %s.csr -subj \"/CN=%s%s\"" print(command_template % (site_name, site_name, wildcard, site_name)) return True <|fim▁end|>
add_ssl
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>.<|fim▁hole|>from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
import lazylibrarian
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: <|fim_middle|> notifier = TwitterNotifier<|fim▁end|>
consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message)
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): <|fim_middle|> def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title)
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): <|fim_middle|> def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title)
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): <|fim_middle|> def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True)
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): <|fim_middle|> def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token']
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): <|fim_middle|> def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): <|fim_middle|> def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): <|fim_middle|> notifier = TwitterNotifier<|fim▁end|>
prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message)
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: <|fim_middle|> def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title)
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: <|fim_middle|> def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title)
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': <|fim_middle|> else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status'])
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: <|fim_middle|> def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token']
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': <|fim_middle|> else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: <|fim_middle|> def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: <|fim_middle|> return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
return False
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def <|fim_middle|>(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
notify_snatch
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def <|fim_middle|>(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
notify_download
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def <|fim_middle|>(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
test_notify
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def <|fim_middle|>(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
_get_authorization
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def <|fim_middle|>(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
_get_credentials
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def <|fim_middle|>(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def _notifyTwitter(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
_send_tweet
<|file_name|>tweet.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/lazylibrarian/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import lazylibrarian from lazylibrarian import logger, common, formatter # parse_qsl moved to urlparse module in v2.6 try: from urlparse import parse_qsl #@UnusedImport except: from cgi import parse_qsl #@Reimport import lib.oauth2 as oauth import lib.pythontwitter as twitter class TwitterNotifier: consumer_key = "208JPTMMnZjtKWA4obcH8g" consumer_secret = "BKaHzaQRd5PK6EH8EqPZ1w8mz6NSk9KErArarinHutk" REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token' ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token' AUTHORIZATION_URL = 'https://api.twitter.com/oauth/authorize' SIGNIN_URL = 'https://api.twitter.com/oauth/authenticate' def notify_snatch(self, title): if lazylibrarian.TWITTER_NOTIFY_ONSNATCH: self._notifyTwitter(common.notifyStrings[common.NOTIFY_SNATCH]+': '+title) def notify_download(self, title): if lazylibrarian.TWITTER_NOTIFY_ONDOWNLOAD: self._notifyTwitter(common.notifyStrings[common.NOTIFY_DOWNLOAD]+': '+title) def test_notify(self): return self._notifyTwitter("This is a test notification from LazyLibrarian / " + formatter.now(), force=True) def _get_authorization(self): signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) oauth_client = oauth.Client(oauth_consumer) logger.info('Requesting temp token from Twitter') resp, content = oauth_client.request(self.REQUEST_TOKEN_URL, 'GET') if resp['status'] != '200': logger.info('Invalid respond from Twitter requesting temp token: %s' % resp['status']) else: request_token = dict(parse_qsl(content)) lazylibrarian.TWITTER_USERNAME = request_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = request_token['oauth_token_secret'] return self.AUTHORIZATION_URL+"?oauth_token="+ request_token['oauth_token'] def _get_credentials(self, key): request_token = {} request_token['oauth_token'] = lazylibrarian.TWITTER_USERNAME request_token['oauth_token_secret'] = lazylibrarian.TWITTER_PASSWORD request_token['oauth_callback_confirmed'] = 'true' token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(key) logger.info('Generating and signing request for an access token using key '+key) signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1() #@UnusedVariable oauth_consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret) logger.info('oauth_consumer: '+str(oauth_consumer)) oauth_client = oauth.Client(oauth_consumer, token) logger.info('oauth_client: '+str(oauth_client)) resp, content = oauth_client.request(self.ACCESS_TOKEN_URL, method='POST', body='oauth_verifier=%s' % key) logger.info('resp, content: '+str(resp)+','+str(content)) access_token = dict(parse_qsl(content)) logger.info('access_token: '+str(access_token)) logger.info('resp[status] = '+str(resp['status'])) if resp['status'] != '200': logger.error('The request for a token with did not succeed: '+str(resp['status'])) return False else: logger.info('Your Twitter Access Token key: %s' % access_token['oauth_token']) logger.info('Access Token secret: %s' % access_token['oauth_token_secret']) lazylibrarian.TWITTER_USERNAME = access_token['oauth_token'] lazylibrarian.TWITTER_PASSWORD = access_token['oauth_token_secret'] return True def _send_tweet(self, message=None): username=self.consumer_key password=self.consumer_secret access_token_key=lazylibrarian.TWITTER_USERNAME access_token_secret=lazylibrarian.TWITTER_PASSWORD logger.info(u"Sending tweet: "+message) api = twitter.Api(username, password, access_token_key, access_token_secret) try: api.PostUpdate(message) except Exception, e: logger.error(u"Error Sending Tweet: %s" %e) return False return True def <|fim_middle|>(self, message='', force=False): prefix = lazylibrarian.TWITTER_PREFIX if not lazylibrarian.USE_TWITTER and not force: return False return self._send_tweet(prefix+": "+message) notifier = TwitterNotifier<|fim▁end|>
_notifyTwitter
<|file_name|>value.py<|end_file_name|><|fim▁begin|>from keras.models import Sequential from keras.layers import convolutional from keras.layers.core import Dense, Flatten from SGD_exponential_decay import SGD_exponential_decay as SGD ### Parameters obtained from paper ### K = 152 # depth of convolutional layers LEARNING_RATE = .003 # initial learning rate DECAY = 8.664339379294006e-08 # rate of exponential learning_rate decay class value_trainer: def __init__(self): self.model = Sequential() self.model.add(convolutional.Convolution2D(input_shape=(49, 19, 19), nb_filter=K, nb_row=5, nb_col=5, init='uniform', activation='relu', border_mode='same')) for i in range(2,13): self.model.add(convolutional.Convolution2D(nb_filter=K, nb_row=3, nb_col=3, init='uniform', activation='relu', border_mode='same')) self.model.add(convolutional.Convolution2D(nb_filter=1, nb_row=1, nb_col=1, init='uniform', activation='linear', border_mode='same'))<|fim▁hole|> self.model.add(Dense(1,init='uniform',activation="tanh")) sgd = SGD(lr=LEARNING_RATE, decay=DECAY) self.model.compile(loss='mean_squared_error', optimizer=sgd) def get_samples(self): # TODO non-terminating loop that draws training samples uniformly at random pass def train(self): # TODO use self.model.fit_generator to train from data source pass if __name__ == '__main__': trainer = value_trainer() # TODO command line instantiation<|fim▁end|>
self.model.add(Flatten()) self.model.add(Dense(256,init='uniform'))
<|file_name|>value.py<|end_file_name|><|fim▁begin|>from keras.models import Sequential from keras.layers import convolutional from keras.layers.core import Dense, Flatten from SGD_exponential_decay import SGD_exponential_decay as SGD ### Parameters obtained from paper ### K = 152 # depth of convolutional layers LEARNING_RATE = .003 # initial learning rate DECAY = 8.664339379294006e-08 # rate of exponential learning_rate decay class value_trainer: <|fim_middle|> if __name__ == '__main__': trainer = value_trainer() # TODO command line instantiation <|fim▁end|>
def __init__(self): self.model = Sequential() self.model.add(convolutional.Convolution2D(input_shape=(49, 19, 19), nb_filter=K, nb_row=5, nb_col=5, init='uniform', activation='relu', border_mode='same')) for i in range(2,13): self.model.add(convolutional.Convolution2D(nb_filter=K, nb_row=3, nb_col=3, init='uniform', activation='relu', border_mode='same')) self.model.add(convolutional.Convolution2D(nb_filter=1, nb_row=1, nb_col=1, init='uniform', activation='linear', border_mode='same')) self.model.add(Flatten()) self.model.add(Dense(256,init='uniform')) self.model.add(Dense(1,init='uniform',activation="tanh")) sgd = SGD(lr=LEARNING_RATE, decay=DECAY) self.model.compile(loss='mean_squared_error', optimizer=sgd) def get_samples(self): # TODO non-terminating loop that draws training samples uniformly at random pass def train(self): # TODO use self.model.fit_generator to train from data source pass
<|file_name|>value.py<|end_file_name|><|fim▁begin|>from keras.models import Sequential from keras.layers import convolutional from keras.layers.core import Dense, Flatten from SGD_exponential_decay import SGD_exponential_decay as SGD ### Parameters obtained from paper ### K = 152 # depth of convolutional layers LEARNING_RATE = .003 # initial learning rate DECAY = 8.664339379294006e-08 # rate of exponential learning_rate decay class value_trainer: def __init__(self): <|fim_middle|> def get_samples(self): # TODO non-terminating loop that draws training samples uniformly at random pass def train(self): # TODO use self.model.fit_generator to train from data source pass if __name__ == '__main__': trainer = value_trainer() # TODO command line instantiation <|fim▁end|>
self.model = Sequential() self.model.add(convolutional.Convolution2D(input_shape=(49, 19, 19), nb_filter=K, nb_row=5, nb_col=5, init='uniform', activation='relu', border_mode='same')) for i in range(2,13): self.model.add(convolutional.Convolution2D(nb_filter=K, nb_row=3, nb_col=3, init='uniform', activation='relu', border_mode='same')) self.model.add(convolutional.Convolution2D(nb_filter=1, nb_row=1, nb_col=1, init='uniform', activation='linear', border_mode='same')) self.model.add(Flatten()) self.model.add(Dense(256,init='uniform')) self.model.add(Dense(1,init='uniform',activation="tanh")) sgd = SGD(lr=LEARNING_RATE, decay=DECAY) self.model.compile(loss='mean_squared_error', optimizer=sgd)
<|file_name|>value.py<|end_file_name|><|fim▁begin|>from keras.models import Sequential from keras.layers import convolutional from keras.layers.core import Dense, Flatten from SGD_exponential_decay import SGD_exponential_decay as SGD ### Parameters obtained from paper ### K = 152 # depth of convolutional layers LEARNING_RATE = .003 # initial learning rate DECAY = 8.664339379294006e-08 # rate of exponential learning_rate decay class value_trainer: def __init__(self): self.model = Sequential() self.model.add(convolutional.Convolution2D(input_shape=(49, 19, 19), nb_filter=K, nb_row=5, nb_col=5, init='uniform', activation='relu', border_mode='same')) for i in range(2,13): self.model.add(convolutional.Convolution2D(nb_filter=K, nb_row=3, nb_col=3, init='uniform', activation='relu', border_mode='same')) self.model.add(convolutional.Convolution2D(nb_filter=1, nb_row=1, nb_col=1, init='uniform', activation='linear', border_mode='same')) self.model.add(Flatten()) self.model.add(Dense(256,init='uniform')) self.model.add(Dense(1,init='uniform',activation="tanh")) sgd = SGD(lr=LEARNING_RATE, decay=DECAY) self.model.compile(loss='mean_squared_error', optimizer=sgd) def get_samples(self): # TODO non-terminating loop that draws training samples uniformly at random <|fim_middle|> def train(self): # TODO use self.model.fit_generator to train from data source pass if __name__ == '__main__': trainer = value_trainer() # TODO command line instantiation <|fim▁end|>
pass
<|file_name|>value.py<|end_file_name|><|fim▁begin|>from keras.models import Sequential from keras.layers import convolutional from keras.layers.core import Dense, Flatten from SGD_exponential_decay import SGD_exponential_decay as SGD ### Parameters obtained from paper ### K = 152 # depth of convolutional layers LEARNING_RATE = .003 # initial learning rate DECAY = 8.664339379294006e-08 # rate of exponential learning_rate decay class value_trainer: def __init__(self): self.model = Sequential() self.model.add(convolutional.Convolution2D(input_shape=(49, 19, 19), nb_filter=K, nb_row=5, nb_col=5, init='uniform', activation='relu', border_mode='same')) for i in range(2,13): self.model.add(convolutional.Convolution2D(nb_filter=K, nb_row=3, nb_col=3, init='uniform', activation='relu', border_mode='same')) self.model.add(convolutional.Convolution2D(nb_filter=1, nb_row=1, nb_col=1, init='uniform', activation='linear', border_mode='same')) self.model.add(Flatten()) self.model.add(Dense(256,init='uniform')) self.model.add(Dense(1,init='uniform',activation="tanh")) sgd = SGD(lr=LEARNING_RATE, decay=DECAY) self.model.compile(loss='mean_squared_error', optimizer=sgd) def get_samples(self): # TODO non-terminating loop that draws training samples uniformly at random pass def train(self): # TODO use self.model.fit_generator to train from data source <|fim_middle|> if __name__ == '__main__': trainer = value_trainer() # TODO command line instantiation <|fim▁end|>
pass