commit
stringlengths
40
40
old_file
stringlengths
4
106
new_file
stringlengths
4
106
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
2.95k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
43k
ndiff
stringlengths
52
3.31k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
diff
stringlengths
49
3.61k
53080f89af51340b0b2c1854e0a4bf38346c14a8
kill.py
kill.py
return 1
from datetime import datetime, timedelta from json import loads import sys if len(sys.argv) < 2: raise Exception("Need an amount of keep-days of which to save your comments.") days = int(sys.argv[1]) before_time = datetime.now() - timedelta(days=days) f = open('data.json', 'r') data = loads(f.read()) f.close() for d in data: date = datetime.fromtimestamp(d['date']) if date < before_time: delete_post(d['id'])
Work out now() - 7 days
Work out now() - 7 days
Python
bsd-2-clause
bparafina/Shreddit,bparafina/Shreddit,ijkilchenko/Shreddit,ijkilchenko/Shreddit
- return 1 + from datetime import datetime, timedelta + from json import loads + import sys + if len(sys.argv) < 2: + raise Exception("Need an amount of keep-days of which to save your comments.") + + days = int(sys.argv[1]) + + before_time = datetime.now() - timedelta(days=days) + + f = open('data.json', 'r') + data = loads(f.read()) + f.close() + + for d in data: + date = datetime.fromtimestamp(d['date']) + if date < before_time: + delete_post(d['id']) +
Work out now() - 7 days
## Code Before: return 1 ## Instruction: Work out now() - 7 days ## Code After: from datetime import datetime, timedelta from json import loads import sys if len(sys.argv) < 2: raise Exception("Need an amount of keep-days of which to save your comments.") days = int(sys.argv[1]) before_time = datetime.now() - timedelta(days=days) f = open('data.json', 'r') data = loads(f.read()) f.close() for d in data: date = datetime.fromtimestamp(d['date']) if date < before_time: delete_post(d['id'])
- return 1 + from datetime import datetime, timedelta + from json import loads + import sys + + if len(sys.argv) < 2: + raise Exception("Need an amount of keep-days of which to save your comments.") + + days = int(sys.argv[1]) + + before_time = datetime.now() - timedelta(days=days) + + f = open('data.json', 'r') + data = loads(f.read()) + f.close() + + for d in data: + date = datetime.fromtimestamp(d['date']) + if date < before_time: + delete_post(d['id'])
86273d96e33e3bd686904377ba2b53fbbbcbc38b
tests/test_crossword.py
tests/test_crossword.py
import unittest from crossword import Crossword class CrosswordTestCase(unittest.TestCase): def test_crossword_set_and_get_element(self): c = Crossword(10, 10) c[3, 3] = 'A' self.assertEqual(c[3, 3], 'A')
import unittest from crossword import Crossword class CrosswordTestCase(unittest.TestCase): def test_crossword_set_and_get_element(self): crossword = Crossword(10, 10) crossword[3, 3] = 'A' self.assertEqual(crossword[3, 3], 'A')
Use a better variable name instead of one character
Use a better variable name instead of one character
Python
mit
svisser/crossword
import unittest from crossword import Crossword class CrosswordTestCase(unittest.TestCase): def test_crossword_set_and_get_element(self): - c = Crossword(10, 10) + crossword = Crossword(10, 10) - c[3, 3] = 'A' + crossword[3, 3] = 'A' - self.assertEqual(c[3, 3], 'A') + self.assertEqual(crossword[3, 3], 'A')
Use a better variable name instead of one character
## Code Before: import unittest from crossword import Crossword class CrosswordTestCase(unittest.TestCase): def test_crossword_set_and_get_element(self): c = Crossword(10, 10) c[3, 3] = 'A' self.assertEqual(c[3, 3], 'A') ## Instruction: Use a better variable name instead of one character ## Code After: import unittest from crossword import Crossword class CrosswordTestCase(unittest.TestCase): def test_crossword_set_and_get_element(self): crossword = Crossword(10, 10) crossword[3, 3] = 'A' self.assertEqual(crossword[3, 3], 'A')
import unittest from crossword import Crossword class CrosswordTestCase(unittest.TestCase): def test_crossword_set_and_get_element(self): - c = Crossword(10, 10) + crossword = Crossword(10, 10) ? ++++++++ - c[3, 3] = 'A' + crossword[3, 3] = 'A' ? ++++++++ - self.assertEqual(c[3, 3], 'A') + self.assertEqual(crossword[3, 3], 'A') ? ++++++++
c0a7554c7c8160d6a7b4023441c3cbe5e2f46ee5
tests/test_replwrap.py
tests/test_replwrap.py
import sys import unittest import pexpect from pexpect import replwrap class REPLWrapTestCase(unittest.TestCase): def test_python(self): py = replwrap.python(sys.executable) res = py.run_command("5+6") self.assertEqual(res.strip(), "11") def test_multiline(self): py = replwrap.python(sys.executable) res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) # Should raise ValueError if input is incomplete try: py.run_command("for a in range(3):") except ValueError: pass else: assert False, "Didn't raise ValueError for incorrect input" # Check that the REPL was reset (SIGINT) after the incomplete input res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) def test_existing_spawn(self): child = pexpect.spawnu("python") repl = replwrap.REPLWrapper(child, u">>> ", "import sys; sys.ps1=%r" % replwrap.PEXPECT_PROMPT) res = repl.run_command("print(7*6)") self.assertEqual(res.strip(), "42") if __name__ == '__main__': unittest.main()
import sys import unittest import pexpect from pexpect import replwrap class REPLWrapTestCase(unittest.TestCase): def test_python(self): py = replwrap.python(sys.executable) res = py.run_command("5+6") self.assertEqual(res.strip(), "11") def test_multiline(self): py = replwrap.python(sys.executable) res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) # Should raise ValueError if input is incomplete try: py.run_command("for a in range(3):") except ValueError: pass else: assert False, "Didn't raise ValueError for incorrect input" # Check that the REPL was reset (SIGINT) after the incomplete input res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) def test_existing_spawn(self): child = pexpect.spawnu("python") repl = replwrap.REPLWrapper(child, replwrap.u(">>> "), "import sys; sys.ps1=%r" % replwrap.PEXPECT_PROMPT) res = repl.run_command("print(7*6)") self.assertEqual(res.strip(), "42") if __name__ == '__main__': unittest.main()
Fix another unicode literal for Python 3.2
Fix another unicode literal for Python 3.2
Python
isc
dongguangming/pexpect,blink1073/pexpect,crdoconnor/pexpect,nodish/pexpect,Wakeupbuddy/pexpect,Depado/pexpect,crdoconnor/pexpect,quatanium/pexpect,crdoconnor/pexpect,nodish/pexpect,quatanium/pexpect,bangi123/pexpect,quatanium/pexpect,bangi123/pexpect,bangi123/pexpect,blink1073/pexpect,nodish/pexpect,Depado/pexpect,Wakeupbuddy/pexpect,blink1073/pexpect,dongguangming/pexpect,Depado/pexpect,Depado/pexpect,Wakeupbuddy/pexpect,dongguangming/pexpect,Wakeupbuddy/pexpect,dongguangming/pexpect,bangi123/pexpect
import sys import unittest import pexpect from pexpect import replwrap class REPLWrapTestCase(unittest.TestCase): def test_python(self): py = replwrap.python(sys.executable) res = py.run_command("5+6") self.assertEqual(res.strip(), "11") def test_multiline(self): py = replwrap.python(sys.executable) res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) # Should raise ValueError if input is incomplete try: py.run_command("for a in range(3):") except ValueError: pass else: assert False, "Didn't raise ValueError for incorrect input" # Check that the REPL was reset (SIGINT) after the incomplete input res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) def test_existing_spawn(self): child = pexpect.spawnu("python") - repl = replwrap.REPLWrapper(child, u">>> ", + repl = replwrap.REPLWrapper(child, replwrap.u(">>> "), "import sys; sys.ps1=%r" % replwrap.PEXPECT_PROMPT) res = repl.run_command("print(7*6)") self.assertEqual(res.strip(), "42") if __name__ == '__main__': unittest.main()
Fix another unicode literal for Python 3.2
## Code Before: import sys import unittest import pexpect from pexpect import replwrap class REPLWrapTestCase(unittest.TestCase): def test_python(self): py = replwrap.python(sys.executable) res = py.run_command("5+6") self.assertEqual(res.strip(), "11") def test_multiline(self): py = replwrap.python(sys.executable) res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) # Should raise ValueError if input is incomplete try: py.run_command("for a in range(3):") except ValueError: pass else: assert False, "Didn't raise ValueError for incorrect input" # Check that the REPL was reset (SIGINT) after the incomplete input res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) def test_existing_spawn(self): child = pexpect.spawnu("python") repl = replwrap.REPLWrapper(child, u">>> ", "import sys; sys.ps1=%r" % replwrap.PEXPECT_PROMPT) res = repl.run_command("print(7*6)") self.assertEqual(res.strip(), "42") if __name__ == '__main__': unittest.main() ## Instruction: Fix another unicode literal for Python 3.2 ## Code After: import sys import unittest import pexpect from pexpect import replwrap class REPLWrapTestCase(unittest.TestCase): def test_python(self): py = replwrap.python(sys.executable) res = py.run_command("5+6") self.assertEqual(res.strip(), "11") def test_multiline(self): py = replwrap.python(sys.executable) res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) # Should raise ValueError if input is incomplete try: py.run_command("for a in range(3):") except ValueError: pass else: assert False, "Didn't raise ValueError for incorrect input" # Check that the REPL was reset (SIGINT) after the incomplete input res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) def test_existing_spawn(self): child = pexpect.spawnu("python") repl = replwrap.REPLWrapper(child, replwrap.u(">>> "), "import sys; sys.ps1=%r" % replwrap.PEXPECT_PROMPT) res = repl.run_command("print(7*6)") self.assertEqual(res.strip(), "42") if __name__ == '__main__': unittest.main()
import sys import unittest import pexpect from pexpect import replwrap class REPLWrapTestCase(unittest.TestCase): def test_python(self): py = replwrap.python(sys.executable) res = py.run_command("5+6") self.assertEqual(res.strip(), "11") def test_multiline(self): py = replwrap.python(sys.executable) res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) # Should raise ValueError if input is incomplete try: py.run_command("for a in range(3):") except ValueError: pass else: assert False, "Didn't raise ValueError for incorrect input" # Check that the REPL was reset (SIGINT) after the incomplete input res = py.run_command("for a in range(3):\n print(a)\n") self.assertEqual(res.strip().splitlines(), ['0', '1', '2']) def test_existing_spawn(self): child = pexpect.spawnu("python") - repl = replwrap.REPLWrapper(child, u">>> ", + repl = replwrap.REPLWrapper(child, replwrap.u(">>> "), ? +++++++++ + + "import sys; sys.ps1=%r" % replwrap.PEXPECT_PROMPT) res = repl.run_command("print(7*6)") self.assertEqual(res.strip(), "42") if __name__ == '__main__': unittest.main()
39b5378b0d52e226c410671a47934a02d18f678e
scripts/extract_pivots_from_model.py
scripts/extract_pivots_from_model.py
import sys import numpy as np import torch from learn_pivots_tm import PivotLearnerModel, StraightThroughLayer def main(args): if len(args) < 1: sys.stderr.write("Required arguments: <model file> [num pivots (100)]\n") sys.exit(-1) num_pivots = 100 if len(args) > 1: num_pivots = int(args[1]) model = torch.load(args[0]) vec = np.abs(model.feature.input_layer.vector.data.cpu().numpy()) inds = np.argsort(vec) pivot_inds = inds[0, -num_pivots:] pivot_inds.sort() for x in pivot_inds: print(x) if __name__ == '__main__': main(sys.argv[1:])
import sys import numpy as np import torch from learn_pivots_dual_domain import PivotLearnerModel, StraightThroughLayer def main(args): if len(args) < 1: sys.stderr.write("Required arguments: <model file> [num pivots (100)]\n") sys.exit(-1) num_pivots = 100 if len(args) > 1: num_pivots = int(args[1]) model = torch.load(args[0]) vec = np.abs(model.feature.input_layer.vector.data.cpu().numpy()) inds = np.argsort(vec) pivot_inds = inds[0, -num_pivots:] pivot_inds.sort() for x in pivot_inds: print(x) if __name__ == '__main__': main(sys.argv[1:])
Fix import for new script location.
Fix import for new script location.
Python
apache-2.0
tmills/uda,tmills/uda
import sys import numpy as np import torch - from learn_pivots_tm import PivotLearnerModel, StraightThroughLayer + from learn_pivots_dual_domain import PivotLearnerModel, StraightThroughLayer def main(args): if len(args) < 1: sys.stderr.write("Required arguments: <model file> [num pivots (100)]\n") sys.exit(-1) num_pivots = 100 if len(args) > 1: num_pivots = int(args[1]) model = torch.load(args[0]) vec = np.abs(model.feature.input_layer.vector.data.cpu().numpy()) inds = np.argsort(vec) pivot_inds = inds[0, -num_pivots:] pivot_inds.sort() for x in pivot_inds: print(x) if __name__ == '__main__': main(sys.argv[1:])
Fix import for new script location.
## Code Before: import sys import numpy as np import torch from learn_pivots_tm import PivotLearnerModel, StraightThroughLayer def main(args): if len(args) < 1: sys.stderr.write("Required arguments: <model file> [num pivots (100)]\n") sys.exit(-1) num_pivots = 100 if len(args) > 1: num_pivots = int(args[1]) model = torch.load(args[0]) vec = np.abs(model.feature.input_layer.vector.data.cpu().numpy()) inds = np.argsort(vec) pivot_inds = inds[0, -num_pivots:] pivot_inds.sort() for x in pivot_inds: print(x) if __name__ == '__main__': main(sys.argv[1:]) ## Instruction: Fix import for new script location. ## Code After: import sys import numpy as np import torch from learn_pivots_dual_domain import PivotLearnerModel, StraightThroughLayer def main(args): if len(args) < 1: sys.stderr.write("Required arguments: <model file> [num pivots (100)]\n") sys.exit(-1) num_pivots = 100 if len(args) > 1: num_pivots = int(args[1]) model = torch.load(args[0]) vec = np.abs(model.feature.input_layer.vector.data.cpu().numpy()) inds = np.argsort(vec) pivot_inds = inds[0, -num_pivots:] pivot_inds.sort() for x in pivot_inds: print(x) if __name__ == '__main__': main(sys.argv[1:])
import sys import numpy as np import torch - from learn_pivots_tm import PivotLearnerModel, StraightThroughLayer ? ^ + from learn_pivots_dual_domain import PivotLearnerModel, StraightThroughLayer ? ^^^^^^^ +++ def main(args): if len(args) < 1: sys.stderr.write("Required arguments: <model file> [num pivots (100)]\n") sys.exit(-1) num_pivots = 100 if len(args) > 1: num_pivots = int(args[1]) model = torch.load(args[0]) vec = np.abs(model.feature.input_layer.vector.data.cpu().numpy()) inds = np.argsort(vec) pivot_inds = inds[0, -num_pivots:] pivot_inds.sort() for x in pivot_inds: print(x) if __name__ == '__main__': main(sys.argv[1:])
d6a03fad6c9280981ae3beee24de89bd6361bcc9
dumbrepl.py
dumbrepl.py
if __name__ == "__main__": import pycket.test.testhelper as th th.dumb_repl()
if __name__ == "__main__": import pycket.values import pycket.config from pycket.env import w_global_config #w_global_config.set_linklet_mode_off() import pycket.test.testhelper as th th.dumb_repl()
Make sure things are loaded right.
Make sure things are loaded right.
Python
mit
samth/pycket,pycket/pycket,pycket/pycket,samth/pycket,samth/pycket,pycket/pycket
if __name__ == "__main__": + import pycket.values + import pycket.config + from pycket.env import w_global_config + #w_global_config.set_linklet_mode_off() import pycket.test.testhelper as th th.dumb_repl()
Make sure things are loaded right.
## Code Before: if __name__ == "__main__": import pycket.test.testhelper as th th.dumb_repl() ## Instruction: Make sure things are loaded right. ## Code After: if __name__ == "__main__": import pycket.values import pycket.config from pycket.env import w_global_config #w_global_config.set_linklet_mode_off() import pycket.test.testhelper as th th.dumb_repl()
if __name__ == "__main__": + import pycket.values + import pycket.config + from pycket.env import w_global_config + #w_global_config.set_linklet_mode_off() import pycket.test.testhelper as th th.dumb_repl()
ae8273f86fc3cc7fdacadf495aa148dda796f11b
printcli.py
printcli.py
import argparse import os from labelprinter import Labelprinter if os.path.isfile('labelprinterServeConf_local.py'): import labelprinterServeConf_local as conf else: import labelprinterServeConf as conf def text(args, labelprinter): bold = 'on' if args.bold else 'off' labelprinter.printText(args.text, charSize=args.char_size, font=args.font, align=args.align, bold=bold, charStyle=args.char_style, cut=args.cut ) parser = argparse.ArgumentParser(description="A command line interface to Labello.") subparsers = parser.add_subparsers(help="commands") parser_text = subparsers.add_parser("text", help="print a text") parser_text.add_argument("text", type=str, help="the text to print") parser_text.add_argument("--char_size", type=str, default='42') parser_text.add_argument("--font", type=str, default='lettergothic') parser_text.add_argument("--align", type=str, default='left') parser_text.add_argument("--bold", action='store_true') parser_text.add_argument("--char_style", type=str, default='normal') parser_text.add_argument("--cut", type=str, default='full') parser_text.set_defaults(func=text) args = parser.parse_args() labelprinter = Labelprinter(conf=conf) args.func(args, labelprinter)
import argparse import os from labelprinter import Labelprinter import labelprinterServeConf as conf def text(args, labelprinter): bold = 'on' if args.bold else 'off' labelprinter.printText(args.text, charSize=args.char_size, font=args.font, align=args.align, bold=bold, charStyle=args.char_style, cut=args.cut ) parser = argparse.ArgumentParser(description="A command line interface to Labello.") subparsers = parser.add_subparsers(help="commands") parser_text = subparsers.add_parser("text", help="print a text") parser_text.add_argument("text", type=str, help="the text to print") parser_text.add_argument("--char_size", type=str, default='42') parser_text.add_argument("--font", type=str, default='lettergothic') parser_text.add_argument("--align", type=str, default='left') parser_text.add_argument("--bold", action='store_true') parser_text.add_argument("--char_style", type=str, default='normal') parser_text.add_argument("--cut", type=str, default='full') parser_text.set_defaults(func=text) args = parser.parse_args() labelprinter = Labelprinter(conf=conf) args.func(args, labelprinter)
Make the CLI use the new config (see e4054fb).
Make the CLI use the new config (see e4054fb).
Python
mit
chaosdorf/labello,chaosdorf/labello,chaosdorf/labello
import argparse import os from labelprinter import Labelprinter - - if os.path.isfile('labelprinterServeConf_local.py'): - import labelprinterServeConf_local as conf - else: - import labelprinterServeConf as conf + import labelprinterServeConf as conf def text(args, labelprinter): bold = 'on' if args.bold else 'off' labelprinter.printText(args.text, charSize=args.char_size, font=args.font, align=args.align, bold=bold, charStyle=args.char_style, cut=args.cut ) parser = argparse.ArgumentParser(description="A command line interface to Labello.") subparsers = parser.add_subparsers(help="commands") parser_text = subparsers.add_parser("text", help="print a text") parser_text.add_argument("text", type=str, help="the text to print") parser_text.add_argument("--char_size", type=str, default='42') parser_text.add_argument("--font", type=str, default='lettergothic') parser_text.add_argument("--align", type=str, default='left') parser_text.add_argument("--bold", action='store_true') parser_text.add_argument("--char_style", type=str, default='normal') parser_text.add_argument("--cut", type=str, default='full') parser_text.set_defaults(func=text) args = parser.parse_args() labelprinter = Labelprinter(conf=conf) args.func(args, labelprinter)
Make the CLI use the new config (see e4054fb).
## Code Before: import argparse import os from labelprinter import Labelprinter if os.path.isfile('labelprinterServeConf_local.py'): import labelprinterServeConf_local as conf else: import labelprinterServeConf as conf def text(args, labelprinter): bold = 'on' if args.bold else 'off' labelprinter.printText(args.text, charSize=args.char_size, font=args.font, align=args.align, bold=bold, charStyle=args.char_style, cut=args.cut ) parser = argparse.ArgumentParser(description="A command line interface to Labello.") subparsers = parser.add_subparsers(help="commands") parser_text = subparsers.add_parser("text", help="print a text") parser_text.add_argument("text", type=str, help="the text to print") parser_text.add_argument("--char_size", type=str, default='42') parser_text.add_argument("--font", type=str, default='lettergothic') parser_text.add_argument("--align", type=str, default='left') parser_text.add_argument("--bold", action='store_true') parser_text.add_argument("--char_style", type=str, default='normal') parser_text.add_argument("--cut", type=str, default='full') parser_text.set_defaults(func=text) args = parser.parse_args() labelprinter = Labelprinter(conf=conf) args.func(args, labelprinter) ## Instruction: Make the CLI use the new config (see e4054fb). ## Code After: import argparse import os from labelprinter import Labelprinter import labelprinterServeConf as conf def text(args, labelprinter): bold = 'on' if args.bold else 'off' labelprinter.printText(args.text, charSize=args.char_size, font=args.font, align=args.align, bold=bold, charStyle=args.char_style, cut=args.cut ) parser = argparse.ArgumentParser(description="A command line interface to Labello.") subparsers = parser.add_subparsers(help="commands") parser_text = subparsers.add_parser("text", help="print a text") parser_text.add_argument("text", type=str, help="the text to print") parser_text.add_argument("--char_size", type=str, default='42') parser_text.add_argument("--font", type=str, default='lettergothic') parser_text.add_argument("--align", type=str, default='left') parser_text.add_argument("--bold", action='store_true') parser_text.add_argument("--char_style", type=str, default='normal') parser_text.add_argument("--cut", type=str, default='full') parser_text.set_defaults(func=text) args = parser.parse_args() labelprinter = Labelprinter(conf=conf) args.func(args, labelprinter)
import argparse import os from labelprinter import Labelprinter - - if os.path.isfile('labelprinterServeConf_local.py'): - import labelprinterServeConf_local as conf - else: - import labelprinterServeConf as conf ? ---- + import labelprinterServeConf as conf def text(args, labelprinter): bold = 'on' if args.bold else 'off' labelprinter.printText(args.text, charSize=args.char_size, font=args.font, align=args.align, bold=bold, charStyle=args.char_style, cut=args.cut ) parser = argparse.ArgumentParser(description="A command line interface to Labello.") subparsers = parser.add_subparsers(help="commands") parser_text = subparsers.add_parser("text", help="print a text") parser_text.add_argument("text", type=str, help="the text to print") parser_text.add_argument("--char_size", type=str, default='42') parser_text.add_argument("--font", type=str, default='lettergothic') parser_text.add_argument("--align", type=str, default='left') parser_text.add_argument("--bold", action='store_true') parser_text.add_argument("--char_style", type=str, default='normal') parser_text.add_argument("--cut", type=str, default='full') parser_text.set_defaults(func=text) args = parser.parse_args() labelprinter = Labelprinter(conf=conf) args.func(args, labelprinter)
364aa00d3f97711e25654f63e5d4ab5d6b4e7d44
tests/mod_auth_tests.py
tests/mod_auth_tests.py
from tests.app_tests import BaseTestCase from app.mod_auth.models import * from app.mod_auth.views import user_is_logged_in from flask import url_for USERNAME = 'username' PASSWORD = 'password' INVALID_USERNAME = 'wrong_username' INVALID_PASSWORD = 'wrong_password' class TestAuth(BaseTestCase): def setUp(self): super().setUp() user = User(username=USERNAME, password=PASSWORD) db.session.add(user) db.session.commit() def login(self, username, password): return self.client.post(url_for('auth.login'), data=dict( username=username, password=password ), follow_redirects=True) def logout(self): return self.client.get(url_for('auth.logout', follow_redirects=True)) def test_login(self): with self.client: self.login(INVALID_USERNAME, PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(INVALID_USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) def test_logout(self): with self.client: self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) self.logout() self.assertFalse(user_is_logged_in())
from tests.app_tests import BaseTestCase from app.mod_auth.models import * from app.mod_auth.views import user_is_logged_in from flask import url_for USERNAME = 'username' PASSWORD = 'password' INVALID_USERNAME = 'wrong_username' INVALID_PASSWORD = 'wrong_password' class TestAuth(BaseTestCase): def setUp(self): super().setUp() User.create(username=USERNAME, password=PASSWORD) def login(self, username, password): return self.client.post(url_for('auth.login'), data=dict( username=username, password=password ), follow_redirects=True) def logout(self): return self.client.get(url_for('auth.logout', follow_redirects=True)) def test_login(self): with self.client: self.login(INVALID_USERNAME, PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(INVALID_USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) def test_logout(self): with self.client: self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) self.logout() self.assertFalse(user_is_logged_in())
Use BaseModel.create to create a test user
Use BaseModel.create to create a test user
Python
mit
ziel980/website,ziel980/website
from tests.app_tests import BaseTestCase from app.mod_auth.models import * from app.mod_auth.views import user_is_logged_in from flask import url_for USERNAME = 'username' PASSWORD = 'password' INVALID_USERNAME = 'wrong_username' INVALID_PASSWORD = 'wrong_password' class TestAuth(BaseTestCase): def setUp(self): super().setUp() - user = User(username=USERNAME, password=PASSWORD) + User.create(username=USERNAME, password=PASSWORD) - db.session.add(user) - db.session.commit() def login(self, username, password): return self.client.post(url_for('auth.login'), data=dict( username=username, password=password ), follow_redirects=True) def logout(self): return self.client.get(url_for('auth.logout', follow_redirects=True)) def test_login(self): with self.client: self.login(INVALID_USERNAME, PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(INVALID_USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) def test_logout(self): with self.client: self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) self.logout() self.assertFalse(user_is_logged_in())
Use BaseModel.create to create a test user
## Code Before: from tests.app_tests import BaseTestCase from app.mod_auth.models import * from app.mod_auth.views import user_is_logged_in from flask import url_for USERNAME = 'username' PASSWORD = 'password' INVALID_USERNAME = 'wrong_username' INVALID_PASSWORD = 'wrong_password' class TestAuth(BaseTestCase): def setUp(self): super().setUp() user = User(username=USERNAME, password=PASSWORD) db.session.add(user) db.session.commit() def login(self, username, password): return self.client.post(url_for('auth.login'), data=dict( username=username, password=password ), follow_redirects=True) def logout(self): return self.client.get(url_for('auth.logout', follow_redirects=True)) def test_login(self): with self.client: self.login(INVALID_USERNAME, PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(INVALID_USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) def test_logout(self): with self.client: self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) self.logout() self.assertFalse(user_is_logged_in()) ## Instruction: Use BaseModel.create to create a test user ## Code After: from tests.app_tests import BaseTestCase from app.mod_auth.models import * from app.mod_auth.views import user_is_logged_in from flask import url_for USERNAME = 'username' PASSWORD = 'password' INVALID_USERNAME = 'wrong_username' INVALID_PASSWORD = 'wrong_password' class TestAuth(BaseTestCase): def setUp(self): super().setUp() User.create(username=USERNAME, password=PASSWORD) def login(self, username, password): return self.client.post(url_for('auth.login'), data=dict( username=username, password=password ), follow_redirects=True) def logout(self): return self.client.get(url_for('auth.logout', follow_redirects=True)) def test_login(self): with self.client: self.login(INVALID_USERNAME, PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(INVALID_USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) def test_logout(self): with self.client: self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) self.logout() self.assertFalse(user_is_logged_in())
from tests.app_tests import BaseTestCase from app.mod_auth.models import * from app.mod_auth.views import user_is_logged_in from flask import url_for USERNAME = 'username' PASSWORD = 'password' INVALID_USERNAME = 'wrong_username' INVALID_PASSWORD = 'wrong_password' class TestAuth(BaseTestCase): def setUp(self): super().setUp() - user = User(username=USERNAME, password=PASSWORD) ? ------- + User.create(username=USERNAME, password=PASSWORD) ? +++++++ - db.session.add(user) - db.session.commit() def login(self, username, password): return self.client.post(url_for('auth.login'), data=dict( username=username, password=password ), follow_redirects=True) def logout(self): return self.client.get(url_for('auth.logout', follow_redirects=True)) def test_login(self): with self.client: self.login(INVALID_USERNAME, PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(INVALID_USERNAME, INVALID_PASSWORD) self.assertFalse(user_is_logged_in()) self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) def test_logout(self): with self.client: self.login(USERNAME, PASSWORD) self.assertTrue(user_is_logged_in()) self.logout() self.assertFalse(user_is_logged_in())
ce3fa12a6fc497264529d5f44e3f4a20b5317fcd
gapipy/resources/booking/customer.py
gapipy/resources/booking/customer.py
from __future__ import unicode_literals from ..base import Resource class Customer(Resource): _resource_name = 'customers' _is_listable = False _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'place_of_birth', 'meal_preference', 'meal_notes', 'emergency_contacts', 'medical_notes', 'phone_numbers', 'account_email', 'name', 'passport', 'address', 'nationality', ] _date_fields = ['date_of_birth', ] @property def _resource_collection_fields(self): from .booking import Booking return [ ('bookings', Booking), ]
from __future__ import unicode_literals from ..base import Resource class Customer(Resource): _resource_name = 'customers' _is_listable = False _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'place_of_birth', 'meal_preference', 'meal_notes', 'emergency_contacts', 'medical_notes', 'phone_numbers', 'account_email', 'name', 'passport', 'address', 'nationality', 'gender', ] _date_fields = ['date_of_birth', ] @property def _resource_collection_fields(self): from .booking import Booking return [ ('bookings', Booking), ]
Add gender to Customer model.
Add gender to Customer model.
Python
mit
gadventures/gapipy
from __future__ import unicode_literals from ..base import Resource class Customer(Resource): _resource_name = 'customers' _is_listable = False _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'place_of_birth', 'meal_preference', 'meal_notes', 'emergency_contacts', 'medical_notes', 'phone_numbers', 'account_email', 'name', 'passport', 'address', 'nationality', + 'gender', ] _date_fields = ['date_of_birth', ] @property def _resource_collection_fields(self): from .booking import Booking return [ ('bookings', Booking), ]
Add gender to Customer model.
## Code Before: from __future__ import unicode_literals from ..base import Resource class Customer(Resource): _resource_name = 'customers' _is_listable = False _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'place_of_birth', 'meal_preference', 'meal_notes', 'emergency_contacts', 'medical_notes', 'phone_numbers', 'account_email', 'name', 'passport', 'address', 'nationality', ] _date_fields = ['date_of_birth', ] @property def _resource_collection_fields(self): from .booking import Booking return [ ('bookings', Booking), ] ## Instruction: Add gender to Customer model. ## Code After: from __future__ import unicode_literals from ..base import Resource class Customer(Resource): _resource_name = 'customers' _is_listable = False _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'place_of_birth', 'meal_preference', 'meal_notes', 'emergency_contacts', 'medical_notes', 'phone_numbers', 'account_email', 'name', 'passport', 'address', 'nationality', 'gender', ] _date_fields = ['date_of_birth', ] @property def _resource_collection_fields(self): from .booking import Booking return [ ('bookings', Booking), ]
from __future__ import unicode_literals from ..base import Resource class Customer(Resource): _resource_name = 'customers' _is_listable = False _is_parent_resource = True _as_is_fields = [ 'id', 'href', 'place_of_birth', 'meal_preference', 'meal_notes', 'emergency_contacts', 'medical_notes', 'phone_numbers', 'account_email', 'name', 'passport', 'address', 'nationality', + 'gender', ] _date_fields = ['date_of_birth', ] @property def _resource_collection_fields(self): from .booking import Booking return [ ('bookings', Booking), ]
8bacd0f657a931754d8c03e2de86c5e00ac5f791
modoboa/lib/cryptutils.py
modoboa/lib/cryptutils.py
from Crypto.Cipher import AES import base64 import random import string from modoboa.lib import parameters def random_key(l=16): """Generate a random key :param integer l: the key's length :return: a string """ char_set = string.digits + string.letters + string.punctuation return ''.join(random.sample(char_set * l, l)) def encrypt(clear): key = parameters.get_admin("SECRET_KEY", app="core") obj = AES.new(key, AES.MODE_ECB) if type(clear) is unicode: clear = clear.encode("utf-8") if len(clear) % AES.block_size: clear += " " * (AES.block_size - len(clear) % AES.block_size) ciph = obj.encrypt(clear) ciph = base64.b64encode(ciph) return ciph def decrypt(ciph): obj = AES.new( parameters.get_admin("SECRET_KEY", app="core"), AES.MODE_ECB ) ciph = base64.b64decode(ciph) clear = obj.decrypt(ciph) return clear.rstrip(' ') def get_password(request): return decrypt(request.session["password"])
"""Crypto related utilities.""" import base64 import random import string from Crypto.Cipher import AES from modoboa.lib import parameters def random_key(l=16): """Generate a random key. :param integer l: the key's length :return: a string """ population = string.digits + string.letters + string.punctuation while True: key = "".join(random.sample(population * l, l)) if len(key) == l: return key def encrypt(clear): key = parameters.get_admin("SECRET_KEY", app="core") obj = AES.new(key, AES.MODE_ECB) if type(clear) is unicode: clear = clear.encode("utf-8") if len(clear) % AES.block_size: clear += " " * (AES.block_size - len(clear) % AES.block_size) ciph = obj.encrypt(clear) ciph = base64.b64encode(ciph) return ciph def decrypt(ciph): obj = AES.new( parameters.get_admin("SECRET_KEY", app="core"), AES.MODE_ECB ) ciph = base64.b64decode(ciph) clear = obj.decrypt(ciph) return clear.rstrip(' ') def get_password(request): return decrypt(request.session["password"])
Make sure key has the required size.
Make sure key has the required size. see #867
Python
isc
tonioo/modoboa,modoboa/modoboa,bearstech/modoboa,carragom/modoboa,tonioo/modoboa,modoboa/modoboa,bearstech/modoboa,carragom/modoboa,bearstech/modoboa,bearstech/modoboa,modoboa/modoboa,carragom/modoboa,modoboa/modoboa,tonioo/modoboa
- from Crypto.Cipher import AES + """Crypto related utilities.""" + import base64 import random import string + + from Crypto.Cipher import AES + from modoboa.lib import parameters def random_key(l=16): - """Generate a random key + """Generate a random key. :param integer l: the key's length :return: a string """ - char_set = string.digits + string.letters + string.punctuation + population = string.digits + string.letters + string.punctuation - return ''.join(random.sample(char_set * l, l)) + while True: + key = "".join(random.sample(population * l, l)) + if len(key) == l: + return key def encrypt(clear): key = parameters.get_admin("SECRET_KEY", app="core") obj = AES.new(key, AES.MODE_ECB) if type(clear) is unicode: clear = clear.encode("utf-8") if len(clear) % AES.block_size: clear += " " * (AES.block_size - len(clear) % AES.block_size) ciph = obj.encrypt(clear) ciph = base64.b64encode(ciph) return ciph def decrypt(ciph): obj = AES.new( parameters.get_admin("SECRET_KEY", app="core"), AES.MODE_ECB ) ciph = base64.b64decode(ciph) clear = obj.decrypt(ciph) return clear.rstrip(' ') def get_password(request): return decrypt(request.session["password"])
Make sure key has the required size.
## Code Before: from Crypto.Cipher import AES import base64 import random import string from modoboa.lib import parameters def random_key(l=16): """Generate a random key :param integer l: the key's length :return: a string """ char_set = string.digits + string.letters + string.punctuation return ''.join(random.sample(char_set * l, l)) def encrypt(clear): key = parameters.get_admin("SECRET_KEY", app="core") obj = AES.new(key, AES.MODE_ECB) if type(clear) is unicode: clear = clear.encode("utf-8") if len(clear) % AES.block_size: clear += " " * (AES.block_size - len(clear) % AES.block_size) ciph = obj.encrypt(clear) ciph = base64.b64encode(ciph) return ciph def decrypt(ciph): obj = AES.new( parameters.get_admin("SECRET_KEY", app="core"), AES.MODE_ECB ) ciph = base64.b64decode(ciph) clear = obj.decrypt(ciph) return clear.rstrip(' ') def get_password(request): return decrypt(request.session["password"]) ## Instruction: Make sure key has the required size. ## Code After: """Crypto related utilities.""" import base64 import random import string from Crypto.Cipher import AES from modoboa.lib import parameters def random_key(l=16): """Generate a random key. :param integer l: the key's length :return: a string """ population = string.digits + string.letters + string.punctuation while True: key = "".join(random.sample(population * l, l)) if len(key) == l: return key def encrypt(clear): key = parameters.get_admin("SECRET_KEY", app="core") obj = AES.new(key, AES.MODE_ECB) if type(clear) is unicode: clear = clear.encode("utf-8") if len(clear) % AES.block_size: clear += " " * (AES.block_size - len(clear) % AES.block_size) ciph = obj.encrypt(clear) ciph = base64.b64encode(ciph) return ciph def decrypt(ciph): obj = AES.new( parameters.get_admin("SECRET_KEY", app="core"), AES.MODE_ECB ) ciph = base64.b64decode(ciph) clear = obj.decrypt(ciph) return clear.rstrip(' ') def get_password(request): return decrypt(request.session["password"])
- from Crypto.Cipher import AES + """Crypto related utilities.""" + import base64 import random import string + + from Crypto.Cipher import AES + from modoboa.lib import parameters def random_key(l=16): - """Generate a random key + """Generate a random key. ? + :param integer l: the key's length :return: a string """ - char_set = string.digits + string.letters + string.punctuation ? ^^ ---- + population = string.digits + string.letters + string.punctuation ? ^^^^^ +++ - return ''.join(random.sample(char_set * l, l)) + while True: + key = "".join(random.sample(population * l, l)) + if len(key) == l: + return key def encrypt(clear): key = parameters.get_admin("SECRET_KEY", app="core") obj = AES.new(key, AES.MODE_ECB) if type(clear) is unicode: clear = clear.encode("utf-8") if len(clear) % AES.block_size: clear += " " * (AES.block_size - len(clear) % AES.block_size) ciph = obj.encrypt(clear) ciph = base64.b64encode(ciph) return ciph def decrypt(ciph): obj = AES.new( parameters.get_admin("SECRET_KEY", app="core"), AES.MODE_ECB ) ciph = base64.b64decode(ciph) clear = obj.decrypt(ciph) return clear.rstrip(' ') def get_password(request): return decrypt(request.session["password"])
46dda5e761d3752fce26b379cc8542e3f5244376
examples/fabfile.py
examples/fabfile.py
from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just below @task @task(default=True, alias="success") @notify def sweet_task(some_arg, other_arg): """Always succeeds""" print(green("My sweet task always runs properly.")) @task(alias="failure") @notify def boring_task(some_arg): """Always fails""" print(red("My boring task is designed to fail.")) raise Exception("failure!!!") env.roledefs.update({ 'webserver': ['localhost'] }) @task(alias="has_roles") @notify @roles('webserver') @hosts('localhost') def roles_task(arg_1, arg_2): run('touch /tmp/fab_test')
from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just below @task @notify @task(default=True, alias="success") def sweet_task(some_arg, other_arg): """Always succeeds""" print(green("My sweet task always runs properly.")) @notify @task(alias="failure") def boring_task(some_arg): """Always fails""" print(red("My boring task is designed to fail.")) raise Exception("failure!!!") env.roledefs.update({ 'webserver': ['localhost'] }) @notify @task(alias="has_roles") @roles('webserver') @hosts('localhost') def roles_task(arg_1, arg_2): run('touch /tmp/fab_test')
Make sure @ notify is the first decorator
Make sure @ notify is the first decorator fixes #91
Python
bsd-3-clause
DataDog/dogapi,DataDog/dogapi
from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just below @task + @notify @task(default=True, alias="success") - @notify def sweet_task(some_arg, other_arg): """Always succeeds""" print(green("My sweet task always runs properly.")) + @notify @task(alias="failure") - @notify def boring_task(some_arg): """Always fails""" print(red("My boring task is designed to fail.")) raise Exception("failure!!!") env.roledefs.update({ 'webserver': ['localhost'] }) + @notify @task(alias="has_roles") - @notify @roles('webserver') @hosts('localhost') def roles_task(arg_1, arg_2): run('touch /tmp/fab_test')
Make sure @ notify is the first decorator
## Code Before: from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just below @task @task(default=True, alias="success") @notify def sweet_task(some_arg, other_arg): """Always succeeds""" print(green("My sweet task always runs properly.")) @task(alias="failure") @notify def boring_task(some_arg): """Always fails""" print(red("My boring task is designed to fail.")) raise Exception("failure!!!") env.roledefs.update({ 'webserver': ['localhost'] }) @task(alias="has_roles") @notify @roles('webserver') @hosts('localhost') def roles_task(arg_1, arg_2): run('touch /tmp/fab_test') ## Instruction: Make sure @ notify is the first decorator ## Code After: from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just below @task @notify @task(default=True, alias="success") def sweet_task(some_arg, other_arg): """Always succeeds""" print(green("My sweet task always runs properly.")) @notify @task(alias="failure") def boring_task(some_arg): """Always fails""" print(red("My boring task is designed to fail.")) raise Exception("failure!!!") env.roledefs.update({ 'webserver': ['localhost'] }) @notify @task(alias="has_roles") @roles('webserver') @hosts('localhost') def roles_task(arg_1, arg_2): run('touch /tmp/fab_test')
from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just below @task + @notify @task(default=True, alias="success") - @notify def sweet_task(some_arg, other_arg): """Always succeeds""" print(green("My sweet task always runs properly.")) + @notify @task(alias="failure") - @notify def boring_task(some_arg): """Always fails""" print(red("My boring task is designed to fail.")) raise Exception("failure!!!") env.roledefs.update({ 'webserver': ['localhost'] }) + @notify @task(alias="has_roles") - @notify @roles('webserver') @hosts('localhost') def roles_task(arg_1, arg_2): run('touch /tmp/fab_test')
5ff18f77dd3f38c7209e2b7bca1f2f84d002b00a
tools/glidein_ls.py
tools/glidein_ls.py
import os import string import stat import sys sys.path.append("lib") sys.path.append("../lib") import glideinMonitor def createDirMonitorFile(monitor_file_name,monitor_control_relname, argv,condor_status): fd=open(monitor_file_name,"w") try: fd.write("#!/bin/sh\n") fd.write("outdir=`ls -lt .. | tail -1 | awk '{print $9}'`\n") fd.write("(cd ../$outdir; if [ $? -eq 0 ]; then ls %s; else echo Internal error; fi)\n"%(string.join(argv))) fd.write("echo Done > %s\n"%monitor_control_relname) finally: fd.close() os.chmod(monitor_file_name,stat.S_IRWXU) args=glideinMonitor.parseArgs(sys.argv[1:]) glideinMonitor.monitor(args['jid'],args['schedd_name'],args['pool_name'], args['timeout'], createDirMonitorFile,args['argv'])
import os,os.path import string import stat import sys sys.path.append(os.path.join(os.path[0],"lib")) sys.path.append(os.path.join(os.path[0],"../lib")) import glideinMonitor def createDirMonitorFile(monitor_file_name,monitor_control_relname, argv,condor_status): fd=open(monitor_file_name,"w") try: fd.write("#!/bin/sh\n") fd.write("outdir=`ls -lt .. | tail -1 | awk '{print $9}'`\n") fd.write("(cd ../$outdir; if [ $? -eq 0 ]; then ls %s; else echo Internal error; fi)\n"%(string.join(argv))) fd.write("echo Done > %s\n"%monitor_control_relname) finally: fd.close() os.chmod(monitor_file_name,stat.S_IRWXU) args=glideinMonitor.parseArgs(sys.argv[1:]) glideinMonitor.monitor(args['jid'],args['schedd_name'],args['pool_name'], args['timeout'], createDirMonitorFile,args['argv'])
Change rel paths into abspaths
Change rel paths into abspaths
Python
bsd-3-clause
bbockelm/glideinWMS,bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS,holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS
- import os + import os,os.path import string import stat import sys - sys.path.append("lib") - sys.path.append("../lib") + sys.path.append(os.path.join(os.path[0],"lib")) + sys.path.append(os.path.join(os.path[0],"../lib")) import glideinMonitor def createDirMonitorFile(monitor_file_name,monitor_control_relname, argv,condor_status): fd=open(monitor_file_name,"w") try: fd.write("#!/bin/sh\n") fd.write("outdir=`ls -lt .. | tail -1 | awk '{print $9}'`\n") fd.write("(cd ../$outdir; if [ $? -eq 0 ]; then ls %s; else echo Internal error; fi)\n"%(string.join(argv))) fd.write("echo Done > %s\n"%monitor_control_relname) finally: fd.close() os.chmod(monitor_file_name,stat.S_IRWXU) args=glideinMonitor.parseArgs(sys.argv[1:]) glideinMonitor.monitor(args['jid'],args['schedd_name'],args['pool_name'], args['timeout'], createDirMonitorFile,args['argv'])
Change rel paths into abspaths
## Code Before: import os import string import stat import sys sys.path.append("lib") sys.path.append("../lib") import glideinMonitor def createDirMonitorFile(monitor_file_name,monitor_control_relname, argv,condor_status): fd=open(monitor_file_name,"w") try: fd.write("#!/bin/sh\n") fd.write("outdir=`ls -lt .. | tail -1 | awk '{print $9}'`\n") fd.write("(cd ../$outdir; if [ $? -eq 0 ]; then ls %s; else echo Internal error; fi)\n"%(string.join(argv))) fd.write("echo Done > %s\n"%monitor_control_relname) finally: fd.close() os.chmod(monitor_file_name,stat.S_IRWXU) args=glideinMonitor.parseArgs(sys.argv[1:]) glideinMonitor.monitor(args['jid'],args['schedd_name'],args['pool_name'], args['timeout'], createDirMonitorFile,args['argv']) ## Instruction: Change rel paths into abspaths ## Code After: import os,os.path import string import stat import sys sys.path.append(os.path.join(os.path[0],"lib")) sys.path.append(os.path.join(os.path[0],"../lib")) import glideinMonitor def createDirMonitorFile(monitor_file_name,monitor_control_relname, argv,condor_status): fd=open(monitor_file_name,"w") try: fd.write("#!/bin/sh\n") fd.write("outdir=`ls -lt .. | tail -1 | awk '{print $9}'`\n") fd.write("(cd ../$outdir; if [ $? -eq 0 ]; then ls %s; else echo Internal error; fi)\n"%(string.join(argv))) fd.write("echo Done > %s\n"%monitor_control_relname) finally: fd.close() os.chmod(monitor_file_name,stat.S_IRWXU) args=glideinMonitor.parseArgs(sys.argv[1:]) glideinMonitor.monitor(args['jid'],args['schedd_name'],args['pool_name'], args['timeout'], createDirMonitorFile,args['argv'])
- import os + import os,os.path import string import stat import sys - sys.path.append("lib") - sys.path.append("../lib") + sys.path.append(os.path.join(os.path[0],"lib")) + sys.path.append(os.path.join(os.path[0],"../lib")) import glideinMonitor def createDirMonitorFile(monitor_file_name,monitor_control_relname, argv,condor_status): fd=open(monitor_file_name,"w") try: fd.write("#!/bin/sh\n") fd.write("outdir=`ls -lt .. | tail -1 | awk '{print $9}'`\n") fd.write("(cd ../$outdir; if [ $? -eq 0 ]; then ls %s; else echo Internal error; fi)\n"%(string.join(argv))) fd.write("echo Done > %s\n"%monitor_control_relname) finally: fd.close() os.chmod(monitor_file_name,stat.S_IRWXU) args=glideinMonitor.parseArgs(sys.argv[1:]) glideinMonitor.monitor(args['jid'],args['schedd_name'],args['pool_name'], args['timeout'], createDirMonitorFile,args['argv'])
d608d9f474f089df8f5d6e0e899554f9324e84f3
squash/dashboard/urls.py
squash/dashboard/urls.py
from django.conf.urls import include, url from django.contrib import admin from rest_framework.authtoken.views import obtain_auth_token from rest_framework.routers import DefaultRouter from . import views api_router = DefaultRouter() api_router.register(r'jobs', views.JobViewSet) api_router.register(r'metrics', views.MetricViewSet) urlpatterns = [ url(r'^dashboard/admin', include(admin.site.urls)), url(r'^dashboard/api/', include(api_router.urls)), url(r'^dashboard/api/token/', obtain_auth_token, name='api-token'), url(r'^$', views.HomeView.as_view(), name='home'), url(r'^(?P<pk>[a-zA-Z0-9]*$)', views.ListMetricsView.as_view(), name='metrics-list'), ]
from django.conf.urls import include, url from django.contrib import admin from rest_framework.authtoken.views import obtain_auth_token from rest_framework.routers import DefaultRouter from . import views admin.site.site_header = 'SQUASH Admin' api_router = DefaultRouter() api_router.register(r'jobs', views.JobViewSet) api_router.register(r'metrics', views.MetricViewSet) urlpatterns = [ url(r'^dashboard/admin', include(admin.site.urls)), url(r'^dashboard/api/', include(api_router.urls)), url(r'^dashboard/api/token/', obtain_auth_token, name='api-token'), url(r'^$', views.HomeView.as_view(), name='home'), url(r'^(?P<pk>[a-zA-Z0-9]*$)', views.ListMetricsView.as_view(), name='metrics-list'), ]
Set title for SQUASH admin interface
Set title for SQUASH admin interface
Python
mit
lsst-sqre/qa-dashboard,lsst-sqre/qa-dashboard,lsst-sqre/qa-dashboard
from django.conf.urls import include, url from django.contrib import admin from rest_framework.authtoken.views import obtain_auth_token from rest_framework.routers import DefaultRouter from . import views + admin.site.site_header = 'SQUASH Admin' api_router = DefaultRouter() api_router.register(r'jobs', views.JobViewSet) api_router.register(r'metrics', views.MetricViewSet) urlpatterns = [ url(r'^dashboard/admin', include(admin.site.urls)), url(r'^dashboard/api/', include(api_router.urls)), url(r'^dashboard/api/token/', obtain_auth_token, name='api-token'), url(r'^$', views.HomeView.as_view(), name='home'), url(r'^(?P<pk>[a-zA-Z0-9]*$)', views.ListMetricsView.as_view(), name='metrics-list'), ]
Set title for SQUASH admin interface
## Code Before: from django.conf.urls import include, url from django.contrib import admin from rest_framework.authtoken.views import obtain_auth_token from rest_framework.routers import DefaultRouter from . import views api_router = DefaultRouter() api_router.register(r'jobs', views.JobViewSet) api_router.register(r'metrics', views.MetricViewSet) urlpatterns = [ url(r'^dashboard/admin', include(admin.site.urls)), url(r'^dashboard/api/', include(api_router.urls)), url(r'^dashboard/api/token/', obtain_auth_token, name='api-token'), url(r'^$', views.HomeView.as_view(), name='home'), url(r'^(?P<pk>[a-zA-Z0-9]*$)', views.ListMetricsView.as_view(), name='metrics-list'), ] ## Instruction: Set title for SQUASH admin interface ## Code After: from django.conf.urls import include, url from django.contrib import admin from rest_framework.authtoken.views import obtain_auth_token from rest_framework.routers import DefaultRouter from . import views admin.site.site_header = 'SQUASH Admin' api_router = DefaultRouter() api_router.register(r'jobs', views.JobViewSet) api_router.register(r'metrics', views.MetricViewSet) urlpatterns = [ url(r'^dashboard/admin', include(admin.site.urls)), url(r'^dashboard/api/', include(api_router.urls)), url(r'^dashboard/api/token/', obtain_auth_token, name='api-token'), url(r'^$', views.HomeView.as_view(), name='home'), url(r'^(?P<pk>[a-zA-Z0-9]*$)', views.ListMetricsView.as_view(), name='metrics-list'), ]
from django.conf.urls import include, url from django.contrib import admin from rest_framework.authtoken.views import obtain_auth_token from rest_framework.routers import DefaultRouter from . import views + admin.site.site_header = 'SQUASH Admin' api_router = DefaultRouter() api_router.register(r'jobs', views.JobViewSet) api_router.register(r'metrics', views.MetricViewSet) urlpatterns = [ url(r'^dashboard/admin', include(admin.site.urls)), url(r'^dashboard/api/', include(api_router.urls)), url(r'^dashboard/api/token/', obtain_auth_token, name='api-token'), url(r'^$', views.HomeView.as_view(), name='home'), url(r'^(?P<pk>[a-zA-Z0-9]*$)', views.ListMetricsView.as_view(), name='metrics-list'), ]
2207dd266887e812cae9da67ca00bef80c9985fd
thefuck/shells/__init__.py
thefuck/shells/__init__.py
import os from psutil import Process from .bash import Bash from .fish import Fish from .generic import Generic from .tcsh import Tcsh from .zsh import Zsh shells = {'bash': Bash, 'fish': Fish, 'zsh': Zsh, 'csh': Tcsh, 'tcsh': Tcsh} def _get_shell(): try: shell_name = Process(os.getpid()).parent().name() except TypeError: shell_name = Process(os.getpid()).parent.name return shells.get(shell_name, Generic)() shell = _get_shell()
import os from psutil import Process from .bash import Bash from .fish import Fish from .generic import Generic from .tcsh import Tcsh from .zsh import Zsh shells = {'bash': Bash, 'fish': Fish, 'zsh': Zsh, 'csh': Tcsh, 'tcsh': Tcsh} def _get_shell(): proc = Process(os.getpid()) while (proc is not None): name = None try: name = proc.name() except TypeError: name = proc.name name = os.path.splitext(name)[0] if name in shells: return shells[name]() try: proc = proc.parent() except TypeError: proc = proc.parent return Generic() shell = _get_shell()
Update _get_shell to work with Windows
Update _get_shell to work with Windows - _get_shell assumed the parent process would always be the shell process, in Powershell the parent process is Python, with the grandparent being the shell - Switched to walking the process tree so the same code path can be used in both places
Python
mit
mlk/thefuck,SimenB/thefuck,SimenB/thefuck,mlk/thefuck,nvbn/thefuck,Clpsplug/thefuck,scorphus/thefuck,Clpsplug/thefuck,scorphus/thefuck,nvbn/thefuck
import os from psutil import Process from .bash import Bash from .fish import Fish from .generic import Generic from .tcsh import Tcsh from .zsh import Zsh shells = {'bash': Bash, 'fish': Fish, 'zsh': Zsh, 'csh': Tcsh, 'tcsh': Tcsh} def _get_shell(): + proc = Process(os.getpid()) + + while (proc is not None): + name = None - try: + try: - shell_name = Process(os.getpid()).parent().name() + name = proc.name() - except TypeError: + except TypeError: - shell_name = Process(os.getpid()).parent.name - return shells.get(shell_name, Generic)() + name = proc.name + + name = os.path.splitext(name)[0] + + if name in shells: + return shells[name]() + + try: + proc = proc.parent() + except TypeError: + proc = proc.parent + + return Generic() shell = _get_shell()
Update _get_shell to work with Windows
## Code Before: import os from psutil import Process from .bash import Bash from .fish import Fish from .generic import Generic from .tcsh import Tcsh from .zsh import Zsh shells = {'bash': Bash, 'fish': Fish, 'zsh': Zsh, 'csh': Tcsh, 'tcsh': Tcsh} def _get_shell(): try: shell_name = Process(os.getpid()).parent().name() except TypeError: shell_name = Process(os.getpid()).parent.name return shells.get(shell_name, Generic)() shell = _get_shell() ## Instruction: Update _get_shell to work with Windows ## Code After: import os from psutil import Process from .bash import Bash from .fish import Fish from .generic import Generic from .tcsh import Tcsh from .zsh import Zsh shells = {'bash': Bash, 'fish': Fish, 'zsh': Zsh, 'csh': Tcsh, 'tcsh': Tcsh} def _get_shell(): proc = Process(os.getpid()) while (proc is not None): name = None try: name = proc.name() except TypeError: name = proc.name name = os.path.splitext(name)[0] if name in shells: return shells[name]() try: proc = proc.parent() except TypeError: proc = proc.parent return Generic() shell = _get_shell()
import os from psutil import Process from .bash import Bash from .fish import Fish from .generic import Generic from .tcsh import Tcsh from .zsh import Zsh shells = {'bash': Bash, 'fish': Fish, 'zsh': Zsh, 'csh': Tcsh, 'tcsh': Tcsh} def _get_shell(): + proc = Process(os.getpid()) + + while (proc is not None): + name = None - try: + try: ? ++++ - shell_name = Process(os.getpid()).parent().name() + name = proc.name() - except TypeError: + except TypeError: ? ++++ - shell_name = Process(os.getpid()).parent.name - return shells.get(shell_name, Generic)() + name = proc.name + + name = os.path.splitext(name)[0] + + if name in shells: + return shells[name]() + + try: + proc = proc.parent() + except TypeError: + proc = proc.parent + + return Generic() shell = _get_shell()
62a20e28a5f0bc9b6a9eab67891c875562337c94
rwt/tests/test_deps.py
rwt/tests/test_deps.py
import pkg_resources from rwt import deps def test_entry_points(): """ Ensure entry points are visible after making packages visible """ with deps.on_sys_path('jaraco.mongodb'): eps = pkg_resources.iter_entry_points('pytest11') assert list(eps), "Entry points not found" class TestInstallCheck: def test_installed(self): assert deps.pkg_installed('rwt') def test_not_installed(self): assert not deps.pkg_installed('not_a_package') def test_installed_version(self): assert not deps.pkg_installed('rwt==0.0') def test_not_installed_args(self): args = [ '-i', 'https://devpi.net', '-r', 'requirements.txt', 'rwt', 'not_a_package', 'rwt==0.0', ] expected = args.copy() expected.remove('rwt') filtered = deps.not_installed(args) assert list(filtered) == expected
import copy import pkg_resources from rwt import deps def test_entry_points(): """ Ensure entry points are visible after making packages visible """ with deps.on_sys_path('jaraco.mongodb'): eps = pkg_resources.iter_entry_points('pytest11') assert list(eps), "Entry points not found" class TestInstallCheck: def test_installed(self): assert deps.pkg_installed('rwt') def test_not_installed(self): assert not deps.pkg_installed('not_a_package') def test_installed_version(self): assert not deps.pkg_installed('rwt==0.0') def test_not_installed_args(self): args = [ '-i', 'https://devpi.net', '-r', 'requirements.txt', 'rwt', 'not_a_package', 'rwt==0.0', ] expected = copy.copy(args) expected.remove('rwt') filtered = deps.not_installed(args) assert list(filtered) == expected
Fix test failure on Python 2
Fix test failure on Python 2
Python
mit
jaraco/rwt
+ import copy + import pkg_resources from rwt import deps def test_entry_points(): """ Ensure entry points are visible after making packages visible """ with deps.on_sys_path('jaraco.mongodb'): eps = pkg_resources.iter_entry_points('pytest11') assert list(eps), "Entry points not found" class TestInstallCheck: def test_installed(self): assert deps.pkg_installed('rwt') def test_not_installed(self): assert not deps.pkg_installed('not_a_package') def test_installed_version(self): assert not deps.pkg_installed('rwt==0.0') def test_not_installed_args(self): args = [ '-i', 'https://devpi.net', '-r', 'requirements.txt', 'rwt', 'not_a_package', 'rwt==0.0', ] - expected = args.copy() + expected = copy.copy(args) expected.remove('rwt') filtered = deps.not_installed(args) assert list(filtered) == expected
Fix test failure on Python 2
## Code Before: import pkg_resources from rwt import deps def test_entry_points(): """ Ensure entry points are visible after making packages visible """ with deps.on_sys_path('jaraco.mongodb'): eps = pkg_resources.iter_entry_points('pytest11') assert list(eps), "Entry points not found" class TestInstallCheck: def test_installed(self): assert deps.pkg_installed('rwt') def test_not_installed(self): assert not deps.pkg_installed('not_a_package') def test_installed_version(self): assert not deps.pkg_installed('rwt==0.0') def test_not_installed_args(self): args = [ '-i', 'https://devpi.net', '-r', 'requirements.txt', 'rwt', 'not_a_package', 'rwt==0.0', ] expected = args.copy() expected.remove('rwt') filtered = deps.not_installed(args) assert list(filtered) == expected ## Instruction: Fix test failure on Python 2 ## Code After: import copy import pkg_resources from rwt import deps def test_entry_points(): """ Ensure entry points are visible after making packages visible """ with deps.on_sys_path('jaraco.mongodb'): eps = pkg_resources.iter_entry_points('pytest11') assert list(eps), "Entry points not found" class TestInstallCheck: def test_installed(self): assert deps.pkg_installed('rwt') def test_not_installed(self): assert not deps.pkg_installed('not_a_package') def test_installed_version(self): assert not deps.pkg_installed('rwt==0.0') def test_not_installed_args(self): args = [ '-i', 'https://devpi.net', '-r', 'requirements.txt', 'rwt', 'not_a_package', 'rwt==0.0', ] expected = copy.copy(args) expected.remove('rwt') filtered = deps.not_installed(args) assert list(filtered) == expected
+ import copy + import pkg_resources from rwt import deps def test_entry_points(): """ Ensure entry points are visible after making packages visible """ with deps.on_sys_path('jaraco.mongodb'): eps = pkg_resources.iter_entry_points('pytest11') assert list(eps), "Entry points not found" class TestInstallCheck: def test_installed(self): assert deps.pkg_installed('rwt') def test_not_installed(self): assert not deps.pkg_installed('not_a_package') def test_installed_version(self): assert not deps.pkg_installed('rwt==0.0') def test_not_installed_args(self): args = [ '-i', 'https://devpi.net', '-r', 'requirements.txt', 'rwt', 'not_a_package', 'rwt==0.0', ] - expected = args.copy() ? ^^^^ + expected = copy.copy(args) ? ^^^^ ++++ expected.remove('rwt') filtered = deps.not_installed(args) assert list(filtered) == expected
4468827795606ae57c5a7d62f5b2f08d93387f39
virustotal/server.py
virustotal/server.py
from contextlib import closing from sqlite3 import connect from bottle import template, route, run @route('/virustotal/<db>') def virus(db): with connect(db, timeout=10) as connection: with closing(connection.cursor()) as cursor: cursor.execute('SELECT detected, count(*) FROM virus GROUP BY detected ORDER BY detected') return template('virustotal', title=db, cursor=cursor, refresh=10) run(host='0.0.0.0')
from contextlib import closing from sqlite3 import connect from bottle import request, template, route, run @route('/virustotal/<db>') def virus(db): with connect(db, timeout=10) as connection: with closing(connection.cursor()) as cursor: cursor.execute('SELECT detected, count(*) FROM virus GROUP BY detected ORDER BY detected') return template('virustotal', title=db, cursor=cursor, refresh=request.query.refresh) run(host='0.0.0.0')
Use refresh only if required in parameters (?refresh=something)
Use refresh only if required in parameters (?refresh=something)
Python
mit
enricobacis/playscraper
from contextlib import closing from sqlite3 import connect - from bottle import template, route, run + from bottle import request, template, route, run @route('/virustotal/<db>') def virus(db): with connect(db, timeout=10) as connection: with closing(connection.cursor()) as cursor: cursor.execute('SELECT detected, count(*) FROM virus GROUP BY detected ORDER BY detected') - return template('virustotal', title=db, cursor=cursor, refresh=10) + return template('virustotal', title=db, cursor=cursor, refresh=request.query.refresh) run(host='0.0.0.0')
Use refresh only if required in parameters (?refresh=something)
## Code Before: from contextlib import closing from sqlite3 import connect from bottle import template, route, run @route('/virustotal/<db>') def virus(db): with connect(db, timeout=10) as connection: with closing(connection.cursor()) as cursor: cursor.execute('SELECT detected, count(*) FROM virus GROUP BY detected ORDER BY detected') return template('virustotal', title=db, cursor=cursor, refresh=10) run(host='0.0.0.0') ## Instruction: Use refresh only if required in parameters (?refresh=something) ## Code After: from contextlib import closing from sqlite3 import connect from bottle import request, template, route, run @route('/virustotal/<db>') def virus(db): with connect(db, timeout=10) as connection: with closing(connection.cursor()) as cursor: cursor.execute('SELECT detected, count(*) FROM virus GROUP BY detected ORDER BY detected') return template('virustotal', title=db, cursor=cursor, refresh=request.query.refresh) run(host='0.0.0.0')
from contextlib import closing from sqlite3 import connect - from bottle import template, route, run + from bottle import request, template, route, run ? +++++++++ @route('/virustotal/<db>') def virus(db): with connect(db, timeout=10) as connection: with closing(connection.cursor()) as cursor: cursor.execute('SELECT detected, count(*) FROM virus GROUP BY detected ORDER BY detected') - return template('virustotal', title=db, cursor=cursor, refresh=10) ? ^^ + return template('virustotal', title=db, cursor=cursor, refresh=request.query.refresh) ? ^^^^^^^^^^^^^^^^^^^^^ run(host='0.0.0.0')
2b933faaf2f9aba9158d56c49367e423ea1a2ea3
pelican/plugins/related_posts.py
pelican/plugins/related_posts.py
from pelican import signals """ Related posts plugin for Pelican ================================ Adds related_posts variable to article's context """ related_posts = [] def add_related_posts(generator, metadata): if 'tags' in metadata: for tag in metadata['tags']: #print tag for related_article in generator.tags[tag]: related_posts.append(related_article) if len(related_posts) < 1: return relation_score = dict( \ zip(set(related_posts), \ map(related_posts.count, \ set(related_posts)))) ranked_related = sorted(relation_score, key=relation_score.get) metadata["related_posts"] = ranked_related[:5] else: return def register(): signals.article_generate_context.connect(add_related_posts)
from pelican import signals """ Related posts plugin for Pelican ================================ Adds related_posts variable to article's context Settings -------- To enable, add from pelican.plugins import related_posts PLUGINS = [related_posts] to your settings.py. Usage ----- {% if article.related_posts %} <ul> {% for related_post in article.related_posts %} <li>{{ related_post }}</li> {% endfor %} </ul> {% endif %} """ related_posts = [] def add_related_posts(generator, metadata): if 'tags' in metadata: for tag in metadata['tags']: #print tag for related_article in generator.tags[tag]: related_posts.append(related_article) if len(related_posts) < 1: return relation_score = dict( \ zip(set(related_posts), \ map(related_posts.count, \ set(related_posts)))) ranked_related = sorted(relation_score, key=relation_score.get) metadata["related_posts"] = ranked_related[:5] else: return def register(): signals.article_generate_context.connect(add_related_posts)
Add usage and intallation instructions
Add usage and intallation instructions
Python
agpl-3.0
alexras/pelican,HyperGroups/pelican,jvehent/pelican,11craft/pelican,51itclub/pelican,number5/pelican,avaris/pelican,treyhunner/pelican,number5/pelican,deved69/pelican-1,lazycoder-ru/pelican,Polyconseil/pelican,simonjj/pelican,ehashman/pelican,koobs/pelican,florianjacob/pelican,joetboole/pelican,sunzhongwei/pelican,GiovanniMoretti/pelican,Summonee/pelican,Scheirle/pelican,rbarraud/pelican,jimperio/pelican,karlcow/pelican,ls2uper/pelican,lazycoder-ru/pelican,janaurka/git-debug-presentiation,catdog2/pelican,GiovanniMoretti/pelican,JeremyMorgan/pelican,zackw/pelican,levanhien8/pelican,levanhien8/pelican,jimperio/pelican,ehashman/pelican,liyonghelpme/myBlog,liyonghelpme/myBlog,goerz/pelican,btnpushnmunky/pelican,abrahamvarricatt/pelican,crmackay/pelican,iurisilvio/pelican,arty-name/pelican,deanishe/pelican,TC01/pelican,goerz/pelican,UdeskDeveloper/pelican,Scheirle/pelican,alexras/pelican,janaurka/git-debug-presentiation,justinmayer/pelican,farseerfc/pelican,iKevinY/pelican,jimperio/pelican,treyhunner/pelican,JeremyMorgan/pelican,karlcow/pelican,abrahamvarricatt/pelican,51itclub/pelican,11craft/pelican,talha131/pelican,Rogdham/pelican,eevee/pelican,joetboole/pelican,number5/pelican,catdog2/pelican,btnpushnmunky/pelican,lucasplus/pelican,farseerfc/pelican,HyperGroups/pelican,gymglish/pelican,11craft/pelican,deved69/pelican-1,simonjj/pelican,florianjacob/pelican,jvehent/pelican,Scheirle/pelican,getpelican/pelican,Polyconseil/pelican,kennethlyn/pelican,karlcow/pelican,eevee/pelican,douglaskastle/pelican,ls2uper/pelican,eevee/pelican,lucasplus/pelican,jo-tham/pelican,garbas/pelican,Rogdham/pelican,levanhien8/pelican,joetboole/pelican,iurisilvio/pelican,0xMF/pelican,garbas/pelican,Rogdham/pelican,florianjacob/pelican,koobs/pelican,GiovanniMoretti/pelican,simonjj/pelican,ls2uper/pelican,kernc/pelican,kernc/pelican,treyhunner/pelican,ionelmc/pelican,iKevinY/pelican,rbarraud/pelican,JeremyMorgan/pelican,HyperGroups/pelican,douglaskastle/pelican,abrahamvarricatt/pelican,crmackay/pelican,crmackay/pelican,kernc/pelican,deanishe/pelican,zackw/pelican,ehashman/pelican,lazycoder-ru/pelican,sunzhongwei/pelican,janaurka/git-debug-presentiation,talha131/pelican,rbarraud/pelican,UdeskDeveloper/pelican,deved69/pelican-1,kennethlyn/pelican,51itclub/pelican,avaris/pelican,alexras/pelican,fbs/pelican,iurisilvio/pelican,TC01/pelican,douglaskastle/pelican,TC01/pelican,kennethlyn/pelican,Summonee/pelican,ingwinlu/pelican,Summonee/pelican,sunzhongwei/pelican,jo-tham/pelican,sunzhongwei/pelican,gymglish/pelican,koobs/pelican,zackw/pelican,deanishe/pelican,liyonghelpme/myBlog,catdog2/pelican,liyonghelpme/myBlog,getpelican/pelican,garbas/pelican,UdeskDeveloper/pelican,ingwinlu/pelican,btnpushnmunky/pelican,lucasplus/pelican,Natim/pelican,gymglish/pelican,liyonghelpme/myBlog,jvehent/pelican,goerz/pelican
from pelican import signals """ Related posts plugin for Pelican ================================ Adds related_posts variable to article's context + + Settings + -------- + To enable, add + + from pelican.plugins import related_posts + PLUGINS = [related_posts] + + to your settings.py. + + Usage + ----- + {% if article.related_posts %} + <ul> + {% for related_post in article.related_posts %} + <li>{{ related_post }}</li> + {% endfor %} + </ul> + {% endif %} + + """ + related_posts = [] def add_related_posts(generator, metadata): if 'tags' in metadata: for tag in metadata['tags']: #print tag for related_article in generator.tags[tag]: related_posts.append(related_article) if len(related_posts) < 1: return relation_score = dict( \ zip(set(related_posts), \ map(related_posts.count, \ set(related_posts)))) ranked_related = sorted(relation_score, key=relation_score.get) metadata["related_posts"] = ranked_related[:5] else: return def register(): signals.article_generate_context.connect(add_related_posts)
Add usage and intallation instructions
## Code Before: from pelican import signals """ Related posts plugin for Pelican ================================ Adds related_posts variable to article's context """ related_posts = [] def add_related_posts(generator, metadata): if 'tags' in metadata: for tag in metadata['tags']: #print tag for related_article in generator.tags[tag]: related_posts.append(related_article) if len(related_posts) < 1: return relation_score = dict( \ zip(set(related_posts), \ map(related_posts.count, \ set(related_posts)))) ranked_related = sorted(relation_score, key=relation_score.get) metadata["related_posts"] = ranked_related[:5] else: return def register(): signals.article_generate_context.connect(add_related_posts) ## Instruction: Add usage and intallation instructions ## Code After: from pelican import signals """ Related posts plugin for Pelican ================================ Adds related_posts variable to article's context Settings -------- To enable, add from pelican.plugins import related_posts PLUGINS = [related_posts] to your settings.py. Usage ----- {% if article.related_posts %} <ul> {% for related_post in article.related_posts %} <li>{{ related_post }}</li> {% endfor %} </ul> {% endif %} """ related_posts = [] def add_related_posts(generator, metadata): if 'tags' in metadata: for tag in metadata['tags']: #print tag for related_article in generator.tags[tag]: related_posts.append(related_article) if len(related_posts) < 1: return relation_score = dict( \ zip(set(related_posts), \ map(related_posts.count, \ set(related_posts)))) ranked_related = sorted(relation_score, key=relation_score.get) metadata["related_posts"] = ranked_related[:5] else: return def register(): signals.article_generate_context.connect(add_related_posts)
from pelican import signals """ Related posts plugin for Pelican ================================ Adds related_posts variable to article's context + + Settings + -------- + To enable, add + + from pelican.plugins import related_posts + PLUGINS = [related_posts] + + to your settings.py. + + Usage + ----- + {% if article.related_posts %} + <ul> + {% for related_post in article.related_posts %} + <li>{{ related_post }}</li> + {% endfor %} + </ul> + {% endif %} + + """ + related_posts = [] def add_related_posts(generator, metadata): if 'tags' in metadata: for tag in metadata['tags']: #print tag for related_article in generator.tags[tag]: related_posts.append(related_article) if len(related_posts) < 1: return relation_score = dict( \ zip(set(related_posts), \ map(related_posts.count, \ set(related_posts)))) ranked_related = sorted(relation_score, key=relation_score.get) metadata["related_posts"] = ranked_related[:5] else: return def register(): signals.article_generate_context.connect(add_related_posts)
f6c2f222db0f529d3f5906d5de7a7541e835ea77
litecord/api/guilds.py
litecord/api/guilds.py
''' guilds.py - All handlers under /guilds/* ''' import json import logging from ..utils import _err, _json, strip_user_data log = logging.getLogger(__name__) class GuildsEndpoint: def __init__(self, server): self.server = server async def h_post_guilds(self, request): pass
''' guilds.py - All handlers under /guilds/* ''' import json import logging from ..utils import _err, _json, strip_user_data log = logging.getLogger(__name__) class GuildsEndpoint: def __init__(self, server): self.server = server async def h_post_guilds(self, request): pass async def h_guilds(self, request): ''' GuildsEndpoint.h_guilds Handle `GET /guilds/{guild_id}` ''' _error = await self.server.check_request(request) _error_json = json.loads(_error.text) if _error_json['code'] == 0: return _error guild_id = request.match_info['guild_id'] guild = self.server.guild_man.get_guild(guild_id) if guild is None: return _err('404: Not Found') return _json(guild.as_json) async def h_get_guild_channels(self, request): ''' GuildsEndpoint.h_get_guild_channels `GET /guilds/{guild_id}/channels` ''' _error = await self.server.check_request(request) _error_json = json.loads(_error.text) if _error_json['code'] == 0: return _error guild_id = request.match_info['guild_id'] return _json('Not Implemented')
Add some dummy routes in GuildsEndpoint
Add some dummy routes in GuildsEndpoint
Python
mit
nullpixel/litecord,nullpixel/litecord
''' guilds.py - All handlers under /guilds/* ''' import json import logging from ..utils import _err, _json, strip_user_data log = logging.getLogger(__name__) class GuildsEndpoint: def __init__(self, server): self.server = server async def h_post_guilds(self, request): pass + async def h_guilds(self, request): + ''' + GuildsEndpoint.h_guilds + + Handle `GET /guilds/{guild_id}` + ''' + _error = await self.server.check_request(request) + _error_json = json.loads(_error.text) + if _error_json['code'] == 0: + return _error + + guild_id = request.match_info['guild_id'] + + guild = self.server.guild_man.get_guild(guild_id) + if guild is None: + return _err('404: Not Found') + + return _json(guild.as_json) + + async def h_get_guild_channels(self, request): + ''' + GuildsEndpoint.h_get_guild_channels + + `GET /guilds/{guild_id}/channels` + ''' + _error = await self.server.check_request(request) + _error_json = json.loads(_error.text) + if _error_json['code'] == 0: + return _error + + guild_id = request.match_info['guild_id'] + + return _json('Not Implemented') +
Add some dummy routes in GuildsEndpoint
## Code Before: ''' guilds.py - All handlers under /guilds/* ''' import json import logging from ..utils import _err, _json, strip_user_data log = logging.getLogger(__name__) class GuildsEndpoint: def __init__(self, server): self.server = server async def h_post_guilds(self, request): pass ## Instruction: Add some dummy routes in GuildsEndpoint ## Code After: ''' guilds.py - All handlers under /guilds/* ''' import json import logging from ..utils import _err, _json, strip_user_data log = logging.getLogger(__name__) class GuildsEndpoint: def __init__(self, server): self.server = server async def h_post_guilds(self, request): pass async def h_guilds(self, request): ''' GuildsEndpoint.h_guilds Handle `GET /guilds/{guild_id}` ''' _error = await self.server.check_request(request) _error_json = json.loads(_error.text) if _error_json['code'] == 0: return _error guild_id = request.match_info['guild_id'] guild = self.server.guild_man.get_guild(guild_id) if guild is None: return _err('404: Not Found') return _json(guild.as_json) async def h_get_guild_channels(self, request): ''' GuildsEndpoint.h_get_guild_channels `GET /guilds/{guild_id}/channels` ''' _error = await self.server.check_request(request) _error_json = json.loads(_error.text) if _error_json['code'] == 0: return _error guild_id = request.match_info['guild_id'] return _json('Not Implemented')
''' guilds.py - All handlers under /guilds/* ''' import json import logging from ..utils import _err, _json, strip_user_data log = logging.getLogger(__name__) class GuildsEndpoint: def __init__(self, server): self.server = server async def h_post_guilds(self, request): pass + + async def h_guilds(self, request): + ''' + GuildsEndpoint.h_guilds + + Handle `GET /guilds/{guild_id}` + ''' + _error = await self.server.check_request(request) + _error_json = json.loads(_error.text) + if _error_json['code'] == 0: + return _error + + guild_id = request.match_info['guild_id'] + + guild = self.server.guild_man.get_guild(guild_id) + if guild is None: + return _err('404: Not Found') + + return _json(guild.as_json) + + async def h_get_guild_channels(self, request): + ''' + GuildsEndpoint.h_get_guild_channels + + `GET /guilds/{guild_id}/channels` + ''' + _error = await self.server.check_request(request) + _error_json = json.loads(_error.text) + if _error_json['code'] == 0: + return _error + + guild_id = request.match_info['guild_id'] + + return _json('Not Implemented')
0519824c537a96474e0501e1ac45f7a626391a31
tests/test_model_object.py
tests/test_model_object.py
from marathon.models.base import MarathonObject import unittest class MarathonObjectTest(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonObject defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonObjects are hashable, but in Python3 they're not, This test ensures that we are hashable in all versions of python """ obj = MarathonObject() collection = {} collection[obj] = True assert collection[obj]
from marathon.models.base import MarathonObject from marathon.models.base import MarathonResource import unittest class MarathonObjectTest(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonObject defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonObjects are hashable, but in Python3 they're not, This test ensures that we are hashable in all versions of python """ obj = MarathonObject() collection = {} collection[obj] = True assert collection[obj] class MarathonResourceHashable(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonResource defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonResources are hashable, but in Python3 they're not This test ensures that we are hashable in all versions of python """ obj = MarathonResource() collection = {} collection[obj] = True assert collection[obj]
Add regression test for MarathonResource
Add regression test for MarathonResource
Python
mit
thefactory/marathon-python,thefactory/marathon-python
from marathon.models.base import MarathonObject + from marathon.models.base import MarathonResource import unittest class MarathonObjectTest(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonObject defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonObjects are hashable, but in Python3 they're not, This test ensures that we are hashable in all versions of python """ obj = MarathonObject() collection = {} collection[obj] = True assert collection[obj] + + class MarathonResourceHashable(unittest.TestCase): + + def test_hashable(self): + """ + Regression test for issue #203 + + MarathonResource defined __eq__ but not __hash__, meaning that in + in Python2.7 MarathonResources are hashable, but in Python3 they're + not + + This test ensures that we are hashable in all versions of python + """ + obj = MarathonResource() + collection = {} + collection[obj] = True + assert collection[obj] +
Add regression test for MarathonResource
## Code Before: from marathon.models.base import MarathonObject import unittest class MarathonObjectTest(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonObject defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonObjects are hashable, but in Python3 they're not, This test ensures that we are hashable in all versions of python """ obj = MarathonObject() collection = {} collection[obj] = True assert collection[obj] ## Instruction: Add regression test for MarathonResource ## Code After: from marathon.models.base import MarathonObject from marathon.models.base import MarathonResource import unittest class MarathonObjectTest(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonObject defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonObjects are hashable, but in Python3 they're not, This test ensures that we are hashable in all versions of python """ obj = MarathonObject() collection = {} collection[obj] = True assert collection[obj] class MarathonResourceHashable(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonResource defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonResources are hashable, but in Python3 they're not This test ensures that we are hashable in all versions of python """ obj = MarathonResource() collection = {} collection[obj] = True assert collection[obj]
from marathon.models.base import MarathonObject + from marathon.models.base import MarathonResource import unittest class MarathonObjectTest(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonObject defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonObjects are hashable, but in Python3 they're not, This test ensures that we are hashable in all versions of python """ obj = MarathonObject() collection = {} collection[obj] = True assert collection[obj] + + + class MarathonResourceHashable(unittest.TestCase): + + def test_hashable(self): + """ + Regression test for issue #203 + + MarathonResource defined __eq__ but not __hash__, meaning that in + in Python2.7 MarathonResources are hashable, but in Python3 they're + not + + This test ensures that we are hashable in all versions of python + """ + obj = MarathonResource() + collection = {} + collection[obj] = True + assert collection[obj]
182f070c69e59907eeda3c261d833a492af46967
rojak-database/generate_media_data.py
rojak-database/generate_media_data.py
import MySQLdb as mysql from faker import Factory # Open database connection db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database') # Create new db cursor cursor = db.cursor() sql = ''' INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`, `slogan`) VALUES ('{}', '{}', '{}', '{}', '{}'); ''' MAX_MEDIA=100 fake = Factory.create('it_IT') for i in xrange(MAX_MEDIA): # Generate random data for the media media_name = fake.name() + ' Media ' + str(i) website_name = media_name.lower().replace(' ', '') website_name = website_name.replace("'", '') website_url = 'https://{}.com'.format(website_name) cat_txt = website_name cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt) logo_url = cat_img facebookpage_url = 'https://facebook.com/{}'.format(website_name) slogan = ' '.join(fake.text().split()[:5]) # Parse the SQL command insert_sql = sql.format(media_name, website_url, logo_url, facebookpage_url, slogan) # insert to the database try: cursor.execute(insert_sql) db.commit() except mysql.Error as err: print("Something went wrong: {}".format(err)) db.rollback() # Close the DB connection db.close()
import MySQLdb as mysql from faker import Factory # Open database connection db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database') # Create new db cursor cursor = db.cursor() sql = ''' INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`, `slogan`) VALUES ('{}', '{}', '{}', '{}', '{}'); ''' MAX_MEDIA=100 fake = Factory.create() for i in xrange(MAX_MEDIA): # Generate random data for the media media_name = fake.name() + ' Media ' + str(i) website_name = media_name.lower().replace(' ', '') website_url = 'https://{}.com'.format(website_name) cat_txt = website_name cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt) logo_url = cat_img facebookpage_url = 'https://facebook.com/{}'.format(website_name) slogan = ' '.join(fake.text().split()[:5]) # Parse the SQL command insert_sql = sql.format(media_name, website_url, logo_url, facebookpage_url, slogan) # insert to the database try: cursor.execute(insert_sql) db.commit() except mysql.Error as err: print("Something went wrong: {}".format(err)) db.rollback() # Close the DB connection db.close()
Update the default language for the media generator
Update the default language for the media generator
Python
bsd-3-clause
CodeRiderz/rojak,bobbypriambodo/rojak,reinarduswindy/rojak,CodeRiderz/rojak,bobbypriambodo/rojak,reinarduswindy/rojak,bobbypriambodo/rojak,reinarduswindy/rojak,CodeRiderz/rojak,pyk/rojak,pyk/rojak,bobbypriambodo/rojak,pyk/rojak,bobbypriambodo/rojak,rawgni/rojak,bobbypriambodo/rojak,CodeRiderz/rojak,pyk/rojak,pyk/rojak,CodeRiderz/rojak,rawgni/rojak,pyk/rojak,rawgni/rojak,rawgni/rojak,rawgni/rojak,pyk/rojak,reinarduswindy/rojak,reinarduswindy/rojak,CodeRiderz/rojak,CodeRiderz/rojak,rawgni/rojak,rawgni/rojak,reinarduswindy/rojak,reinarduswindy/rojak,bobbypriambodo/rojak
import MySQLdb as mysql from faker import Factory # Open database connection db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database') # Create new db cursor cursor = db.cursor() sql = ''' INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`, `slogan`) VALUES ('{}', '{}', '{}', '{}', '{}'); ''' MAX_MEDIA=100 - fake = Factory.create('it_IT') + fake = Factory.create() for i in xrange(MAX_MEDIA): # Generate random data for the media media_name = fake.name() + ' Media ' + str(i) website_name = media_name.lower().replace(' ', '') - website_name = website_name.replace("'", '') website_url = 'https://{}.com'.format(website_name) cat_txt = website_name cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt) logo_url = cat_img facebookpage_url = 'https://facebook.com/{}'.format(website_name) slogan = ' '.join(fake.text().split()[:5]) # Parse the SQL command insert_sql = sql.format(media_name, website_url, logo_url, facebookpage_url, slogan) # insert to the database try: cursor.execute(insert_sql) db.commit() except mysql.Error as err: print("Something went wrong: {}".format(err)) db.rollback() # Close the DB connection db.close()
Update the default language for the media generator
## Code Before: import MySQLdb as mysql from faker import Factory # Open database connection db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database') # Create new db cursor cursor = db.cursor() sql = ''' INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`, `slogan`) VALUES ('{}', '{}', '{}', '{}', '{}'); ''' MAX_MEDIA=100 fake = Factory.create('it_IT') for i in xrange(MAX_MEDIA): # Generate random data for the media media_name = fake.name() + ' Media ' + str(i) website_name = media_name.lower().replace(' ', '') website_name = website_name.replace("'", '') website_url = 'https://{}.com'.format(website_name) cat_txt = website_name cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt) logo_url = cat_img facebookpage_url = 'https://facebook.com/{}'.format(website_name) slogan = ' '.join(fake.text().split()[:5]) # Parse the SQL command insert_sql = sql.format(media_name, website_url, logo_url, facebookpage_url, slogan) # insert to the database try: cursor.execute(insert_sql) db.commit() except mysql.Error as err: print("Something went wrong: {}".format(err)) db.rollback() # Close the DB connection db.close() ## Instruction: Update the default language for the media generator ## Code After: import MySQLdb as mysql from faker import Factory # Open database connection db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database') # Create new db cursor cursor = db.cursor() sql = ''' INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`, `slogan`) VALUES ('{}', '{}', '{}', '{}', '{}'); ''' MAX_MEDIA=100 fake = Factory.create() for i in xrange(MAX_MEDIA): # Generate random data for the media media_name = fake.name() + ' Media ' + str(i) website_name = media_name.lower().replace(' ', '') website_url = 'https://{}.com'.format(website_name) cat_txt = website_name cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt) logo_url = cat_img facebookpage_url = 'https://facebook.com/{}'.format(website_name) slogan = ' '.join(fake.text().split()[:5]) # Parse the SQL command insert_sql = sql.format(media_name, website_url, logo_url, facebookpage_url, slogan) # insert to the database try: cursor.execute(insert_sql) db.commit() except mysql.Error as err: print("Something went wrong: {}".format(err)) db.rollback() # Close the DB connection db.close()
import MySQLdb as mysql from faker import Factory # Open database connection db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database') # Create new db cursor cursor = db.cursor() sql = ''' INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`, `slogan`) VALUES ('{}', '{}', '{}', '{}', '{}'); ''' MAX_MEDIA=100 - fake = Factory.create('it_IT') ? ------- + fake = Factory.create() for i in xrange(MAX_MEDIA): # Generate random data for the media media_name = fake.name() + ' Media ' + str(i) website_name = media_name.lower().replace(' ', '') - website_name = website_name.replace("'", '') website_url = 'https://{}.com'.format(website_name) cat_txt = website_name cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt) logo_url = cat_img facebookpage_url = 'https://facebook.com/{}'.format(website_name) slogan = ' '.join(fake.text().split()[:5]) # Parse the SQL command insert_sql = sql.format(media_name, website_url, logo_url, facebookpage_url, slogan) # insert to the database try: cursor.execute(insert_sql) db.commit() except mysql.Error as err: print("Something went wrong: {}".format(err)) db.rollback() # Close the DB connection db.close()
f01921e6e2fbac76dc41e354b84f970b1591193d
nsone/rest/monitoring.py
nsone/rest/monitoring.py
from . import resource class Monitors(resource.BaseResource): ROOT = 'monitoring/jobs' PASSTHRU_FIELDS = ['name', 'config'] def list(self, callback=None, errback=None): return self._make_request('GET', '%s' % (self.ROOT), callback=callback, errback=errback) def update(self, jobid, body, callback=None, errback=None, **kwargs): self._buildStdBody(body, kwargs) return self._make_request('POST', '%s/%s' % (self.ROOT, jobid), body=body, callback=callback, errback=errback) def create(self,body, callback=None, errback=None): return self._make_request('PUT', '%s' % (self.ROOT), body=body, callback=callback, errback=errback) def retrieve(self, jobid, callback=None, errback=None): return self._make_request('GET', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback)
from . import resource class Monitors(resource.BaseResource): ROOT = 'monitoring/jobs' PASSTHRU_FIELDS = ['name', 'config'] def list(self, callback=None, errback=None): return self._make_request('GET', '%s' % (self.ROOT), callback=callback, errback=errback) def update(self, jobid, body, callback=None, errback=None, **kwargs): self._buildStdBody(body, kwargs) return self._make_request('POST', '%s/%s' % (self.ROOT, jobid), body=body, callback=callback, errback=errback) def create(self,body, callback=None, errback=None): return self._make_request('PUT', '%s' % (self.ROOT), body=body, callback=callback, errback=errback) def retrieve(self, jobid, callback=None, errback=None): return self._make_request('GET', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback) def delete(self, jobid, callback=None, errback=None): return self._make_request('DELETE', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback)
Add support for monitor deletion
Add support for monitor deletion
Python
mit
nsone/nsone-python,ns1/nsone-python
from . import resource class Monitors(resource.BaseResource): ROOT = 'monitoring/jobs' PASSTHRU_FIELDS = ['name', 'config'] def list(self, callback=None, errback=None): return self._make_request('GET', '%s' % (self.ROOT), callback=callback, errback=errback) def update(self, jobid, body, callback=None, errback=None, **kwargs): self._buildStdBody(body, kwargs) return self._make_request('POST', '%s/%s' % (self.ROOT, jobid), body=body, callback=callback, - errback=errback) + errback=errback) def create(self,body, callback=None, errback=None): return self._make_request('PUT', '%s' % (self.ROOT), body=body, callback=callback, errback=errback) def retrieve(self, jobid, callback=None, errback=None): return self._make_request('GET', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback) + def delete(self, jobid, callback=None, errback=None): + return self._make_request('DELETE', '%s/%s' % (self.ROOT, jobid), + callback=callback, + errback=errback) +
Add support for monitor deletion
## Code Before: from . import resource class Monitors(resource.BaseResource): ROOT = 'monitoring/jobs' PASSTHRU_FIELDS = ['name', 'config'] def list(self, callback=None, errback=None): return self._make_request('GET', '%s' % (self.ROOT), callback=callback, errback=errback) def update(self, jobid, body, callback=None, errback=None, **kwargs): self._buildStdBody(body, kwargs) return self._make_request('POST', '%s/%s' % (self.ROOT, jobid), body=body, callback=callback, errback=errback) def create(self,body, callback=None, errback=None): return self._make_request('PUT', '%s' % (self.ROOT), body=body, callback=callback, errback=errback) def retrieve(self, jobid, callback=None, errback=None): return self._make_request('GET', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback) ## Instruction: Add support for monitor deletion ## Code After: from . import resource class Monitors(resource.BaseResource): ROOT = 'monitoring/jobs' PASSTHRU_FIELDS = ['name', 'config'] def list(self, callback=None, errback=None): return self._make_request('GET', '%s' % (self.ROOT), callback=callback, errback=errback) def update(self, jobid, body, callback=None, errback=None, **kwargs): self._buildStdBody(body, kwargs) return self._make_request('POST', '%s/%s' % (self.ROOT, jobid), body=body, callback=callback, errback=errback) def create(self,body, callback=None, errback=None): return self._make_request('PUT', '%s' % (self.ROOT), body=body, callback=callback, errback=errback) def retrieve(self, jobid, callback=None, errback=None): return self._make_request('GET', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback) def delete(self, jobid, callback=None, errback=None): return self._make_request('DELETE', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback)
from . import resource class Monitors(resource.BaseResource): ROOT = 'monitoring/jobs' PASSTHRU_FIELDS = ['name', 'config'] def list(self, callback=None, errback=None): return self._make_request('GET', '%s' % (self.ROOT), callback=callback, errback=errback) def update(self, jobid, body, callback=None, errback=None, **kwargs): self._buildStdBody(body, kwargs) return self._make_request('POST', '%s/%s' % (self.ROOT, jobid), body=body, callback=callback, - errback=errback) + errback=errback) ? + def create(self,body, callback=None, errback=None): return self._make_request('PUT', '%s' % (self.ROOT), body=body, callback=callback, errback=errback) def retrieve(self, jobid, callback=None, errback=None): return self._make_request('GET', '%s/%s' % (self.ROOT, jobid), callback=callback, errback=errback) + + def delete(self, jobid, callback=None, errback=None): + return self._make_request('DELETE', '%s/%s' % (self.ROOT, jobid), + callback=callback, + errback=errback)
f4c5bb0a77108f340533736c52f01c861146a6b6
byceps/util/money.py
byceps/util/money.py
from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True, monetary=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
Remove usage of `monetary` keyword argument again as it is not available on Python 3.6
Remove usage of `monetary` keyword argument again as it is not available on Python 3.6
Python
bsd-3-clause
m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps
from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) - formatted_number = locale.format_string('%.2f', quantized, grouping=True, + formatted_number = locale.format_string('%.2f', quantized, grouping=True) - monetary=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
Remove usage of `monetary` keyword argument again as it is not available on Python 3.6
## Code Before: from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True, monetary=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES) ## Instruction: Remove usage of `monetary` keyword argument again as it is not available on Python 3.6 ## Code After: from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) formatted_number = locale.format_string('%.2f', quantized, grouping=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
from decimal import Decimal import locale TWO_PLACES = Decimal('.00') def format_euro_amount(x: Decimal) -> str: """Return a textual representation with two decimal places, locale-specific decimal point and thousands separators, and the Euro symbol. """ quantized = to_two_places(x) - formatted_number = locale.format_string('%.2f', quantized, grouping=True, ? ^ + formatted_number = locale.format_string('%.2f', quantized, grouping=True) ? ^ - monetary=True) return f'{formatted_number} €' def to_two_places(x: Decimal) -> Decimal: """Quantize to two decimal places.""" return x.quantize(TWO_PLACES)
78d36a68e0d460f3ead713a82c7d23faf7e73b9b
Instanssi/tickets/views.py
Instanssi/tickets/views.py
from datetime import datetime from django.conf import settings from django.http import HttpResponse, Http404 from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from Instanssi.tickets.models import Ticket from Instanssi.store.models import StoreTransaction # Logging related import logging logger = logging.getLogger(__name__) # Shows information about a single ticket def ticket(request, ticket_key): # Find ticket ticket = get_object_or_404(Ticket, key=ticket_key) # Render ticket return render_to_response('tickets/ticket.html', { 'ticket': ticket, }, context_instance=RequestContext(request)) # Lists all tickets def tickets(request, transaction_key): # Get transaction transaction = get_object_or_404(StoreTransaction, key=transaction_key) # Get all tickets by this transaction tickets = Ticket.objects.filter(transaction=transaction) # Render tickets return render_to_response('tickets/tickets.html', { 'transaction': transaction, 'tickets': tickets, }, context_instance=RequestContext(request))
from datetime import datetime from django.conf import settings from django.http import HttpResponse, Http404 from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from Instanssi.tickets.models import Ticket from Instanssi.store.models import StoreTransaction # Logging related import logging logger = logging.getLogger(__name__) # Shows information about a single ticket def ticket(request, ticket_key): # Find ticket ticket = get_object_or_404(Ticket, key=ticket_key) # Render ticket return render_to_response('tickets/ticket.html', { 'ticket': ticket, }, context_instance=RequestContext(request)) # Lists all tickets def tickets(request, transaction_key): # Get transaction transaction = get_object_or_404(StoreTransaction, key=transaction_key) if not transaction.paid: raise Http404 # Get all tickets by this transaction tickets = Ticket.objects.filter(transaction=transaction) # Render tickets return render_to_response('tickets/tickets.html', { 'transaction': transaction, 'tickets': tickets, }, context_instance=RequestContext(request))
Make sure ticket is paid before it can be viewed
tickets: Make sure ticket is paid before it can be viewed
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
from datetime import datetime from django.conf import settings from django.http import HttpResponse, Http404 from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from Instanssi.tickets.models import Ticket from Instanssi.store.models import StoreTransaction # Logging related import logging logger = logging.getLogger(__name__) # Shows information about a single ticket def ticket(request, ticket_key): # Find ticket ticket = get_object_or_404(Ticket, key=ticket_key) # Render ticket return render_to_response('tickets/ticket.html', { 'ticket': ticket, }, context_instance=RequestContext(request)) # Lists all tickets def tickets(request, transaction_key): # Get transaction transaction = get_object_or_404(StoreTransaction, key=transaction_key) + if not transaction.paid: + raise Http404 # Get all tickets by this transaction tickets = Ticket.objects.filter(transaction=transaction) # Render tickets return render_to_response('tickets/tickets.html', { 'transaction': transaction, 'tickets': tickets, }, context_instance=RequestContext(request)) +
Make sure ticket is paid before it can be viewed
## Code Before: from datetime import datetime from django.conf import settings from django.http import HttpResponse, Http404 from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from Instanssi.tickets.models import Ticket from Instanssi.store.models import StoreTransaction # Logging related import logging logger = logging.getLogger(__name__) # Shows information about a single ticket def ticket(request, ticket_key): # Find ticket ticket = get_object_or_404(Ticket, key=ticket_key) # Render ticket return render_to_response('tickets/ticket.html', { 'ticket': ticket, }, context_instance=RequestContext(request)) # Lists all tickets def tickets(request, transaction_key): # Get transaction transaction = get_object_or_404(StoreTransaction, key=transaction_key) # Get all tickets by this transaction tickets = Ticket.objects.filter(transaction=transaction) # Render tickets return render_to_response('tickets/tickets.html', { 'transaction': transaction, 'tickets': tickets, }, context_instance=RequestContext(request)) ## Instruction: Make sure ticket is paid before it can be viewed ## Code After: from datetime import datetime from django.conf import settings from django.http import HttpResponse, Http404 from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from Instanssi.tickets.models import Ticket from Instanssi.store.models import StoreTransaction # Logging related import logging logger = logging.getLogger(__name__) # Shows information about a single ticket def ticket(request, ticket_key): # Find ticket ticket = get_object_or_404(Ticket, key=ticket_key) # Render ticket return render_to_response('tickets/ticket.html', { 'ticket': ticket, }, context_instance=RequestContext(request)) # Lists all tickets def tickets(request, transaction_key): # Get transaction transaction = get_object_or_404(StoreTransaction, key=transaction_key) if not transaction.paid: raise Http404 # Get all tickets by this transaction tickets = Ticket.objects.filter(transaction=transaction) # Render tickets return render_to_response('tickets/tickets.html', { 'transaction': transaction, 'tickets': tickets, }, context_instance=RequestContext(request))
from datetime import datetime from django.conf import settings from django.http import HttpResponse, Http404 from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404 from Instanssi.tickets.models import Ticket from Instanssi.store.models import StoreTransaction # Logging related import logging logger = logging.getLogger(__name__) # Shows information about a single ticket def ticket(request, ticket_key): # Find ticket ticket = get_object_or_404(Ticket, key=ticket_key) # Render ticket return render_to_response('tickets/ticket.html', { 'ticket': ticket, }, context_instance=RequestContext(request)) # Lists all tickets def tickets(request, transaction_key): # Get transaction transaction = get_object_or_404(StoreTransaction, key=transaction_key) + if not transaction.paid: + raise Http404 # Get all tickets by this transaction tickets = Ticket.objects.filter(transaction=transaction) # Render tickets return render_to_response('tickets/tickets.html', { 'transaction': transaction, 'tickets': tickets, }, context_instance=RequestContext(request))
9f5e61bf821823c14f6a0640bd334c8732d41296
ipkg/files/backends/filesystem.py
ipkg/files/backends/filesystem.py
try: from urlparse import urlparse except ImportError: # Python 3 from urllib.parse import urlparse from . import BaseFile, BackendException class LocalFileException(BackendException): """An error occurred while accessing a local file.""" class LocalFile(BaseFile): """A file on the local filesystem. """ def __init__(self, *args, **kw): super(LocalFile, self).__init__(*args, **kw) filepath = urlparse(self.name).path self.__file = open(filepath) def seek(self, *args): self.__file.seek(*args) def tell(self): return self.__file.tell() def read(self, *args): return self.__file.read(*args)
import os try: from urlparse import urlparse except ImportError: # Python 3 from urllib.parse import urlparse from . import BaseFile, BackendException class LocalFileException(BackendException): """An error occurred while accessing a local file.""" class LocalFile(BaseFile): """A file on the local filesystem. """ def __init__(self, *args, **kw): super(LocalFile, self).__init__(*args, **kw) filepath = urlparse(self.name).path if os.path.isfile(filepath): self.__file = open(filepath) else: raise LocalFileException('Not a file: %s' % filepath) def seek(self, *args): self.__file.seek(*args) def tell(self): return self.__file.tell() def read(self, *args): return self.__file.read(*args)
Check if its a file
Check if its a file
Python
mit
pmuller/ipkg
+ import os + try: from urlparse import urlparse except ImportError: # Python 3 from urllib.parse import urlparse from . import BaseFile, BackendException class LocalFileException(BackendException): """An error occurred while accessing a local file.""" class LocalFile(BaseFile): """A file on the local filesystem. """ def __init__(self, *args, **kw): super(LocalFile, self).__init__(*args, **kw) filepath = urlparse(self.name).path + if os.path.isfile(filepath): - self.__file = open(filepath) + self.__file = open(filepath) + else: + raise LocalFileException('Not a file: %s' % filepath) def seek(self, *args): self.__file.seek(*args) def tell(self): return self.__file.tell() def read(self, *args): return self.__file.read(*args)
Check if its a file
## Code Before: try: from urlparse import urlparse except ImportError: # Python 3 from urllib.parse import urlparse from . import BaseFile, BackendException class LocalFileException(BackendException): """An error occurred while accessing a local file.""" class LocalFile(BaseFile): """A file on the local filesystem. """ def __init__(self, *args, **kw): super(LocalFile, self).__init__(*args, **kw) filepath = urlparse(self.name).path self.__file = open(filepath) def seek(self, *args): self.__file.seek(*args) def tell(self): return self.__file.tell() def read(self, *args): return self.__file.read(*args) ## Instruction: Check if its a file ## Code After: import os try: from urlparse import urlparse except ImportError: # Python 3 from urllib.parse import urlparse from . import BaseFile, BackendException class LocalFileException(BackendException): """An error occurred while accessing a local file.""" class LocalFile(BaseFile): """A file on the local filesystem. """ def __init__(self, *args, **kw): super(LocalFile, self).__init__(*args, **kw) filepath = urlparse(self.name).path if os.path.isfile(filepath): self.__file = open(filepath) else: raise LocalFileException('Not a file: %s' % filepath) def seek(self, *args): self.__file.seek(*args) def tell(self): return self.__file.tell() def read(self, *args): return self.__file.read(*args)
+ import os + try: from urlparse import urlparse except ImportError: # Python 3 from urllib.parse import urlparse from . import BaseFile, BackendException class LocalFileException(BackendException): """An error occurred while accessing a local file.""" class LocalFile(BaseFile): """A file on the local filesystem. """ def __init__(self, *args, **kw): super(LocalFile, self).__init__(*args, **kw) filepath = urlparse(self.name).path + if os.path.isfile(filepath): - self.__file = open(filepath) + self.__file = open(filepath) ? ++++ + else: + raise LocalFileException('Not a file: %s' % filepath) def seek(self, *args): self.__file.seek(*args) def tell(self): return self.__file.tell() def read(self, *args): return self.__file.read(*args)
c6d589859d621ac0eb2b4843a22cfe8e011bbeaf
braid/postgres.py
braid/postgres.py
from fabric.api import sudo, hide from braid import package from pipes import quote def install(): package.install(['postgresql-9.1', 'postgresql-server-dev-9.1']) def _runQuery(query): with hide('running', 'output'): return sudo('psql --no-align --no-readline --no-password --quiet ' '--tuples-only -c {}'.format(quote(query)), user='postgres', pty=False, combine_stderr=False) def _dbExists(name): res = _runQuery("select count(*) from pg_database " "where datname = '{}';".format(name)) return res == '1' def _userExists(name): res = _runQuery("select count(*) from pg_user " "where usename = '{}';".format(name)) return res == '1' def createUser(name): if not _userExists(name): sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False) def createDb(name, owner): if not _dbExists(name): sudo('createdb -O {} {}'.format(owner, name), user='postgres', pty=False) def grantRead(user, database): """ Grant read permissions to C{user} to all tables in C{database}. """ def grantReadWrite(user, database): """ Grant read and write permissions to C{user} to all tables in C{database}. """
from fabric.api import sudo, hide from braid import package from pipes import quote def install(): package.install(['postgresql-9.1', 'postgresql-server-dev-9.1']) def _runQuery(query, database=None): with hide('running', 'output'): database = '--dbname={}'.format(database) if database else '' return sudo('psql --no-align --no-readline --no-password --quiet ' '--tuples-only {} -c {}'.format(database, quote(query)), user='postgres', pty=False, combine_stderr=False) def _dbExists(name): res = _runQuery("select count(*) from pg_database " "where datname = '{}';".format(name)) return res == '1' def _userExists(name): res = _runQuery("select count(*) from pg_user " "where usename = '{}';".format(name)) return res == '1' def createUser(name): if not _userExists(name): sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False) def createDb(name, owner): if not _dbExists(name): sudo('createdb -O {} {}'.format(owner, name), user='postgres', pty=False) def grantRead(user, database): """ Grant read permissions to C{user} to all tables in C{database}. """ def grantReadWrite(user, database): """ Grant read and write permissions to C{user} to all tables in C{database}. """
Allow to specify a database when running a query
Allow to specify a database when running a query
Python
mit
alex/braid,alex/braid
from fabric.api import sudo, hide from braid import package from pipes import quote def install(): package.install(['postgresql-9.1', 'postgresql-server-dev-9.1']) - def _runQuery(query): + def _runQuery(query, database=None): with hide('running', 'output'): + database = '--dbname={}'.format(database) if database else '' return sudo('psql --no-align --no-readline --no-password --quiet ' - '--tuples-only -c {}'.format(quote(query)), + '--tuples-only {} -c {}'.format(database, quote(query)), user='postgres', pty=False, combine_stderr=False) def _dbExists(name): res = _runQuery("select count(*) from pg_database " "where datname = '{}';".format(name)) return res == '1' def _userExists(name): res = _runQuery("select count(*) from pg_user " "where usename = '{}';".format(name)) return res == '1' def createUser(name): if not _userExists(name): sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False) def createDb(name, owner): if not _dbExists(name): sudo('createdb -O {} {}'.format(owner, name), user='postgres', pty=False) def grantRead(user, database): """ Grant read permissions to C{user} to all tables in C{database}. """ def grantReadWrite(user, database): """ Grant read and write permissions to C{user} to all tables in C{database}. """
Allow to specify a database when running a query
## Code Before: from fabric.api import sudo, hide from braid import package from pipes import quote def install(): package.install(['postgresql-9.1', 'postgresql-server-dev-9.1']) def _runQuery(query): with hide('running', 'output'): return sudo('psql --no-align --no-readline --no-password --quiet ' '--tuples-only -c {}'.format(quote(query)), user='postgres', pty=False, combine_stderr=False) def _dbExists(name): res = _runQuery("select count(*) from pg_database " "where datname = '{}';".format(name)) return res == '1' def _userExists(name): res = _runQuery("select count(*) from pg_user " "where usename = '{}';".format(name)) return res == '1' def createUser(name): if not _userExists(name): sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False) def createDb(name, owner): if not _dbExists(name): sudo('createdb -O {} {}'.format(owner, name), user='postgres', pty=False) def grantRead(user, database): """ Grant read permissions to C{user} to all tables in C{database}. """ def grantReadWrite(user, database): """ Grant read and write permissions to C{user} to all tables in C{database}. """ ## Instruction: Allow to specify a database when running a query ## Code After: from fabric.api import sudo, hide from braid import package from pipes import quote def install(): package.install(['postgresql-9.1', 'postgresql-server-dev-9.1']) def _runQuery(query, database=None): with hide('running', 'output'): database = '--dbname={}'.format(database) if database else '' return sudo('psql --no-align --no-readline --no-password --quiet ' '--tuples-only {} -c {}'.format(database, quote(query)), user='postgres', pty=False, combine_stderr=False) def _dbExists(name): res = _runQuery("select count(*) from pg_database " "where datname = '{}';".format(name)) return res == '1' def _userExists(name): res = _runQuery("select count(*) from pg_user " "where usename = '{}';".format(name)) return res == '1' def createUser(name): if not _userExists(name): sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False) def createDb(name, owner): if not _dbExists(name): sudo('createdb -O {} {}'.format(owner, name), user='postgres', pty=False) def grantRead(user, database): """ Grant read permissions to C{user} to all tables in C{database}. """ def grantReadWrite(user, database): """ Grant read and write permissions to C{user} to all tables in C{database}. """
from fabric.api import sudo, hide from braid import package from pipes import quote def install(): package.install(['postgresql-9.1', 'postgresql-server-dev-9.1']) - def _runQuery(query): + def _runQuery(query, database=None): with hide('running', 'output'): + database = '--dbname={}'.format(database) if database else '' return sudo('psql --no-align --no-readline --no-password --quiet ' - '--tuples-only -c {}'.format(quote(query)), + '--tuples-only {} -c {}'.format(database, quote(query)), ? +++ ++++++++++ user='postgres', pty=False, combine_stderr=False) def _dbExists(name): res = _runQuery("select count(*) from pg_database " "where datname = '{}';".format(name)) return res == '1' def _userExists(name): res = _runQuery("select count(*) from pg_user " "where usename = '{}';".format(name)) return res == '1' def createUser(name): if not _userExists(name): sudo('createuser -D -R -S {}'.format(name), user='postgres', pty=False) def createDb(name, owner): if not _dbExists(name): sudo('createdb -O {} {}'.format(owner, name), user='postgres', pty=False) def grantRead(user, database): """ Grant read permissions to C{user} to all tables in C{database}. """ def grantReadWrite(user, database): """ Grant read and write permissions to C{user} to all tables in C{database}. """
084eac5735404edeed62cee4e2b429c8f4f2a7a5
app/dao/inbound_numbers_dao.py
app/dao/inbound_numbers_dao.py
from app import db from app.dao.dao_utils import transactional from app.models import InboundNumber def dao_get_inbound_numbers(): return InboundNumber.query.all() def dao_get_available_inbound_numbers(): return InboundNumber.query.filter(InboundNumber.active, InboundNumber.service_id.is_(None)).all() def dao_get_inbound_number_for_service(service_id): return InboundNumber.query.filter(InboundNumber.service_id == service_id).first() def dao_get_inbound_number(inbound_number_id): return InboundNumber.query.filter(InboundNumber.id == inbound_number_id).first() @transactional def dao_set_inbound_number_to_service(service_id, inbound_number): inbound_number.service_id = service_id db.session.add(inbound_number) @transactional def dao_set_inbound_number_active_flag(service_id, active): inbound_number = InboundNumber.query.filter(InboundNumber.service_id == service_id).first() inbound_number.active = active db.session.add(inbound_number)
from app import db from app.dao.dao_utils import transactional from app.models import InboundNumber def dao_get_inbound_numbers(): return InboundNumber.query.order_by(InboundNumber.updated_at, InboundNumber.number).all() def dao_get_available_inbound_numbers(): return InboundNumber.query.filter(InboundNumber.active, InboundNumber.service_id.is_(None)).all() def dao_get_inbound_number_for_service(service_id): return InboundNumber.query.filter(InboundNumber.service_id == service_id).first() def dao_get_inbound_number(inbound_number_id): return InboundNumber.query.filter(InboundNumber.id == inbound_number_id).first() @transactional def dao_set_inbound_number_to_service(service_id, inbound_number): inbound_number.service_id = service_id db.session.add(inbound_number) @transactional def dao_set_inbound_number_active_flag(service_id, active): inbound_number = InboundNumber.query.filter(InboundNumber.service_id == service_id).first() inbound_number.active = active db.session.add(inbound_number)
Update dao to order by updated_at, number
Update dao to order by updated_at, number
Python
mit
alphagov/notifications-api,alphagov/notifications-api
from app import db from app.dao.dao_utils import transactional from app.models import InboundNumber def dao_get_inbound_numbers(): - return InboundNumber.query.all() + return InboundNumber.query.order_by(InboundNumber.updated_at, InboundNumber.number).all() def dao_get_available_inbound_numbers(): return InboundNumber.query.filter(InboundNumber.active, InboundNumber.service_id.is_(None)).all() def dao_get_inbound_number_for_service(service_id): return InboundNumber.query.filter(InboundNumber.service_id == service_id).first() def dao_get_inbound_number(inbound_number_id): return InboundNumber.query.filter(InboundNumber.id == inbound_number_id).first() @transactional def dao_set_inbound_number_to_service(service_id, inbound_number): inbound_number.service_id = service_id db.session.add(inbound_number) @transactional def dao_set_inbound_number_active_flag(service_id, active): inbound_number = InboundNumber.query.filter(InboundNumber.service_id == service_id).first() inbound_number.active = active db.session.add(inbound_number)
Update dao to order by updated_at, number
## Code Before: from app import db from app.dao.dao_utils import transactional from app.models import InboundNumber def dao_get_inbound_numbers(): return InboundNumber.query.all() def dao_get_available_inbound_numbers(): return InboundNumber.query.filter(InboundNumber.active, InboundNumber.service_id.is_(None)).all() def dao_get_inbound_number_for_service(service_id): return InboundNumber.query.filter(InboundNumber.service_id == service_id).first() def dao_get_inbound_number(inbound_number_id): return InboundNumber.query.filter(InboundNumber.id == inbound_number_id).first() @transactional def dao_set_inbound_number_to_service(service_id, inbound_number): inbound_number.service_id = service_id db.session.add(inbound_number) @transactional def dao_set_inbound_number_active_flag(service_id, active): inbound_number = InboundNumber.query.filter(InboundNumber.service_id == service_id).first() inbound_number.active = active db.session.add(inbound_number) ## Instruction: Update dao to order by updated_at, number ## Code After: from app import db from app.dao.dao_utils import transactional from app.models import InboundNumber def dao_get_inbound_numbers(): return InboundNumber.query.order_by(InboundNumber.updated_at, InboundNumber.number).all() def dao_get_available_inbound_numbers(): return InboundNumber.query.filter(InboundNumber.active, InboundNumber.service_id.is_(None)).all() def dao_get_inbound_number_for_service(service_id): return InboundNumber.query.filter(InboundNumber.service_id == service_id).first() def dao_get_inbound_number(inbound_number_id): return InboundNumber.query.filter(InboundNumber.id == inbound_number_id).first() @transactional def dao_set_inbound_number_to_service(service_id, inbound_number): inbound_number.service_id = service_id db.session.add(inbound_number) @transactional def dao_set_inbound_number_active_flag(service_id, active): inbound_number = InboundNumber.query.filter(InboundNumber.service_id == service_id).first() inbound_number.active = active db.session.add(inbound_number)
from app import db from app.dao.dao_utils import transactional from app.models import InboundNumber def dao_get_inbound_numbers(): - return InboundNumber.query.all() + return InboundNumber.query.order_by(InboundNumber.updated_at, InboundNumber.number).all() def dao_get_available_inbound_numbers(): return InboundNumber.query.filter(InboundNumber.active, InboundNumber.service_id.is_(None)).all() def dao_get_inbound_number_for_service(service_id): return InboundNumber.query.filter(InboundNumber.service_id == service_id).first() def dao_get_inbound_number(inbound_number_id): return InboundNumber.query.filter(InboundNumber.id == inbound_number_id).first() @transactional def dao_set_inbound_number_to_service(service_id, inbound_number): inbound_number.service_id = service_id db.session.add(inbound_number) @transactional def dao_set_inbound_number_active_flag(service_id, active): inbound_number = InboundNumber.query.filter(InboundNumber.service_id == service_id).first() inbound_number.active = active db.session.add(inbound_number)
c3a6554ce24781a3eaa9229f9609a09e4e018069
lcd_restful/__main__.py
lcd_restful/__main__.py
import sys from getopt import getopt, GetoptError from .api import Server from .fake import FakeLcdApi USAGE = """\ Usage %s [-h|--help] \t-h or --help\tThis help message """ def get_args(args): try: opts, args = getopt(args[1:], 'hf', ['help', 'fake']) except GetoptError as e: print('GetoptError %s' % e) sys.exit(2) ret_args = {} ret_args['fake'] = False for opt, arg in opts: if opt in ['-h', '--help']: print(USAGE % args[0]) sys.exit(0) elif opt in ['-f', '--fake']: ret_args['fake'] = True else: print(USAGE % args[0]) sys.exit(1) return ret_args def main_serv(clargs=sys.argv): opts = get_args(clargs) lcd = None if opts['fake']: lcd = FakeLcdApi() s = Server(lcd=lcd) s.run() return 0 if __name__ == "__main__": sys.exit(main_serv())
import sys from getopt import getopt, GetoptError from .api import Server from .lcd import Lcd USAGE = """\ Usage %s [-h|--help] [-f|--fake] \t-h or --help\tThis help message \t-f or --fake\tIf on RPi, use FakeHw """ def get_args(args): arg0 = args[0] try: opts, args = getopt(args[1:], 'hf', ['help', 'fake']) except GetoptError as e: print('GetoptError %s' % e) sys.exit(2) ret_args = {} ret_args['fake'] = False for opt, arg in opts: if opt in ['-h', '--help']: print(USAGE % arg0) sys.exit(0) elif opt in ['-f', '--fake']: ret_args['fake'] = True else: print(USAGE % arg0) sys.exit(1) return ret_args def main_serv(clargs=sys.argv): opts = get_args(clargs) s = Server(lcd=Lcd(opts['fake'])) s.run() return 0 if __name__ == "__main__": sys.exit(main_serv())
Update main Lcd import and init, and fix help msg
Update main Lcd import and init, and fix help msg
Python
mit
rfarley3/lcd-restful,rfarley3/lcd-restful
import sys from getopt import getopt, GetoptError from .api import Server - from .fake import FakeLcdApi + from .lcd import Lcd USAGE = """\ - Usage %s [-h|--help] + Usage %s [-h|--help] [-f|--fake] \t-h or --help\tThis help message + \t-f or --fake\tIf on RPi, use FakeHw """ def get_args(args): + arg0 = args[0] try: opts, args = getopt(args[1:], 'hf', ['help', 'fake']) except GetoptError as e: print('GetoptError %s' % e) sys.exit(2) ret_args = {} ret_args['fake'] = False for opt, arg in opts: if opt in ['-h', '--help']: - print(USAGE % args[0]) + print(USAGE % arg0) sys.exit(0) elif opt in ['-f', '--fake']: ret_args['fake'] = True else: - print(USAGE % args[0]) + print(USAGE % arg0) sys.exit(1) return ret_args def main_serv(clargs=sys.argv): opts = get_args(clargs) + s = Server(lcd=Lcd(opts['fake'])) - lcd = None - if opts['fake']: - lcd = FakeLcdApi() - s = Server(lcd=lcd) s.run() return 0 if __name__ == "__main__": sys.exit(main_serv()) +
Update main Lcd import and init, and fix help msg
## Code Before: import sys from getopt import getopt, GetoptError from .api import Server from .fake import FakeLcdApi USAGE = """\ Usage %s [-h|--help] \t-h or --help\tThis help message """ def get_args(args): try: opts, args = getopt(args[1:], 'hf', ['help', 'fake']) except GetoptError as e: print('GetoptError %s' % e) sys.exit(2) ret_args = {} ret_args['fake'] = False for opt, arg in opts: if opt in ['-h', '--help']: print(USAGE % args[0]) sys.exit(0) elif opt in ['-f', '--fake']: ret_args['fake'] = True else: print(USAGE % args[0]) sys.exit(1) return ret_args def main_serv(clargs=sys.argv): opts = get_args(clargs) lcd = None if opts['fake']: lcd = FakeLcdApi() s = Server(lcd=lcd) s.run() return 0 if __name__ == "__main__": sys.exit(main_serv()) ## Instruction: Update main Lcd import and init, and fix help msg ## Code After: import sys from getopt import getopt, GetoptError from .api import Server from .lcd import Lcd USAGE = """\ Usage %s [-h|--help] [-f|--fake] \t-h or --help\tThis help message \t-f or --fake\tIf on RPi, use FakeHw """ def get_args(args): arg0 = args[0] try: opts, args = getopt(args[1:], 'hf', ['help', 'fake']) except GetoptError as e: print('GetoptError %s' % e) sys.exit(2) ret_args = {} ret_args['fake'] = False for opt, arg in opts: if opt in ['-h', '--help']: print(USAGE % arg0) sys.exit(0) elif opt in ['-f', '--fake']: ret_args['fake'] = True else: print(USAGE % arg0) sys.exit(1) return ret_args def main_serv(clargs=sys.argv): opts = get_args(clargs) s = Server(lcd=Lcd(opts['fake'])) s.run() return 0 if __name__ == "__main__": sys.exit(main_serv())
import sys from getopt import getopt, GetoptError from .api import Server - from .fake import FakeLcdApi + from .lcd import Lcd USAGE = """\ - Usage %s [-h|--help] + Usage %s [-h|--help] [-f|--fake] ? ++++++++++++ \t-h or --help\tThis help message + \t-f or --fake\tIf on RPi, use FakeHw """ def get_args(args): + arg0 = args[0] try: opts, args = getopt(args[1:], 'hf', ['help', 'fake']) except GetoptError as e: print('GetoptError %s' % e) sys.exit(2) ret_args = {} ret_args['fake'] = False for opt, arg in opts: if opt in ['-h', '--help']: - print(USAGE % args[0]) ? -- - + print(USAGE % arg0) sys.exit(0) elif opt in ['-f', '--fake']: ret_args['fake'] = True else: - print(USAGE % args[0]) ? -- - + print(USAGE % arg0) sys.exit(1) return ret_args def main_serv(clargs=sys.argv): opts = get_args(clargs) + s = Server(lcd=Lcd(opts['fake'])) - lcd = None - if opts['fake']: - lcd = FakeLcdApi() - s = Server(lcd=lcd) s.run() return 0 if __name__ == "__main__": sys.exit(main_serv()) +
c1e5e6a5c34f1d4617be3053d87af8e95045ad77
query/views.py
query/views.py
import ipwhois from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.views.decorators.cache import cache_page from django.views.decorators.csrf import csrf_protect from json import dumps from .forms import QueryForm def index(request): if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): return HttpResponseRedirect(reverse( 'query:results', args=(form['query'].value(),) )) else: form = QueryForm() return render(request, 'query/index.html', { 'title': 'Query', 'form': form }) @cache_page(86400) @csrf_protect def results(request, query): error = None result = {} form = QueryForm(initial={"query": query}) try: ip = ipwhois.IPWhois(query) result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True) title = ip.address_str except (ValueError, ipwhois.exceptions.IPDefinedError) as e: error = e title = 'Error' return render(request, 'query/index.html', { 'title': title, 'error': error, 'form': form, 'result': dumps(result) })
import ipwhois from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.views.decorators.cache import cache_page from django.views.decorators.csrf import csrf_protect from json import dumps from .forms import QueryForm def index(request): if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): return HttpResponseRedirect(reverse( 'query:results', args=(form['query'].value(),) )) else: form = QueryForm() return render(request, 'query/index.html', { 'title': 'Query', 'form': form }) @cache_page(86400) @csrf_protect def results(request, query): error = None result = {} form = QueryForm(initial={"query": query}) try: ip = ipwhois.IPWhois(query) result = ip.lookup_rdap(retry_count=1, depth=2) title = ip.address_str except (ValueError, ipwhois.exceptions.IPDefinedError) as e: error = e title = 'Error' return render(request, 'query/index.html', { 'title': title, 'error': error, 'form': form, 'result': dumps(result) })
Remove raw results from IPWhois object.
Remove raw results from IPWhois object.
Python
mit
cdubz/rdap-explorer,cdubz/rdap-explorer
import ipwhois from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.views.decorators.cache import cache_page from django.views.decorators.csrf import csrf_protect from json import dumps from .forms import QueryForm def index(request): if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): return HttpResponseRedirect(reverse( 'query:results', args=(form['query'].value(),) )) else: form = QueryForm() return render(request, 'query/index.html', { 'title': 'Query', 'form': form }) @cache_page(86400) @csrf_protect def results(request, query): error = None result = {} form = QueryForm(initial={"query": query}) try: ip = ipwhois.IPWhois(query) - result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True) + result = ip.lookup_rdap(retry_count=1, depth=2) title = ip.address_str except (ValueError, ipwhois.exceptions.IPDefinedError) as e: error = e title = 'Error' return render(request, 'query/index.html', { 'title': title, 'error': error, 'form': form, 'result': dumps(result) })
Remove raw results from IPWhois object.
## Code Before: import ipwhois from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.views.decorators.cache import cache_page from django.views.decorators.csrf import csrf_protect from json import dumps from .forms import QueryForm def index(request): if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): return HttpResponseRedirect(reverse( 'query:results', args=(form['query'].value(),) )) else: form = QueryForm() return render(request, 'query/index.html', { 'title': 'Query', 'form': form }) @cache_page(86400) @csrf_protect def results(request, query): error = None result = {} form = QueryForm(initial={"query": query}) try: ip = ipwhois.IPWhois(query) result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True) title = ip.address_str except (ValueError, ipwhois.exceptions.IPDefinedError) as e: error = e title = 'Error' return render(request, 'query/index.html', { 'title': title, 'error': error, 'form': form, 'result': dumps(result) }) ## Instruction: Remove raw results from IPWhois object. ## Code After: import ipwhois from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.views.decorators.cache import cache_page from django.views.decorators.csrf import csrf_protect from json import dumps from .forms import QueryForm def index(request): if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): return HttpResponseRedirect(reverse( 'query:results', args=(form['query'].value(),) )) else: form = QueryForm() return render(request, 'query/index.html', { 'title': 'Query', 'form': form }) @cache_page(86400) @csrf_protect def results(request, query): error = None result = {} form = QueryForm(initial={"query": query}) try: ip = ipwhois.IPWhois(query) result = ip.lookup_rdap(retry_count=1, depth=2) title = ip.address_str except (ValueError, ipwhois.exceptions.IPDefinedError) as e: error = e title = 'Error' return render(request, 'query/index.html', { 'title': title, 'error': error, 'form': form, 'result': dumps(result) })
import ipwhois from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.views.decorators.cache import cache_page from django.views.decorators.csrf import csrf_protect from json import dumps from .forms import QueryForm def index(request): if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): return HttpResponseRedirect(reverse( 'query:results', args=(form['query'].value(),) )) else: form = QueryForm() return render(request, 'query/index.html', { 'title': 'Query', 'form': form }) @cache_page(86400) @csrf_protect def results(request, query): error = None result = {} form = QueryForm(initial={"query": query}) try: ip = ipwhois.IPWhois(query) - result = ip.lookup_rdap(retry_count=1, depth=2, inc_raw=True) ? -------------- + result = ip.lookup_rdap(retry_count=1, depth=2) title = ip.address_str except (ValueError, ipwhois.exceptions.IPDefinedError) as e: error = e title = 'Error' return render(request, 'query/index.html', { 'title': title, 'error': error, 'form': form, 'result': dumps(result) })
1093601daf8d42f0e3745788e51c1b843d29f2d7
git-keeper-robot/gkeeprobot/keywords/ServerSetupKeywords.py
git-keeper-robot/gkeeprobot/keywords/ServerSetupKeywords.py
from gkeeprobot.control.ServerControl import ServerControl """Provides keywords for robotframework to configure gkserver before testing begins.""" control = ServerControl() class ServerSetupKeywords: def add_file_to_server(self, username, filename, target_filename): control.copy(username, filename, target_filename) def start_gkeepd(self): control.run('keeper', 'screen -S gkserver -d -m gkeepd') def add_account_on_server(self, faculty_name): cmd = 'sudo useradd -ms /bin/bash {}'.format(faculty_name) control.run('keeper', cmd) def reset_server(self): control.run_vm_python_script('keeper', 'reset_server.py')
from gkeeprobot.control.ServerControl import ServerControl """Provides keywords for robotframework to configure gkserver before testing begins.""" control = ServerControl() class ServerSetupKeywords: def add_file_to_server(self, username, filename, target_filename): control.copy(username, filename, target_filename) def start_gkeepd(self): control.run('keeper', 'screen -S gkserver -d -m gkeepd') def stop_gkeepd(self): control.run('keeper', 'screen -S gkserver -X quit') def add_account_on_server(self, faculty_name): cmd = 'sudo useradd -ms /bin/bash {}'.format(faculty_name) control.run('keeper', cmd) def reset_server(self): control.run_vm_python_script('keeper', 'reset_server.py')
Add command to stop gkeepd
Add command to stop gkeepd
Python
agpl-3.0
git-keeper/git-keeper,git-keeper/git-keeper
from gkeeprobot.control.ServerControl import ServerControl """Provides keywords for robotframework to configure gkserver before testing begins.""" control = ServerControl() class ServerSetupKeywords: def add_file_to_server(self, username, filename, target_filename): control.copy(username, filename, target_filename) def start_gkeepd(self): control.run('keeper', 'screen -S gkserver -d -m gkeepd') + def stop_gkeepd(self): + control.run('keeper', 'screen -S gkserver -X quit') + def add_account_on_server(self, faculty_name): cmd = 'sudo useradd -ms /bin/bash {}'.format(faculty_name) control.run('keeper', cmd) def reset_server(self): control.run_vm_python_script('keeper', 'reset_server.py')
Add command to stop gkeepd
## Code Before: from gkeeprobot.control.ServerControl import ServerControl """Provides keywords for robotframework to configure gkserver before testing begins.""" control = ServerControl() class ServerSetupKeywords: def add_file_to_server(self, username, filename, target_filename): control.copy(username, filename, target_filename) def start_gkeepd(self): control.run('keeper', 'screen -S gkserver -d -m gkeepd') def add_account_on_server(self, faculty_name): cmd = 'sudo useradd -ms /bin/bash {}'.format(faculty_name) control.run('keeper', cmd) def reset_server(self): control.run_vm_python_script('keeper', 'reset_server.py') ## Instruction: Add command to stop gkeepd ## Code After: from gkeeprobot.control.ServerControl import ServerControl """Provides keywords for robotframework to configure gkserver before testing begins.""" control = ServerControl() class ServerSetupKeywords: def add_file_to_server(self, username, filename, target_filename): control.copy(username, filename, target_filename) def start_gkeepd(self): control.run('keeper', 'screen -S gkserver -d -m gkeepd') def stop_gkeepd(self): control.run('keeper', 'screen -S gkserver -X quit') def add_account_on_server(self, faculty_name): cmd = 'sudo useradd -ms /bin/bash {}'.format(faculty_name) control.run('keeper', cmd) def reset_server(self): control.run_vm_python_script('keeper', 'reset_server.py')
from gkeeprobot.control.ServerControl import ServerControl """Provides keywords for robotframework to configure gkserver before testing begins.""" control = ServerControl() class ServerSetupKeywords: def add_file_to_server(self, username, filename, target_filename): control.copy(username, filename, target_filename) def start_gkeepd(self): control.run('keeper', 'screen -S gkserver -d -m gkeepd') + def stop_gkeepd(self): + control.run('keeper', 'screen -S gkserver -X quit') + def add_account_on_server(self, faculty_name): cmd = 'sudo useradd -ms /bin/bash {}'.format(faculty_name) control.run('keeper', cmd) def reset_server(self): control.run_vm_python_script('keeper', 'reset_server.py')
5b554752aaabd59b8248f9eecfc03458dd9f07d0
coding/admin.py
coding/admin.py
from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") date_hierarchy = "action_time" admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
Add date drill down to coding assignment activity list
Add date drill down to coding assignment activity list
Python
mit
inducer/codery,inducer/codery
from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") + date_hierarchy = "action_time" + admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
Add date drill down to coding assignment activity list
## Code Before: from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin) ## Instruction: Add date drill down to coding assignment activity list ## Code After: from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") date_hierarchy = "action_time" admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") + date_hierarchy = "action_time" + admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
c6862c5f864db4e77dd835f074efdd284667e6fd
util/ldjpp.py
util/ldjpp.py
from __future__ import print_function import argparse import json parser = argparse.ArgumentParser(description='Pretty-print LDJSON.') parser.add_argument('--indent', metavar='N', type=int, default=2, dest='indent', help='indentation for pretty-printing') parser.add_argument('--file', metavar='FILE', required=True, dest='file', type=argparse.FileType('r'), help='input LDJSON file') parser.add_argument('--sort', action='store_true', dest='sortkeys', help='sort object keys') args = parser.parse_args() for line in args.file: record = json.loads(line) print(json.dumps(record, indent=args.indent, sort_keys=args.sortkeys))
from __future__ import print_function import click import json from collections import OrderedDict def json_loader(sortkeys): def _loader(line): if sortkeys: return json.loads(line) else: # if --no-sortkeys, let's preserve file order return json.JSONDecoder(object_pairs_hook=OrderedDict).decode(line) return _loader @click.command() @click.option('indent', '-i', '--indent', default=2, help='indentation for pretty-printing') @click.option('--sortkeys/--no-sortkeys', default=False, help='sort object keys') @click.argument('infile', type=click.File()) def cli(indent, sortkeys, infile): """Pretty-print LDJSON.""" loader = json_loader(sortkeys) for line in infile: record = loader(line) print(json.dumps(record, indent=indent, sort_keys=sortkeys)) if __name__ == '__main__': cli()
Use click instead of argparse
Use click instead of argparse
Python
mit
mhyfritz/goontools,mhyfritz/goontools,mhyfritz/goontools
from __future__ import print_function - import argparse + import click import json + from collections import OrderedDict - parser = argparse.ArgumentParser(description='Pretty-print LDJSON.') - parser.add_argument('--indent', metavar='N', type=int, default=2, - dest='indent', help='indentation for pretty-printing') - parser.add_argument('--file', metavar='FILE', required=True, dest='file', - type=argparse.FileType('r'), help='input LDJSON file') - parser.add_argument('--sort', action='store_true', dest='sortkeys', - help='sort object keys') - args = parser.parse_args() + def json_loader(sortkeys): + def _loader(line): + if sortkeys: + return json.loads(line) + else: + # if --no-sortkeys, let's preserve file order + return json.JSONDecoder(object_pairs_hook=OrderedDict).decode(line) + return _loader - for line in args.file: - record = json.loads(line) - print(json.dumps(record, indent=args.indent, sort_keys=args.sortkeys)) + + @click.command() + @click.option('indent', '-i', '--indent', default=2, + help='indentation for pretty-printing') + @click.option('--sortkeys/--no-sortkeys', default=False, + help='sort object keys') + @click.argument('infile', type=click.File()) + def cli(indent, sortkeys, infile): + """Pretty-print LDJSON.""" + loader = json_loader(sortkeys) + for line in infile: + record = loader(line) + print(json.dumps(record, indent=indent, sort_keys=sortkeys)) + + if __name__ == '__main__': + cli() +
Use click instead of argparse
## Code Before: from __future__ import print_function import argparse import json parser = argparse.ArgumentParser(description='Pretty-print LDJSON.') parser.add_argument('--indent', metavar='N', type=int, default=2, dest='indent', help='indentation for pretty-printing') parser.add_argument('--file', metavar='FILE', required=True, dest='file', type=argparse.FileType('r'), help='input LDJSON file') parser.add_argument('--sort', action='store_true', dest='sortkeys', help='sort object keys') args = parser.parse_args() for line in args.file: record = json.loads(line) print(json.dumps(record, indent=args.indent, sort_keys=args.sortkeys)) ## Instruction: Use click instead of argparse ## Code After: from __future__ import print_function import click import json from collections import OrderedDict def json_loader(sortkeys): def _loader(line): if sortkeys: return json.loads(line) else: # if --no-sortkeys, let's preserve file order return json.JSONDecoder(object_pairs_hook=OrderedDict).decode(line) return _loader @click.command() @click.option('indent', '-i', '--indent', default=2, help='indentation for pretty-printing') @click.option('--sortkeys/--no-sortkeys', default=False, help='sort object keys') @click.argument('infile', type=click.File()) def cli(indent, sortkeys, infile): """Pretty-print LDJSON.""" loader = json_loader(sortkeys) for line in infile: record = loader(line) print(json.dumps(record, indent=indent, sort_keys=sortkeys)) if __name__ == '__main__': cli()
from __future__ import print_function - import argparse + import click import json + from collections import OrderedDict - parser = argparse.ArgumentParser(description='Pretty-print LDJSON.') - parser.add_argument('--indent', metavar='N', type=int, default=2, - dest='indent', help='indentation for pretty-printing') - parser.add_argument('--file', metavar='FILE', required=True, dest='file', - type=argparse.FileType('r'), help='input LDJSON file') - parser.add_argument('--sort', action='store_true', dest='sortkeys', - help='sort object keys') - args = parser.parse_args() + def json_loader(sortkeys): + def _loader(line): + if sortkeys: + return json.loads(line) + else: + # if --no-sortkeys, let's preserve file order + return json.JSONDecoder(object_pairs_hook=OrderedDict).decode(line) + return _loader + + + @click.command() + @click.option('indent', '-i', '--indent', default=2, + help='indentation for pretty-printing') + @click.option('--sortkeys/--no-sortkeys', default=False, + help='sort object keys') + @click.argument('infile', type=click.File()) + def cli(indent, sortkeys, infile): + """Pretty-print LDJSON.""" + loader = json_loader(sortkeys) - for line in args.file: ? ^^^^^ + for line in infile: ? ++++ ^^ - record = json.loads(line) ? ----- ^ + record = loader(line) ? ++++ ^^ - print(json.dumps(record, indent=args.indent, sort_keys=args.sortkeys)) ? ----- ----- + print(json.dumps(record, indent=indent, sort_keys=sortkeys)) ? ++++ + + if __name__ == '__main__': + cli()
bc576b0284ebf49e105af678b483173084068bfb
ufyr/utils/http.py
ufyr/utils/http.py
import json import requests class Callback(object): def __init__(self, url, method='GET', req_kwargs={}, **kwargs): assert isinstance(url, (str, unicode)) assert isinstance(method, (str, unicode)) assert isinstance(req_kwargs, dict) self.url = url self.method = method self.req_kwargs = req_kwargs def __eq__(self, other): return all((self.url.lower() == other.url.lower(), self.method.lower() == other.method.lower(), self.req_kwargs == other.req_kwargs)) @classmethod def from_json(cls, json_string): ''' Input: string json_string containing a url key Returns: a Callback obj instance initalized by the parameters in the json_string. ''' json_obj = json.loads(json_string) if 'url' not in json_obj: raise Exception('"url" not in json') return Callback(**json_obj) def to_json(self): ''' Return a JSON serialization of the Callback obj. ''' json_obj = {'url':self.url, 'method':self.method, 'req_kwargs':self.req_kwargs} return json.dumps(json_obj) def execute(self): ''' Execute the callback call that this object represents. ''' f = getattr(requests, self.method.lower()) return f(self.url, **self.req_kwargs)
import json import requests from ufyr.decorators import retry class Callback(object): def __init__(self, url, method='GET', req_kwargs={}, **kwargs): assert isinstance(url, (str, unicode)) assert isinstance(method, (str, unicode)) assert isinstance(req_kwargs, dict) self.url = url self.method = method self.req_kwargs = req_kwargs def __eq__(self, other): return all((self.url.lower() == other.url.lower(), self.method.lower() == other.method.lower(), self.req_kwargs == other.req_kwargs)) @classmethod def from_json(cls, json_string): ''' Input: string json_string containing a url key Returns: a Callback obj instance initalized by the parameters in the json_string. ''' json_obj = json.loads(json_string) if 'url' not in json_obj: raise Exception('"url" not in json') return Callback(**json_obj) def to_json(self): ''' Return a JSON serialization of the Callback obj. ''' json_obj = {'url':self.url, 'method':self.method, 'req_kwargs':self.req_kwargs} return json.dumps(json_obj) @retry def execute(self): ''' Execute the callback call that this object represents. ''' f = getattr(requests, self.method.lower()) return f(self.url, **self.req_kwargs).status_code < 400
Add retry and failure detection to callback.execute
Add retry and failure detection to callback.execute
Python
unlicense
timeartist/ufyr
import json import requests + + from ufyr.decorators import retry class Callback(object): def __init__(self, url, method='GET', req_kwargs={}, **kwargs): assert isinstance(url, (str, unicode)) assert isinstance(method, (str, unicode)) assert isinstance(req_kwargs, dict) self.url = url self.method = method self.req_kwargs = req_kwargs def __eq__(self, other): return all((self.url.lower() == other.url.lower(), self.method.lower() == other.method.lower(), self.req_kwargs == other.req_kwargs)) @classmethod def from_json(cls, json_string): ''' Input: string json_string containing a url key Returns: a Callback obj instance initalized by the parameters in the json_string. ''' json_obj = json.loads(json_string) if 'url' not in json_obj: raise Exception('"url" not in json') return Callback(**json_obj) def to_json(self): ''' Return a JSON serialization of the Callback obj. ''' json_obj = {'url':self.url, 'method':self.method, 'req_kwargs':self.req_kwargs} return json.dumps(json_obj) + @retry def execute(self): ''' Execute the callback call that this object represents. ''' f = getattr(requests, self.method.lower()) - return f(self.url, **self.req_kwargs) + return f(self.url, **self.req_kwargs).status_code < 400
Add retry and failure detection to callback.execute
## Code Before: import json import requests class Callback(object): def __init__(self, url, method='GET', req_kwargs={}, **kwargs): assert isinstance(url, (str, unicode)) assert isinstance(method, (str, unicode)) assert isinstance(req_kwargs, dict) self.url = url self.method = method self.req_kwargs = req_kwargs def __eq__(self, other): return all((self.url.lower() == other.url.lower(), self.method.lower() == other.method.lower(), self.req_kwargs == other.req_kwargs)) @classmethod def from_json(cls, json_string): ''' Input: string json_string containing a url key Returns: a Callback obj instance initalized by the parameters in the json_string. ''' json_obj = json.loads(json_string) if 'url' not in json_obj: raise Exception('"url" not in json') return Callback(**json_obj) def to_json(self): ''' Return a JSON serialization of the Callback obj. ''' json_obj = {'url':self.url, 'method':self.method, 'req_kwargs':self.req_kwargs} return json.dumps(json_obj) def execute(self): ''' Execute the callback call that this object represents. ''' f = getattr(requests, self.method.lower()) return f(self.url, **self.req_kwargs) ## Instruction: Add retry and failure detection to callback.execute ## Code After: import json import requests from ufyr.decorators import retry class Callback(object): def __init__(self, url, method='GET', req_kwargs={}, **kwargs): assert isinstance(url, (str, unicode)) assert isinstance(method, (str, unicode)) assert isinstance(req_kwargs, dict) self.url = url self.method = method self.req_kwargs = req_kwargs def __eq__(self, other): return all((self.url.lower() == other.url.lower(), self.method.lower() == other.method.lower(), self.req_kwargs == other.req_kwargs)) @classmethod def from_json(cls, json_string): ''' Input: string json_string containing a url key Returns: a Callback obj instance initalized by the parameters in the json_string. ''' json_obj = json.loads(json_string) if 'url' not in json_obj: raise Exception('"url" not in json') return Callback(**json_obj) def to_json(self): ''' Return a JSON serialization of the Callback obj. ''' json_obj = {'url':self.url, 'method':self.method, 'req_kwargs':self.req_kwargs} return json.dumps(json_obj) @retry def execute(self): ''' Execute the callback call that this object represents. ''' f = getattr(requests, self.method.lower()) return f(self.url, **self.req_kwargs).status_code < 400
import json import requests + + from ufyr.decorators import retry class Callback(object): def __init__(self, url, method='GET', req_kwargs={}, **kwargs): assert isinstance(url, (str, unicode)) assert isinstance(method, (str, unicode)) assert isinstance(req_kwargs, dict) self.url = url self.method = method self.req_kwargs = req_kwargs def __eq__(self, other): return all((self.url.lower() == other.url.lower(), self.method.lower() == other.method.lower(), self.req_kwargs == other.req_kwargs)) @classmethod def from_json(cls, json_string): ''' Input: string json_string containing a url key Returns: a Callback obj instance initalized by the parameters in the json_string. ''' json_obj = json.loads(json_string) if 'url' not in json_obj: raise Exception('"url" not in json') return Callback(**json_obj) def to_json(self): ''' Return a JSON serialization of the Callback obj. ''' json_obj = {'url':self.url, 'method':self.method, 'req_kwargs':self.req_kwargs} return json.dumps(json_obj) + @retry def execute(self): ''' Execute the callback call that this object represents. ''' f = getattr(requests, self.method.lower()) - return f(self.url, **self.req_kwargs) + return f(self.url, **self.req_kwargs).status_code < 400 ? ++++++++++++++++++
591a40b6e1f4ac8b1d21050ccfa10779dc9dbf7c
analytic_code.py
analytic_code.py
from openerp.osv import fields, osv class analytic_code(osv.Model): _name = "analytic.code" _columns = dict( name=fields.char("Name", size=128, translate=True, required=True), nd_id=fields.many2one( "analytic.dimension", ondelete="restrict"), active=fields.boolean('Active'), nd_name=fields.related('nd_id', 'name', type="char", string="Dimension Name", store=False), description=fields.char('Description', size=512), ) _defaults = { 'active': 1, }
from openerp.osv import fields, osv class analytic_code(osv.Model): _name = "analytic.code" _columns = dict( name=fields.char("Name", size=128, translate=True, required=True), nd_id=fields.many2one( "analytic.dimension", "Dimensions", ondelete="restrict"), active=fields.boolean('Active'), nd_name=fields.related('nd_id', 'name', type="char", string="Dimension Name", store=False), description=fields.char('Description', size=512), ) _defaults = { 'active': 1, }
Add string to display the name of the field Dimension during the import
Add string to display the name of the field Dimension during the import
Python
agpl-3.0
xcgd/analytic_structure
from openerp.osv import fields, osv class analytic_code(osv.Model): _name = "analytic.code" _columns = dict( name=fields.char("Name", size=128, translate=True, required=True), nd_id=fields.many2one( - "analytic.dimension", ondelete="restrict"), + "analytic.dimension", "Dimensions", ondelete="restrict"), active=fields.boolean('Active'), nd_name=fields.related('nd_id', 'name', type="char", string="Dimension Name", store=False), description=fields.char('Description', size=512), ) _defaults = { 'active': 1, }
Add string to display the name of the field Dimension during the import
## Code Before: from openerp.osv import fields, osv class analytic_code(osv.Model): _name = "analytic.code" _columns = dict( name=fields.char("Name", size=128, translate=True, required=True), nd_id=fields.many2one( "analytic.dimension", ondelete="restrict"), active=fields.boolean('Active'), nd_name=fields.related('nd_id', 'name', type="char", string="Dimension Name", store=False), description=fields.char('Description', size=512), ) _defaults = { 'active': 1, } ## Instruction: Add string to display the name of the field Dimension during the import ## Code After: from openerp.osv import fields, osv class analytic_code(osv.Model): _name = "analytic.code" _columns = dict( name=fields.char("Name", size=128, translate=True, required=True), nd_id=fields.many2one( "analytic.dimension", "Dimensions", ondelete="restrict"), active=fields.boolean('Active'), nd_name=fields.related('nd_id', 'name', type="char", string="Dimension Name", store=False), description=fields.char('Description', size=512), ) _defaults = { 'active': 1, }
from openerp.osv import fields, osv class analytic_code(osv.Model): _name = "analytic.code" _columns = dict( name=fields.char("Name", size=128, translate=True, required=True), nd_id=fields.many2one( - "analytic.dimension", ondelete="restrict"), + "analytic.dimension", "Dimensions", ondelete="restrict"), ? ++++++++++++++ active=fields.boolean('Active'), nd_name=fields.related('nd_id', 'name', type="char", string="Dimension Name", store=False), description=fields.char('Description', size=512), ) _defaults = { 'active': 1, }
b5c85d3bbeb34dd3e5dd9c376bc3e121e518084e
src/zeit/workflow/xmlrpc/tests.py
src/zeit/workflow/xmlrpc/tests.py
from zope.testing import doctest import unittest import zeit.cms.testing import zeit.workflow.testing def test_suite(): suite = unittest.TestSuite() suite.addTest(zeit.cms.testing.FunctionalDocFileSuite( 'README.txt', layer=zeit.workflow.testing.WorkflowLayer, product_config={'zeit.workflow': zeit.workflow.testing.product_config} )) return suite
import zeit.cms.testing import zeit.workflow.testing def test_suite(): return zeit.cms.testing.FunctionalDocFileSuite( 'README.txt', layer=zeit.workflow.testing.WorkflowLayer )
Remove superfluous (and wrong!) product config declaration
Remove superfluous (and wrong!) product config declaration
Python
bsd-3-clause
ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms
- from zope.testing import doctest - import unittest import zeit.cms.testing import zeit.workflow.testing def test_suite(): - suite = unittest.TestSuite() - suite.addTest(zeit.cms.testing.FunctionalDocFileSuite( + return zeit.cms.testing.FunctionalDocFileSuite( 'README.txt', - layer=zeit.workflow.testing.WorkflowLayer, + layer=zeit.workflow.testing.WorkflowLayer - product_config={'zeit.workflow': zeit.workflow.testing.product_config} - )) + ) - return suite
Remove superfluous (and wrong!) product config declaration
## Code Before: from zope.testing import doctest import unittest import zeit.cms.testing import zeit.workflow.testing def test_suite(): suite = unittest.TestSuite() suite.addTest(zeit.cms.testing.FunctionalDocFileSuite( 'README.txt', layer=zeit.workflow.testing.WorkflowLayer, product_config={'zeit.workflow': zeit.workflow.testing.product_config} )) return suite ## Instruction: Remove superfluous (and wrong!) product config declaration ## Code After: import zeit.cms.testing import zeit.workflow.testing def test_suite(): return zeit.cms.testing.FunctionalDocFileSuite( 'README.txt', layer=zeit.workflow.testing.WorkflowLayer )
- from zope.testing import doctest - import unittest import zeit.cms.testing import zeit.workflow.testing def test_suite(): - suite = unittest.TestSuite() - suite.addTest(zeit.cms.testing.FunctionalDocFileSuite( ? ^ ^^^^^^^^^^^^ + return zeit.cms.testing.FunctionalDocFileSuite( ? ^^^ ^^^ 'README.txt', - layer=zeit.workflow.testing.WorkflowLayer, ? - + layer=zeit.workflow.testing.WorkflowLayer - product_config={'zeit.workflow': zeit.workflow.testing.product_config} - )) ? - + ) - return suite
c8c858cd26031178a8be30c3824577e0832806dc
bookworm/settings_mobile.py
bookworm/settings_mobile.py
from settings import * import settings TEMPLATE_DIRS_BASE = TEMPLATE_DIRS TEMPLATE_DIRS = ( '%s/library/templates/mobile/auth' % ROOT_PATH, '%s/library/templates/mobile' % ROOT_PATH, ) TEMPLATE_DIRS += TEMPLATE_DIRS_BASE MOBILE = True
from settings import * import settings TEMPLATE_DIRS_BASE = TEMPLATE_DIRS TEMPLATE_DIRS = ( '%s/library/templates/mobile/auth' % ROOT_PATH, '%s/library/templates/mobile' % ROOT_PATH, ) TEMPLATE_DIRS += TEMPLATE_DIRS_BASE MOBILE = True SESSION_COOKIE_NAME = 'bookworm_mobile'
Change cookie name for mobile setting
Change cookie name for mobile setting --HG-- extra : convert_revision : svn%3Ae08d0fb5-4147-0410-a205-bba44f1f51a3/trunk%40553
Python
bsd-3-clause
erochest/threepress-rdfa,erochest/threepress-rdfa,erochest/threepress-rdfa,erochest/threepress-rdfa
from settings import * import settings TEMPLATE_DIRS_BASE = TEMPLATE_DIRS TEMPLATE_DIRS = ( '%s/library/templates/mobile/auth' % ROOT_PATH, '%s/library/templates/mobile' % ROOT_PATH, ) TEMPLATE_DIRS += TEMPLATE_DIRS_BASE MOBILE = True + SESSION_COOKIE_NAME = 'bookworm_mobile'
Change cookie name for mobile setting
## Code Before: from settings import * import settings TEMPLATE_DIRS_BASE = TEMPLATE_DIRS TEMPLATE_DIRS = ( '%s/library/templates/mobile/auth' % ROOT_PATH, '%s/library/templates/mobile' % ROOT_PATH, ) TEMPLATE_DIRS += TEMPLATE_DIRS_BASE MOBILE = True ## Instruction: Change cookie name for mobile setting ## Code After: from settings import * import settings TEMPLATE_DIRS_BASE = TEMPLATE_DIRS TEMPLATE_DIRS = ( '%s/library/templates/mobile/auth' % ROOT_PATH, '%s/library/templates/mobile' % ROOT_PATH, ) TEMPLATE_DIRS += TEMPLATE_DIRS_BASE MOBILE = True SESSION_COOKIE_NAME = 'bookworm_mobile'
from settings import * import settings TEMPLATE_DIRS_BASE = TEMPLATE_DIRS TEMPLATE_DIRS = ( '%s/library/templates/mobile/auth' % ROOT_PATH, '%s/library/templates/mobile' % ROOT_PATH, ) TEMPLATE_DIRS += TEMPLATE_DIRS_BASE MOBILE = True + SESSION_COOKIE_NAME = 'bookworm_mobile'
3664b2d9b7590b6750e35abba2c0fe77c7afd4cd
bin/license_finder_pip.py
bin/license_finder_pip.py
import json import sys try: from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements try: from pip._internal.download import PipSession except ImportError: from pip.download import PipSession from pip._vendor import pkg_resources from pip._vendor.six import print_ reqs = [] for req in parse_requirements(sys.argv[1], session=PipSession()): if req.req == None or (req.markers != None and not req.markers.evaluate()): continue reqs.append(req) requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in reqs] transform = lambda dist: { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())), } packages = [transform(dist) for dist in pkg_resources.working_set.resolve(requirements)] print_(json.dumps(packages))
import json import sys try: from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements try: # since pip 19.3 from pip._internal.network.session import PipSession except ImportError: try: # since pip 10 from pip._internal.download import PipSession except ImportError: from pip.download import PipSession from pip._vendor import pkg_resources from pip._vendor.six import print_ reqs = [] for req in parse_requirements(sys.argv[1], session=PipSession()): if req.req == None or (req.markers != None and not req.markers.evaluate()): continue reqs.append(req) requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in reqs] transform = lambda dist: { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())), } packages = [transform(dist) for dist in pkg_resources.working_set.resolve(requirements)] print_(json.dumps(packages))
Support finding licenses with pip>=19.3
Support finding licenses with pip>=19.3
Python
mit
pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder
import json import sys try: from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements + try: + # since pip 19.3 + from pip._internal.network.session import PipSession + except ImportError: + try: + # since pip 10 from pip._internal.download import PipSession - except ImportError: + except ImportError: from pip.download import PipSession from pip._vendor import pkg_resources from pip._vendor.six import print_ reqs = [] for req in parse_requirements(sys.argv[1], session=PipSession()): if req.req == None or (req.markers != None and not req.markers.evaluate()): continue reqs.append(req) requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in reqs] transform = lambda dist: { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())), } packages = [transform(dist) for dist in pkg_resources.working_set.resolve(requirements)] print_(json.dumps(packages))
Support finding licenses with pip>=19.3
## Code Before: import json import sys try: from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements try: from pip._internal.download import PipSession except ImportError: from pip.download import PipSession from pip._vendor import pkg_resources from pip._vendor.six import print_ reqs = [] for req in parse_requirements(sys.argv[1], session=PipSession()): if req.req == None or (req.markers != None and not req.markers.evaluate()): continue reqs.append(req) requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in reqs] transform = lambda dist: { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())), } packages = [transform(dist) for dist in pkg_resources.working_set.resolve(requirements)] print_(json.dumps(packages)) ## Instruction: Support finding licenses with pip>=19.3 ## Code After: import json import sys try: from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements try: # since pip 19.3 from pip._internal.network.session import PipSession except ImportError: try: # since pip 10 from pip._internal.download import PipSession except ImportError: from pip.download import PipSession from pip._vendor import pkg_resources from pip._vendor.six import print_ reqs = [] for req in parse_requirements(sys.argv[1], session=PipSession()): if req.req == None or (req.markers != None and not req.markers.evaluate()): continue reqs.append(req) requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in reqs] transform = lambda dist: { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())), } packages = [transform(dist) for dist in pkg_resources.working_set.resolve(requirements)] print_(json.dumps(packages))
import json import sys try: from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements + try: + # since pip 19.3 + from pip._internal.network.session import PipSession + except ImportError: + try: + # since pip 10 from pip._internal.download import PipSession - except ImportError: + except ImportError: ? ++++ from pip.download import PipSession from pip._vendor import pkg_resources from pip._vendor.six import print_ reqs = [] for req in parse_requirements(sys.argv[1], session=PipSession()): if req.req == None or (req.markers != None and not req.markers.evaluate()): continue reqs.append(req) requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in reqs] transform = lambda dist: { 'name': dist.project_name, 'version': dist.version, 'location': dist.location, 'dependencies': list(map(lambda dependency: dependency.project_name, dist.requires())), } packages = [transform(dist) for dist in pkg_resources.working_set.resolve(requirements)] print_(json.dumps(packages))
09d780474d00f3a8f4c2295154d74dae2023c1d3
samples/storage_sample/storage/__init__.py
samples/storage_sample/storage/__init__.py
"""Common imports for generated storage client library.""" # pylint:disable=wildcard-import import pkgutil from apitools.base.py import * from storage_v1 import * from storage_v1_client import * from storage_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__)
"""Common imports for generated storage client library.""" # pylint:disable=wildcard-import import pkgutil from apitools.base.py import * from storage_v1_client import * from storage_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__)
Drop the CLI from the sample storage client imports.
Drop the CLI from the sample storage client imports.
Python
apache-2.0
cherba/apitools,craigcitro/apitools,b-daniels/apitools,betamos/apitools,kevinli7/apitools,houglum/apitools,pcostell/apitools,thobrla/apitools,google/apitools
"""Common imports for generated storage client library.""" # pylint:disable=wildcard-import import pkgutil from apitools.base.py import * - from storage_v1 import * from storage_v1_client import * from storage_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__)
Drop the CLI from the sample storage client imports.
## Code Before: """Common imports for generated storage client library.""" # pylint:disable=wildcard-import import pkgutil from apitools.base.py import * from storage_v1 import * from storage_v1_client import * from storage_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__) ## Instruction: Drop the CLI from the sample storage client imports. ## Code After: """Common imports for generated storage client library.""" # pylint:disable=wildcard-import import pkgutil from apitools.base.py import * from storage_v1_client import * from storage_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__)
"""Common imports for generated storage client library.""" # pylint:disable=wildcard-import import pkgutil from apitools.base.py import * - from storage_v1 import * from storage_v1_client import * from storage_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__)
a4eb952cc2e583d3b7786f5dea101d1e013c8159
services/controllers/utils.py
services/controllers/utils.py
def map_range(x, in_min, in_max, out_min, out_max): out_delta = out_max - out_min in_delta = in_max - in_min return (x - in_min) * out_delta / in_delta + out_min
def lerp(a, b, t): return (1.0 - t) * a + t * b def map_range(x, in_min, in_max, out_min, out_max): out_delta = out_max - out_min in_delta = in_max - in_min return (x - in_min) * out_delta / in_delta + out_min
Add function for linear interpolation (lerp)
Add function for linear interpolation (lerp)
Python
bsd-3-clause
gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2
+ def lerp(a, b, t): + return (1.0 - t) * a + t * b + + def map_range(x, in_min, in_max, out_min, out_max): out_delta = out_max - out_min in_delta = in_max - in_min return (x - in_min) * out_delta / in_delta + out_min
Add function for linear interpolation (lerp)
## Code Before: def map_range(x, in_min, in_max, out_min, out_max): out_delta = out_max - out_min in_delta = in_max - in_min return (x - in_min) * out_delta / in_delta + out_min ## Instruction: Add function for linear interpolation (lerp) ## Code After: def lerp(a, b, t): return (1.0 - t) * a + t * b def map_range(x, in_min, in_max, out_min, out_max): out_delta = out_max - out_min in_delta = in_max - in_min return (x - in_min) * out_delta / in_delta + out_min
+ def lerp(a, b, t): + return (1.0 - t) * a + t * b + + def map_range(x, in_min, in_max, out_min, out_max): out_delta = out_max - out_min in_delta = in_max - in_min return (x - in_min) * out_delta / in_delta + out_min
1bbffc2152ea1c48b47153005beeb2974b682f3c
bot/actions/action.py
bot/actions/action.py
from bot.api.api import Api from bot.storage import Config, State, Cache from bot.utils.dictionaryobject import DictionaryObject class Event(DictionaryObject): pass class Update(Event): def __init__(self, update, is_pending): super().__init__() self.update = update self.is_pending = is_pending class Action: def __init__(self): pass def get_name(self): return self.__class__.__name__ def setup(self, api: Api, config: Config, state: State, cache: Cache): self.api = api self.config = config self.state = state self.cache = cache self.post_setup() def post_setup(self): pass def process(self, event): pass class ActionGroup(Action): def __init__(self, *actions): super().__init__() self.actions = list(actions) def add(self, *actions): self.actions.extend(actions) def setup(self, *args): self.for_each(lambda action: action.setup(*args)) super().setup(*args) def process(self, event): self.for_each(lambda action: action.process(event._copy())) def for_each(self, func): map(func, self.actions) class IntermediateAction(ActionGroup): def __init__(self): super().__init__() def then(self, *next_actions): self.add(*next_actions) return self def _continue(self, event): super().process(event)
from bot.api.api import Api from bot.storage import Config, State, Cache from bot.utils.dictionaryobject import DictionaryObject class Event(DictionaryObject): pass class Update(Event): def __init__(self, update, is_pending): super().__init__() self.update = update self.is_pending = is_pending class Action: def __init__(self): pass def get_name(self): return self.__class__.__name__ def setup(self, api: Api, config: Config, state: State, cache: Cache): self.api = api self.config = config self.state = state self.cache = cache self.post_setup() def post_setup(self): pass def process(self, event): pass class ActionGroup(Action): def __init__(self, *actions): super().__init__() self.actions = list(actions) def add(self, *actions): self.actions.extend(actions) def setup(self, *args): self.for_each(lambda action: action.setup(*args)) super().setup(*args) def process(self, event): self.for_each(lambda action: action.process(event._copy())) def for_each(self, func): for action in self.actions: func(action) class IntermediateAction(ActionGroup): def __init__(self): super().__init__() def then(self, *next_actions): self.add(*next_actions) return self def _continue(self, event): super().process(event)
Fix for_each incorrectly using lazy map operator
Fix for_each incorrectly using lazy map operator
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
from bot.api.api import Api from bot.storage import Config, State, Cache from bot.utils.dictionaryobject import DictionaryObject class Event(DictionaryObject): pass class Update(Event): def __init__(self, update, is_pending): super().__init__() self.update = update self.is_pending = is_pending class Action: def __init__(self): pass def get_name(self): return self.__class__.__name__ def setup(self, api: Api, config: Config, state: State, cache: Cache): self.api = api self.config = config self.state = state self.cache = cache self.post_setup() def post_setup(self): pass def process(self, event): pass class ActionGroup(Action): def __init__(self, *actions): super().__init__() self.actions = list(actions) def add(self, *actions): self.actions.extend(actions) def setup(self, *args): self.for_each(lambda action: action.setup(*args)) super().setup(*args) def process(self, event): self.for_each(lambda action: action.process(event._copy())) def for_each(self, func): - map(func, self.actions) + for action in self.actions: + func(action) class IntermediateAction(ActionGroup): def __init__(self): super().__init__() def then(self, *next_actions): self.add(*next_actions) return self def _continue(self, event): super().process(event)
Fix for_each incorrectly using lazy map operator
## Code Before: from bot.api.api import Api from bot.storage import Config, State, Cache from bot.utils.dictionaryobject import DictionaryObject class Event(DictionaryObject): pass class Update(Event): def __init__(self, update, is_pending): super().__init__() self.update = update self.is_pending = is_pending class Action: def __init__(self): pass def get_name(self): return self.__class__.__name__ def setup(self, api: Api, config: Config, state: State, cache: Cache): self.api = api self.config = config self.state = state self.cache = cache self.post_setup() def post_setup(self): pass def process(self, event): pass class ActionGroup(Action): def __init__(self, *actions): super().__init__() self.actions = list(actions) def add(self, *actions): self.actions.extend(actions) def setup(self, *args): self.for_each(lambda action: action.setup(*args)) super().setup(*args) def process(self, event): self.for_each(lambda action: action.process(event._copy())) def for_each(self, func): map(func, self.actions) class IntermediateAction(ActionGroup): def __init__(self): super().__init__() def then(self, *next_actions): self.add(*next_actions) return self def _continue(self, event): super().process(event) ## Instruction: Fix for_each incorrectly using lazy map operator ## Code After: from bot.api.api import Api from bot.storage import Config, State, Cache from bot.utils.dictionaryobject import DictionaryObject class Event(DictionaryObject): pass class Update(Event): def __init__(self, update, is_pending): super().__init__() self.update = update self.is_pending = is_pending class Action: def __init__(self): pass def get_name(self): return self.__class__.__name__ def setup(self, api: Api, config: Config, state: State, cache: Cache): self.api = api self.config = config self.state = state self.cache = cache self.post_setup() def post_setup(self): pass def process(self, event): pass class ActionGroup(Action): def __init__(self, *actions): super().__init__() self.actions = list(actions) def add(self, *actions): self.actions.extend(actions) def setup(self, *args): self.for_each(lambda action: action.setup(*args)) super().setup(*args) def process(self, event): self.for_each(lambda action: action.process(event._copy())) def for_each(self, func): for action in self.actions: func(action) class IntermediateAction(ActionGroup): def __init__(self): super().__init__() def then(self, *next_actions): self.add(*next_actions) return self def _continue(self, event): super().process(event)
from bot.api.api import Api from bot.storage import Config, State, Cache from bot.utils.dictionaryobject import DictionaryObject class Event(DictionaryObject): pass class Update(Event): def __init__(self, update, is_pending): super().__init__() self.update = update self.is_pending = is_pending class Action: def __init__(self): pass def get_name(self): return self.__class__.__name__ def setup(self, api: Api, config: Config, state: State, cache: Cache): self.api = api self.config = config self.state = state self.cache = cache self.post_setup() def post_setup(self): pass def process(self, event): pass class ActionGroup(Action): def __init__(self, *actions): super().__init__() self.actions = list(actions) def add(self, *actions): self.actions.extend(actions) def setup(self, *args): self.for_each(lambda action: action.setup(*args)) super().setup(*args) def process(self, event): self.for_each(lambda action: action.process(event._copy())) def for_each(self, func): - map(func, self.actions) + for action in self.actions: + func(action) class IntermediateAction(ActionGroup): def __init__(self): super().__init__() def then(self, *next_actions): self.add(*next_actions) return self def _continue(self, event): super().process(event)
1a5583fdba626059e5481e6099b14b8988316dfe
server/superdesk/locators/__init__.py
server/superdesk/locators/__init__.py
import json import os def _load_json(file_path): """ Reads JSON string from the file located in file_path. :param file_path: path of the file having JSON string. :return: JSON Object """ with open(file_path, 'r') as f: return json.load(f) _dir_name = os.path.dirname(os.path.realpath(__file__)) _locators_file_path = os.path.join(_dir_name, 'data', 'locators.json') locators = _load_json(_locators_file_path)
import json import os def _load_json(file_path): """ Reads JSON string from the file located in file_path. :param file_path: path of the file having JSON string. :return: JSON Object """ with open(file_path, 'r', encoding='utf-8') as f: return json.load(f) _dir_name = os.path.dirname(os.path.realpath(__file__)) _locators_file_path = os.path.join(_dir_name, 'data', 'locators.json') locators = _load_json(_locators_file_path)
Fix locators reading on ubuntu
Fix locators reading on ubuntu
Python
agpl-3.0
thnkloud9/superdesk,superdesk/superdesk,marwoodandrew/superdesk-aap,ancafarcas/superdesk,ioanpocol/superdesk-ntb,gbbr/superdesk,liveblog/superdesk,plamut/superdesk,pavlovicnemanja92/superdesk,akintolga/superdesk,pavlovicnemanja92/superdesk,pavlovicnemanja/superdesk,verifiedpixel/superdesk,amagdas/superdesk,akintolga/superdesk-aap,petrjasek/superdesk,akintolga/superdesk,amagdas/superdesk,darconny/superdesk,plamut/superdesk,mdhaman/superdesk,ioanpocol/superdesk-ntb,marwoodandrew/superdesk,mugurrus/superdesk,plamut/superdesk,Aca-jov/superdesk,gbbr/superdesk,sivakuna-aap/superdesk,Aca-jov/superdesk,marwoodandrew/superdesk,mdhaman/superdesk-aap,petrjasek/superdesk-ntb,mdhaman/superdesk,ioanpocol/superdesk,hlmnrmr/superdesk,plamut/superdesk,verifiedpixel/superdesk,marwoodandrew/superdesk,liveblog/superdesk,superdesk/superdesk,pavlovicnemanja/superdesk,petrjasek/superdesk-ntb,petrjasek/superdesk-ntb,mdhaman/superdesk-aap,ancafarcas/superdesk,mdhaman/superdesk-aap,sivakuna-aap/superdesk,hlmnrmr/superdesk,akintolga/superdesk-aap,marwoodandrew/superdesk-aap,petrjasek/superdesk,superdesk/superdesk-aap,pavlovicnemanja92/superdesk,darconny/superdesk,liveblog/superdesk,superdesk/superdesk,verifiedpixel/superdesk,amagdas/superdesk,petrjasek/superdesk,superdesk/superdesk-ntb,Aca-jov/superdesk,superdesk/superdesk,pavlovicnemanja92/superdesk,akintolga/superdesk,marwoodandrew/superdesk,akintolga/superdesk-aap,fritzSF/superdesk,superdesk/superdesk-aap,superdesk/superdesk-ntb,superdesk/superdesk-ntb,hlmnrmr/superdesk,ioanpocol/superdesk,ioanpocol/superdesk-ntb,fritzSF/superdesk,superdesk/superdesk-ntb,sjunaid/superdesk,pavlovicnemanja/superdesk,sivakuna-aap/superdesk,liveblog/superdesk,amagdas/superdesk,thnkloud9/superdesk,akintolga/superdesk,sjunaid/superdesk,marwoodandrew/superdesk-aap,superdesk/superdesk-aap,sivakuna-aap/superdesk,mdhaman/superdesk,pavlovicnemanja/superdesk,akintolga/superdesk,fritzSF/superdesk,sjunaid/superdesk,verifiedpixel/superdesk,ioanpocol/superdesk,plamut/superdesk,petrjasek/superdesk,mugurrus/superdesk,mdhaman/superdesk-aap,ancafarcas/superdesk,akintolga/superdesk-aap,darconny/superdesk,petrjasek/superdesk-ntb,amagdas/superdesk,sivakuna-aap/superdesk,thnkloud9/superdesk,marwoodandrew/superdesk,verifiedpixel/superdesk,fritzSF/superdesk,marwoodandrew/superdesk-aap,pavlovicnemanja92/superdesk,fritzSF/superdesk,liveblog/superdesk,gbbr/superdesk,superdesk/superdesk-aap,mugurrus/superdesk
import json import os def _load_json(file_path): """ Reads JSON string from the file located in file_path. :param file_path: path of the file having JSON string. :return: JSON Object """ - with open(file_path, 'r') as f: + with open(file_path, 'r', encoding='utf-8') as f: return json.load(f) _dir_name = os.path.dirname(os.path.realpath(__file__)) _locators_file_path = os.path.join(_dir_name, 'data', 'locators.json') locators = _load_json(_locators_file_path)
Fix locators reading on ubuntu
## Code Before: import json import os def _load_json(file_path): """ Reads JSON string from the file located in file_path. :param file_path: path of the file having JSON string. :return: JSON Object """ with open(file_path, 'r') as f: return json.load(f) _dir_name = os.path.dirname(os.path.realpath(__file__)) _locators_file_path = os.path.join(_dir_name, 'data', 'locators.json') locators = _load_json(_locators_file_path) ## Instruction: Fix locators reading on ubuntu ## Code After: import json import os def _load_json(file_path): """ Reads JSON string from the file located in file_path. :param file_path: path of the file having JSON string. :return: JSON Object """ with open(file_path, 'r', encoding='utf-8') as f: return json.load(f) _dir_name = os.path.dirname(os.path.realpath(__file__)) _locators_file_path = os.path.join(_dir_name, 'data', 'locators.json') locators = _load_json(_locators_file_path)
import json import os def _load_json(file_path): """ Reads JSON string from the file located in file_path. :param file_path: path of the file having JSON string. :return: JSON Object """ - with open(file_path, 'r') as f: + with open(file_path, 'r', encoding='utf-8') as f: ? ++++++++++++++++++ return json.load(f) _dir_name = os.path.dirname(os.path.realpath(__file__)) _locators_file_path = os.path.join(_dir_name, 'data', 'locators.json') locators = _load_json(_locators_file_path)
9d0e9af5844772c18ca24d4012642d4518b66dfc
tests/test_judicious.py
tests/test_judicious.py
"""Tests for `judicious` package.""" import pytest import judicious @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string
"""Tests for `judicious` package.""" import random import pytest import judicious def test_seeding(): r1 = random.random() r2 = random.random() judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") r3 = random.random() r4 = random.random() judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") r5 = random.random() r6 = random.random() judicious.seed() r7 = random.random() r8 = random.random() assert(r1 != r3) assert(r2 != r4) assert(r3 == r5) assert(r4 == r6) assert(r5 != r7) assert(r6 != r8) @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string
Add test of seeding PRNG
Add test of seeding PRNG
Python
mit
suchow/judicious,suchow/judicious,suchow/judicious
"""Tests for `judicious` package.""" + import random + import pytest + import judicious - import judicious + + def test_seeding(): + r1 = random.random() + r2 = random.random() + judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") + r3 = random.random() + r4 = random.random() + judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") + r5 = random.random() + r6 = random.random() + judicious.seed() + r7 = random.random() + r8 = random.random() + + assert(r1 != r3) + assert(r2 != r4) + assert(r3 == r5) + assert(r4 == r6) + assert(r5 != r7) + assert(r6 != r8) @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string
Add test of seeding PRNG
## Code Before: """Tests for `judicious` package.""" import pytest import judicious @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string ## Instruction: Add test of seeding PRNG ## Code After: """Tests for `judicious` package.""" import random import pytest import judicious def test_seeding(): r1 = random.random() r2 = random.random() judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") r3 = random.random() r4 = random.random() judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") r5 = random.random() r6 = random.random() judicious.seed() r7 = random.random() r8 = random.random() assert(r1 != r3) assert(r2 != r4) assert(r3 == r5) assert(r4 == r6) assert(r5 != r7) assert(r6 != r8) @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string
"""Tests for `judicious` package.""" + import random + import pytest + import judicious - import judicious + + def test_seeding(): + r1 = random.random() + r2 = random.random() + judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") + r3 = random.random() + r4 = random.random() + judicious.seed("70d911d5-6d93-3c42-f9a4-53e493a79bff") + r5 = random.random() + r6 = random.random() + judicious.seed() + r7 = random.random() + r8 = random.random() + + assert(r1 != r3) + assert(r2 != r4) + assert(r3 == r5) + assert(r4 == r6) + assert(r5 != r7) + assert(r6 != r8) @pytest.fixture def response(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ # import requests # return requests.get('https://github.com/audreyr/cookiecutter-pypackage') def test_content(response): """Sample pytest test function with the pytest fixture as an argument.""" # from bs4 import BeautifulSoup # assert 'GitHub' in BeautifulSoup(response.content).title.string
c7941340336b3fe584dd192583c088eb1f1f972e
genomic_neuralnet/common/celeryconfig.py
genomic_neuralnet/common/celeryconfig.py
BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} # Seconds = 1 hour. # Do not pre-fetch work. CELERYD_PREFETCH_MULTIPLIER = 1 # Do not ack messages until work is completed. CELERY_ACKS_LATE = True # Stop warning me about PICKLE. CELERY_ACCEPT_CONTENT = ['pickle']
BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 60*60} # 60*60 Seconds = 1 hour. # Do not pre-fetch work. CELERYD_PREFETCH_MULTIPLIER = 1 # Do not ack messages until work is completed. CELERY_ACKS_LATE = True # Stop warning me about PICKLE. CELERY_ACCEPT_CONTENT = ['pickle'] # Clear out finished results after 30 minutes. CELERY_TASK_RESULT_EXPIRES = 60*30
Reduce result broker message timeout
Reduce result broker message timeout
Python
mit
rileymcdowell/genomic-neuralnet,rileymcdowell/genomic-neuralnet,rileymcdowell/genomic-neuralnet
- BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} # Seconds = 1 hour. + BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 60*60} # 60*60 Seconds = 1 hour. # Do not pre-fetch work. CELERYD_PREFETCH_MULTIPLIER = 1 # Do not ack messages until work is completed. CELERY_ACKS_LATE = True # Stop warning me about PICKLE. CELERY_ACCEPT_CONTENT = ['pickle'] + # Clear out finished results after 30 minutes. + CELERY_TASK_RESULT_EXPIRES = 60*30 -
Reduce result broker message timeout
## Code Before: BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} # Seconds = 1 hour. # Do not pre-fetch work. CELERYD_PREFETCH_MULTIPLIER = 1 # Do not ack messages until work is completed. CELERY_ACKS_LATE = True # Stop warning me about PICKLE. CELERY_ACCEPT_CONTENT = ['pickle'] ## Instruction: Reduce result broker message timeout ## Code After: BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 60*60} # 60*60 Seconds = 1 hour. # Do not pre-fetch work. CELERYD_PREFETCH_MULTIPLIER = 1 # Do not ack messages until work is completed. CELERY_ACKS_LATE = True # Stop warning me about PICKLE. CELERY_ACCEPT_CONTENT = ['pickle'] # Clear out finished results after 30 minutes. CELERY_TASK_RESULT_EXPIRES = 60*30
- BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} # Seconds = 1 hour. ? - + BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 60*60} # 60*60 Seconds = 1 hour. ? ++ ++++++ # Do not pre-fetch work. CELERYD_PREFETCH_MULTIPLIER = 1 # Do not ack messages until work is completed. CELERY_ACKS_LATE = True # Stop warning me about PICKLE. CELERY_ACCEPT_CONTENT = ['pickle'] - + # Clear out finished results after 30 minutes. + CELERY_TASK_RESULT_EXPIRES = 60*30
ead9192b4c2acb21df917dfe116785343e9a59a6
scripts/patches/transfer.py
scripts/patches/transfer.py
patches = [ { "op": "move", "from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", "value": "String", }, { "op": "move", "from": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/ItemType", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", "value": "String", }, ]
patches = [ { "op": "move", "from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", "value": "String", }, { "op": "move", "from": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/ItemType", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", "value": "String", }, { "op": "move", "from": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/ItemType", "path": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/PrimitiveItemType", }, { "op": "replace", "path": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/PrimitiveItemType", "value": "String", }, ]
Fix spec issue with Transfer::Server ProtocolDetails
Fix spec issue with Transfer::Server ProtocolDetails
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
patches = [ { "op": "move", "from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", "value": "String", }, { "op": "move", "from": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/ItemType", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", "value": "String", }, + { + "op": "move", + "from": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/ItemType", + "path": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/PrimitiveItemType", + }, + { + "op": "replace", + "path": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/PrimitiveItemType", + "value": "String", + }, ]
Fix spec issue with Transfer::Server ProtocolDetails
## Code Before: patches = [ { "op": "move", "from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", "value": "String", }, { "op": "move", "from": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/ItemType", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", "value": "String", }, ] ## Instruction: Fix spec issue with Transfer::Server ProtocolDetails ## Code After: patches = [ { "op": "move", "from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", "value": "String", }, { "op": "move", "from": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/ItemType", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", "value": "String", }, { "op": "move", "from": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/ItemType", "path": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/PrimitiveItemType", }, { "op": "replace", "path": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/PrimitiveItemType", "value": "String", }, ]
patches = [ { "op": "move", "from": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/ItemType", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::Server/Properties/Protocols/PrimitiveItemType", "value": "String", }, { "op": "move", "from": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/ItemType", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", }, { "op": "replace", "path": "/ResourceTypes/AWS::Transfer::User/Properties/SshPublicKeys/PrimitiveItemType", "value": "String", }, + { + "op": "move", + "from": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/ItemType", + "path": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/PrimitiveItemType", + }, + { + "op": "replace", + "path": "/PropertyTypes/AWS::Transfer::Server.ProtocolDetails/Properties/As2Transports/PrimitiveItemType", + "value": "String", + }, ]
febb5d9890b074985ca99f05c5b8ffc2572d2652
apps/posters/forms.py
apps/posters/forms.py
from django import forms from apps.posters.models import Poster class AddPosterForm(forms.ModelForm): when = forms.CharField(label=u"Event start", widget=forms.TextInput(attrs={'type': 'datetime-local'})) display_from = forms.CharField(label=u"Vis plakat fra", widget=forms.TextInput(attrs={'type': 'date'})) display_to = forms.CharField(label=u"Vis plakat til", widget=forms.TextInput(attrs={'type': 'date'})) class Meta: model = Poster fields = ['event', 'amount', 'description', 'price', 'display_from', 'display_to', 'comments'] class EditPosterForm(forms.ModelForm): class Meta: model = Poster fields = ['event', 'amount', 'description', 'price', 'display_to', 'display_from', 'comments', 'finished']
from django import forms from apps.posters.models import Poster class AddPosterForm(forms.ModelForm): display_from = forms.CharField(label=u"Vis plakat fra", widget=forms.TextInput(attrs={'type': 'date'})) display_to = forms.CharField(label=u"Vis plakat til", widget=forms.TextInput(attrs={'type': 'date'})) class Meta: model = Poster fields = ['event', 'amount', 'description', 'price', 'display_from', 'display_to', 'comments'] class EditPosterForm(forms.ModelForm): class Meta: model = Poster fields = ['event', 'amount', 'description', 'price', 'display_to', 'display_from', 'comments', 'finished']
Remove event start field from form
Remove event start field from form
Python
mit
dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4
from django import forms from apps.posters.models import Poster class AddPosterForm(forms.ModelForm): - when = forms.CharField(label=u"Event start", widget=forms.TextInput(attrs={'type': 'datetime-local'})) display_from = forms.CharField(label=u"Vis plakat fra", widget=forms.TextInput(attrs={'type': 'date'})) display_to = forms.CharField(label=u"Vis plakat til", widget=forms.TextInput(attrs={'type': 'date'})) class Meta: model = Poster fields = ['event', 'amount', 'description', 'price', 'display_from', 'display_to', 'comments'] class EditPosterForm(forms.ModelForm): class Meta: model = Poster fields = ['event', 'amount', 'description', 'price', 'display_to', 'display_from', 'comments', 'finished']
Remove event start field from form
## Code Before: from django import forms from apps.posters.models import Poster class AddPosterForm(forms.ModelForm): when = forms.CharField(label=u"Event start", widget=forms.TextInput(attrs={'type': 'datetime-local'})) display_from = forms.CharField(label=u"Vis plakat fra", widget=forms.TextInput(attrs={'type': 'date'})) display_to = forms.CharField(label=u"Vis plakat til", widget=forms.TextInput(attrs={'type': 'date'})) class Meta: model = Poster fields = ['event', 'amount', 'description', 'price', 'display_from', 'display_to', 'comments'] class EditPosterForm(forms.ModelForm): class Meta: model = Poster fields = ['event', 'amount', 'description', 'price', 'display_to', 'display_from', 'comments', 'finished'] ## Instruction: Remove event start field from form ## Code After: from django import forms from apps.posters.models import Poster class AddPosterForm(forms.ModelForm): display_from = forms.CharField(label=u"Vis plakat fra", widget=forms.TextInput(attrs={'type': 'date'})) display_to = forms.CharField(label=u"Vis plakat til", widget=forms.TextInput(attrs={'type': 'date'})) class Meta: model = Poster fields = ['event', 'amount', 'description', 'price', 'display_from', 'display_to', 'comments'] class EditPosterForm(forms.ModelForm): class Meta: model = Poster fields = ['event', 'amount', 'description', 'price', 'display_to', 'display_from', 'comments', 'finished']
from django import forms from apps.posters.models import Poster class AddPosterForm(forms.ModelForm): - when = forms.CharField(label=u"Event start", widget=forms.TextInput(attrs={'type': 'datetime-local'})) display_from = forms.CharField(label=u"Vis plakat fra", widget=forms.TextInput(attrs={'type': 'date'})) display_to = forms.CharField(label=u"Vis plakat til", widget=forms.TextInput(attrs={'type': 'date'})) class Meta: model = Poster fields = ['event', 'amount', 'description', 'price', 'display_from', 'display_to', 'comments'] class EditPosterForm(forms.ModelForm): class Meta: model = Poster fields = ['event', 'amount', 'description', 'price', 'display_to', 'display_from', 'comments', 'finished']
9581334db472c8ad8dbff0766ec74ed6dfa20d6f
tests/test_api_request.py
tests/test_api_request.py
from binance.client import Client from binance.exceptions import BinanceAPIException, BinanceRequestException import pytest import requests_mock client = Client('api_key', 'api_secret') def test_invalid_json(): """Test Invalid response Exception""" with pytest.raises(BinanceRequestException): with requests_mock.mock() as m: m.get('https://www.binance.com/exchange/public/product', text='<head></html>') client.get_products() def test_api_exception(): """Test API response Exception""" with pytest.raises(BinanceAPIException): with requests_mock.mock() as m: json_obj = {"code": 1002, "msg": "Invalid API call"} m.get('https://www.binance.com/api/v1/time', json=json_obj, status_code=400) client.get_server_time()
from binance.client import Client from binance.exceptions import BinanceAPIException, BinanceRequestException, BinanceWithdrawException import pytest import requests_mock client = Client('api_key', 'api_secret') def test_invalid_json(): """Test Invalid response Exception""" with pytest.raises(BinanceRequestException): with requests_mock.mock() as m: m.get('https://www.binance.com/exchange/public/product', text='<head></html>') client.get_products() def test_api_exception(): """Test API response Exception""" with pytest.raises(BinanceAPIException): with requests_mock.mock() as m: json_obj = {"code": 1002, "msg": "Invalid API call"} m.get('https://www.binance.com/api/v1/time', json=json_obj, status_code=400) client.get_server_time() def test_withdraw_api_exception(): """Test Withdraw API response Exception""" with pytest.raises(BinanceWithdrawException): with requests_mock.mock() as m: json_obj = {"success": False, "msg": "Insufficient funds"} m.register_uri('POST', requests_mock.ANY, json=json_obj, status_code=200) client.withdraw(asset='BTC', address='BTCADDRESS', amount=100)
Add test for withdraw exception response
Add test for withdraw exception response
Python
mit
sammchardy/python-binance
from binance.client import Client - from binance.exceptions import BinanceAPIException, BinanceRequestException + from binance.exceptions import BinanceAPIException, BinanceRequestException, BinanceWithdrawException import pytest import requests_mock client = Client('api_key', 'api_secret') def test_invalid_json(): """Test Invalid response Exception""" with pytest.raises(BinanceRequestException): with requests_mock.mock() as m: m.get('https://www.binance.com/exchange/public/product', text='<head></html>') client.get_products() def test_api_exception(): """Test API response Exception""" with pytest.raises(BinanceAPIException): with requests_mock.mock() as m: json_obj = {"code": 1002, "msg": "Invalid API call"} m.get('https://www.binance.com/api/v1/time', json=json_obj, status_code=400) client.get_server_time() + + def test_withdraw_api_exception(): + """Test Withdraw API response Exception""" + + with pytest.raises(BinanceWithdrawException): + + with requests_mock.mock() as m: + json_obj = {"success": False, "msg": "Insufficient funds"} + m.register_uri('POST', requests_mock.ANY, json=json_obj, status_code=200) + client.withdraw(asset='BTC', address='BTCADDRESS', amount=100) +
Add test for withdraw exception response
## Code Before: from binance.client import Client from binance.exceptions import BinanceAPIException, BinanceRequestException import pytest import requests_mock client = Client('api_key', 'api_secret') def test_invalid_json(): """Test Invalid response Exception""" with pytest.raises(BinanceRequestException): with requests_mock.mock() as m: m.get('https://www.binance.com/exchange/public/product', text='<head></html>') client.get_products() def test_api_exception(): """Test API response Exception""" with pytest.raises(BinanceAPIException): with requests_mock.mock() as m: json_obj = {"code": 1002, "msg": "Invalid API call"} m.get('https://www.binance.com/api/v1/time', json=json_obj, status_code=400) client.get_server_time() ## Instruction: Add test for withdraw exception response ## Code After: from binance.client import Client from binance.exceptions import BinanceAPIException, BinanceRequestException, BinanceWithdrawException import pytest import requests_mock client = Client('api_key', 'api_secret') def test_invalid_json(): """Test Invalid response Exception""" with pytest.raises(BinanceRequestException): with requests_mock.mock() as m: m.get('https://www.binance.com/exchange/public/product', text='<head></html>') client.get_products() def test_api_exception(): """Test API response Exception""" with pytest.raises(BinanceAPIException): with requests_mock.mock() as m: json_obj = {"code": 1002, "msg": "Invalid API call"} m.get('https://www.binance.com/api/v1/time', json=json_obj, status_code=400) client.get_server_time() def test_withdraw_api_exception(): """Test Withdraw API response Exception""" with pytest.raises(BinanceWithdrawException): with requests_mock.mock() as m: json_obj = {"success": False, "msg": "Insufficient funds"} m.register_uri('POST', requests_mock.ANY, json=json_obj, status_code=200) client.withdraw(asset='BTC', address='BTCADDRESS', amount=100)
from binance.client import Client - from binance.exceptions import BinanceAPIException, BinanceRequestException + from binance.exceptions import BinanceAPIException, BinanceRequestException, BinanceWithdrawException ? ++++++++++++++++++++++++++ import pytest import requests_mock client = Client('api_key', 'api_secret') def test_invalid_json(): """Test Invalid response Exception""" with pytest.raises(BinanceRequestException): with requests_mock.mock() as m: m.get('https://www.binance.com/exchange/public/product', text='<head></html>') client.get_products() def test_api_exception(): """Test API response Exception""" with pytest.raises(BinanceAPIException): with requests_mock.mock() as m: json_obj = {"code": 1002, "msg": "Invalid API call"} m.get('https://www.binance.com/api/v1/time', json=json_obj, status_code=400) client.get_server_time() + + + def test_withdraw_api_exception(): + """Test Withdraw API response Exception""" + + with pytest.raises(BinanceWithdrawException): + + with requests_mock.mock() as m: + json_obj = {"success": False, "msg": "Insufficient funds"} + m.register_uri('POST', requests_mock.ANY, json=json_obj, status_code=200) + client.withdraw(asset='BTC', address='BTCADDRESS', amount=100)
093202349a971ba20982976f464853e657ea3237
tests/test_cli.py
tests/test_cli.py
from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import pytest from twine import cli def test_catches_enoent(): with pytest.raises(SystemExit): cli.dispatch(["non-existant-command"])
from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import pretend import pytest from twine import cli import twine.commands.upload def test_dispatch_to_subcommand(monkeypatch): replaced_main = pretend.call_recorder(lambda args: None) monkeypatch.setattr(twine.commands.upload, "main", replaced_main) cli.dispatch(["upload", "path/to/file"]) assert replaced_main.calls == [pretend.call(["path/to/file"])] def test_catches_enoent(): with pytest.raises(SystemExit): cli.dispatch(["non-existant-command"])
Add test for upload functionality
Add test for upload functionality
Python
apache-2.0
beni55/twine,dstufft/twine,jamesblunt/twine,mhils/twine,sigmavirus24/twine,pypa/twine,warner/twine,reinout/twine
from __future__ import absolute_import, division, print_function from __future__ import unicode_literals + import pretend import pytest from twine import cli + import twine.commands.upload + + + def test_dispatch_to_subcommand(monkeypatch): + replaced_main = pretend.call_recorder(lambda args: None) + monkeypatch.setattr(twine.commands.upload, "main", replaced_main) + + cli.dispatch(["upload", "path/to/file"]) + + assert replaced_main.calls == [pretend.call(["path/to/file"])] def test_catches_enoent(): with pytest.raises(SystemExit): cli.dispatch(["non-existant-command"])
Add test for upload functionality
## Code Before: from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import pytest from twine import cli def test_catches_enoent(): with pytest.raises(SystemExit): cli.dispatch(["non-existant-command"]) ## Instruction: Add test for upload functionality ## Code After: from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import pretend import pytest from twine import cli import twine.commands.upload def test_dispatch_to_subcommand(monkeypatch): replaced_main = pretend.call_recorder(lambda args: None) monkeypatch.setattr(twine.commands.upload, "main", replaced_main) cli.dispatch(["upload", "path/to/file"]) assert replaced_main.calls == [pretend.call(["path/to/file"])] def test_catches_enoent(): with pytest.raises(SystemExit): cli.dispatch(["non-existant-command"])
from __future__ import absolute_import, division, print_function from __future__ import unicode_literals + import pretend import pytest from twine import cli + import twine.commands.upload + + + def test_dispatch_to_subcommand(monkeypatch): + replaced_main = pretend.call_recorder(lambda args: None) + monkeypatch.setattr(twine.commands.upload, "main", replaced_main) + + cli.dispatch(["upload", "path/to/file"]) + + assert replaced_main.calls == [pretend.call(["path/to/file"])] def test_catches_enoent(): with pytest.raises(SystemExit): cli.dispatch(["non-existant-command"])
6319303c93af973718c5e26c4d6b1d47310ff804
install_deps.py
install_deps.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) return install_deps if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: if dep_name == 'None': continue cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name))
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) return [dep for dep in install_deps if dep != 'None'] if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name))
Correct for None appearing in requirements list
Correct for None appearing in requirements list
Python
bsd-3-clause
Neurita/galton
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) - return install_deps + return [dep for dep in install_deps if dep != 'None'] if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: - if dep_name == 'None': - continue - cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name))
Correct for None appearing in requirements list
## Code Before: from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) return install_deps if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: if dep_name == 'None': continue cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name)) ## Instruction: Correct for None appearing in requirements list ## Code After: from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) return [dep for dep in install_deps if dep != 'None'] if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name))
from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements def get_requirements(*args): """Parse all requirements files given and return a list of the dependencies""" install_deps = [] try: for fpath in args: install_deps.extend([str(d.req) for d in parse_requirements(fpath)]) except: print('Error reading {} file looking for dependencies.'.format(fpath)) - return install_deps + return [dep for dep in install_deps if dep != 'None'] if __name__ == '__main__': for line in fileinput.input(): req_filepaths = sys.argv[1:] deps = get_requirements(*req_filepaths) try: for dep_name in deps: - if dep_name == 'None': - continue - cmd = "pip install {0}".format(dep_name) print('#', cmd) subprocess.check_call(cmd, shell=True) except: print('Error installing {}'.format(dep_name))
5596f599287d36126b3a6e30e7579eb00ed07d73
downstream_farmer/utils.py
downstream_farmer/utils.py
try: from urllib import quote_plus except ImportError: from urllib.parse import quote_plus def urlify(string): """ You might be wondering: why is this here at all, since it's basically doing exactly what the quote_plus function in urllib does. Well, to keep the 2 & 3 stuff all in one place, meaning rather than try to import the urllib stuff twice in each file where url-safe strings are needed, we keep it all in one file: here. Supporting multiple Pythons is hard. :param string: String to URLify :return: URLified string """ return quote_plus(string)
try: from urllib import quote except ImportError: from urllib.parse import quote def urlify(string): """ You might be wondering: why is this here at all, since it's basically doing exactly what the quote_plus function in urllib does. Well, to keep the 2 & 3 stuff all in one place, meaning rather than try to import the urllib stuff twice in each file where url-safe strings are needed, we keep it all in one file: here. Supporting multiple Pythons is hard. :param string: String to URLify :return: URLified string """ return quote(string)
Fix method to use quote, not quote_plus
Fix method to use quote, not quote_plus
Python
mit
Storj/downstream-farmer
try: - from urllib import quote_plus + from urllib import quote except ImportError: - from urllib.parse import quote_plus + from urllib.parse import quote def urlify(string): """ You might be wondering: why is this here at all, since it's basically doing exactly what the quote_plus function in urllib does. Well, to keep the 2 & 3 stuff all in one place, meaning rather than try to import the urllib stuff twice in each file where url-safe strings are needed, we keep it all in one file: here. Supporting multiple Pythons is hard. :param string: String to URLify :return: URLified string """ - return quote_plus(string) + return quote(string)
Fix method to use quote, not quote_plus
## Code Before: try: from urllib import quote_plus except ImportError: from urllib.parse import quote_plus def urlify(string): """ You might be wondering: why is this here at all, since it's basically doing exactly what the quote_plus function in urllib does. Well, to keep the 2 & 3 stuff all in one place, meaning rather than try to import the urllib stuff twice in each file where url-safe strings are needed, we keep it all in one file: here. Supporting multiple Pythons is hard. :param string: String to URLify :return: URLified string """ return quote_plus(string) ## Instruction: Fix method to use quote, not quote_plus ## Code After: try: from urllib import quote except ImportError: from urllib.parse import quote def urlify(string): """ You might be wondering: why is this here at all, since it's basically doing exactly what the quote_plus function in urllib does. Well, to keep the 2 & 3 stuff all in one place, meaning rather than try to import the urllib stuff twice in each file where url-safe strings are needed, we keep it all in one file: here. Supporting multiple Pythons is hard. :param string: String to URLify :return: URLified string """ return quote(string)
try: - from urllib import quote_plus ? ----- + from urllib import quote except ImportError: - from urllib.parse import quote_plus ? ----- + from urllib.parse import quote def urlify(string): """ You might be wondering: why is this here at all, since it's basically doing exactly what the quote_plus function in urllib does. Well, to keep the 2 & 3 stuff all in one place, meaning rather than try to import the urllib stuff twice in each file where url-safe strings are needed, we keep it all in one file: here. Supporting multiple Pythons is hard. :param string: String to URLify :return: URLified string """ - return quote_plus(string) ? ----- + return quote(string)
574dd4ef0aa0d6381938a0638e497374434cb75e
lilkv/columnfamily.py
lilkv/columnfamily.py
class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily_purchases") """ def __init__(self, name, data_dir='data'): self.name = name self.ROWS = set() def insert(self, column): return self._insert(column) def delete(self, column): column.tombstone = True return self._insert(column) def get(self, key): # NOTE: Check for tombstones / TTL here pass def _insert(self, column): try: self.ROWS.add(column) return True except: return False def __repr__(self): return '<%r>' % self.name
class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily_purchases") """ def __init__(self, name, data_dir='data'): self.name = name # A row consists of: # {'rowkey': [col1, col2, col3]} self.ROWS = dict() def insert(self, column): return self._insert(column) def delete(self, column): column.tombstone = True return self._insert(column) def get(self, key): # NOTE: Check for tombstones / TTL here pass def _insert(self, column): try: self.ROWS[column.row_key].append(column) return True except KeyError: # Key doesn't exist self.ROWS[column.row_key] = [column] except: return False def __repr__(self): return '<%r>' % self.name
Store rows as dictionaries of lists.
Store rows as dictionaries of lists.
Python
mit
pgorla/lil-kv
class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily_purchases") """ def __init__(self, name, data_dir='data'): self.name = name + # A row consists of: + # {'rowkey': [col1, col2, col3]} - self.ROWS = set() + self.ROWS = dict() def insert(self, column): return self._insert(column) def delete(self, column): column.tombstone = True return self._insert(column) def get(self, key): # NOTE: Check for tombstones / TTL here pass def _insert(self, column): try: - self.ROWS.add(column) + self.ROWS[column.row_key].append(column) return True + except KeyError: # Key doesn't exist + self.ROWS[column.row_key] = [column] except: return False def __repr__(self): return '<%r>' % self.name
Store rows as dictionaries of lists.
## Code Before: class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily_purchases") """ def __init__(self, name, data_dir='data'): self.name = name self.ROWS = set() def insert(self, column): return self._insert(column) def delete(self, column): column.tombstone = True return self._insert(column) def get(self, key): # NOTE: Check for tombstones / TTL here pass def _insert(self, column): try: self.ROWS.add(column) return True except: return False def __repr__(self): return '<%r>' % self.name ## Instruction: Store rows as dictionaries of lists. ## Code After: class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily_purchases") """ def __init__(self, name, data_dir='data'): self.name = name # A row consists of: # {'rowkey': [col1, col2, col3]} self.ROWS = dict() def insert(self, column): return self._insert(column) def delete(self, column): column.tombstone = True return self._insert(column) def get(self, key): # NOTE: Check for tombstones / TTL here pass def _insert(self, column): try: self.ROWS[column.row_key].append(column) return True except KeyError: # Key doesn't exist self.ROWS[column.row_key] = [column] except: return False def __repr__(self): return '<%r>' % self.name
class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily_purchases") """ def __init__(self, name, data_dir='data'): self.name = name + # A row consists of: + # {'rowkey': [col1, col2, col3]} - self.ROWS = set() ? ^^ + self.ROWS = dict() ? ^^^ def insert(self, column): return self._insert(column) def delete(self, column): column.tombstone = True return self._insert(column) def get(self, key): # NOTE: Check for tombstones / TTL here pass def _insert(self, column): try: - self.ROWS.add(column) ? ^ + self.ROWS[column.row_key].append(column) ? ++++++++++++++++ ^^^^ return True + except KeyError: # Key doesn't exist + self.ROWS[column.row_key] = [column] except: return False def __repr__(self): return '<%r>' % self.name
02f77babc6195426fdb5c495d44ede6af6fbec8f
mangopaysdk/entities/userlegal.py
mangopaysdk/entities/userlegal.py
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonType(PersonType.Legal) self.Name = None # Required LegalPersonType: BUSINESS, ORGANIZATION self.LegalPersonType = None self.HeadquartersAddress = None # Required self.LegalRepresentativeFirstName = None # Required self.LegalRepresentativeLastName = None self.LegalRepresentativeAddress = None self.LegalRepresentativeEmail = None # Required self.LegalRepresentativeBirthday = None # Required self.LegalRepresentativeNationality = None # Required self.LegalRepresentativeCountryOfResidence = None self._statute = None self._proofOfRegistration = None self._shareholderDeclaration = None def GetReadOnlyProperties(self): properties = super(UserLegal, self).GetReadOnlyProperties() properties.append('Statute' ) properties.append('ProofOfRegistration' ) properties.append('ShareholderDeclaration' ) return properties
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonType(PersonType.Legal) self.Name = None # Required LegalPersonType: BUSINESS, ORGANIZATION self.LegalPersonType = None self.HeadquartersAddress = None # Required self.LegalRepresentativeFirstName = None # Required self.LegalRepresentativeLastName = None self.LegalRepresentativeAddress = None self.LegalRepresentativeEmail = None # Required self.LegalRepresentativeBirthday = None # Required self.LegalRepresentativeNationality = None # Required self.LegalRepresentativeCountryOfResidence = None self._statute = None self._proofOfRegistration = None self._shareholderDeclaration = None self._legalRepresentativeProofOfIdentity = None def GetReadOnlyProperties(self): properties = super(UserLegal, self).GetReadOnlyProperties() properties.append('Statute' ) properties.append('ProofOfRegistration' ) properties.append('ShareholderDeclaration' ) properties.append('LegalRepresentativeProofOfIdentity' ) return properties
Add LegalRepresentativeProofOfIdentity to legal user
Add LegalRepresentativeProofOfIdentity to legal user
Python
mit
chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonType(PersonType.Legal) self.Name = None # Required LegalPersonType: BUSINESS, ORGANIZATION self.LegalPersonType = None self.HeadquartersAddress = None # Required self.LegalRepresentativeFirstName = None # Required self.LegalRepresentativeLastName = None self.LegalRepresentativeAddress = None self.LegalRepresentativeEmail = None # Required self.LegalRepresentativeBirthday = None # Required self.LegalRepresentativeNationality = None # Required self.LegalRepresentativeCountryOfResidence = None self._statute = None self._proofOfRegistration = None self._shareholderDeclaration = None + self._legalRepresentativeProofOfIdentity = None def GetReadOnlyProperties(self): properties = super(UserLegal, self).GetReadOnlyProperties() properties.append('Statute' ) properties.append('ProofOfRegistration' ) - properties.append('ShareholderDeclaration' ) + properties.append('ShareholderDeclaration' ) + properties.append('LegalRepresentativeProofOfIdentity' ) return properties
Add LegalRepresentativeProofOfIdentity to legal user
## Code Before: from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonType(PersonType.Legal) self.Name = None # Required LegalPersonType: BUSINESS, ORGANIZATION self.LegalPersonType = None self.HeadquartersAddress = None # Required self.LegalRepresentativeFirstName = None # Required self.LegalRepresentativeLastName = None self.LegalRepresentativeAddress = None self.LegalRepresentativeEmail = None # Required self.LegalRepresentativeBirthday = None # Required self.LegalRepresentativeNationality = None # Required self.LegalRepresentativeCountryOfResidence = None self._statute = None self._proofOfRegistration = None self._shareholderDeclaration = None def GetReadOnlyProperties(self): properties = super(UserLegal, self).GetReadOnlyProperties() properties.append('Statute' ) properties.append('ProofOfRegistration' ) properties.append('ShareholderDeclaration' ) return properties ## Instruction: Add LegalRepresentativeProofOfIdentity to legal user ## Code After: from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonType(PersonType.Legal) self.Name = None # Required LegalPersonType: BUSINESS, ORGANIZATION self.LegalPersonType = None self.HeadquartersAddress = None # Required self.LegalRepresentativeFirstName = None # Required self.LegalRepresentativeLastName = None self.LegalRepresentativeAddress = None self.LegalRepresentativeEmail = None # Required self.LegalRepresentativeBirthday = None # Required self.LegalRepresentativeNationality = None # Required self.LegalRepresentativeCountryOfResidence = None self._statute = None self._proofOfRegistration = None self._shareholderDeclaration = None self._legalRepresentativeProofOfIdentity = None def GetReadOnlyProperties(self): properties = super(UserLegal, self).GetReadOnlyProperties() properties.append('Statute' ) properties.append('ProofOfRegistration' ) properties.append('ShareholderDeclaration' ) properties.append('LegalRepresentativeProofOfIdentity' ) return properties
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.entities.user import User from mangopaysdk.tools.enums import PersonType from mangopaysdk.tools.enums import KYCLevel class UserLegal (User): def __init__(self, id = None): super(UserLegal, self).__init__(id) self._setPersonType(PersonType.Legal) self.Name = None # Required LegalPersonType: BUSINESS, ORGANIZATION self.LegalPersonType = None self.HeadquartersAddress = None # Required self.LegalRepresentativeFirstName = None # Required self.LegalRepresentativeLastName = None self.LegalRepresentativeAddress = None self.LegalRepresentativeEmail = None # Required self.LegalRepresentativeBirthday = None # Required self.LegalRepresentativeNationality = None # Required self.LegalRepresentativeCountryOfResidence = None self._statute = None self._proofOfRegistration = None self._shareholderDeclaration = None + self._legalRepresentativeProofOfIdentity = None def GetReadOnlyProperties(self): properties = super(UserLegal, self).GetReadOnlyProperties() properties.append('Statute' ) properties.append('ProofOfRegistration' ) - properties.append('ShareholderDeclaration' ) ? --- + properties.append('ShareholderDeclaration' ) + properties.append('LegalRepresentativeProofOfIdentity' ) return properties
5651445944bce163a2c3f746d6ac1acd9ae76032
numpy/array_api/tests/test_asarray.py
numpy/array_api/tests/test_asarray.py
import numpy as np def test_fast_return(): """""" a = np.array([1, 2, 3], dtype='i') assert np.asarray(a) is a assert np.asarray(a, dtype='i') is a # This may produce a new view or a copy, but is never the same object. assert np.asarray(a, dtype='l') is not a unequal_type = np.dtype('i', metadata={'spam': True}) b = np.asarray(a, dtype=unequal_type) assert b is not a assert b.base is a equivalent_requirement = np.dtype('i', metadata={'spam': True}) c = np.asarray(b, dtype=equivalent_requirement) # A quirk of the metadata test is that equivalent metadata dicts are still # separate objects and so don't evaluate as the same array type description. assert unequal_type == equivalent_requirement assert unequal_type is not equivalent_requirement assert c is not b assert c.dtype is equivalent_requirement
import numpy as np def test_fast_return(): """""" a = np.array([1, 2, 3], dtype='i') assert np.asarray(a) is a assert np.asarray(a, dtype='i') is a # This may produce a new view or a copy, but is never the same object. assert np.asarray(a, dtype='l') is not a unequal_type = np.dtype('i', metadata={'spam': True}) b = np.asarray(a, dtype=unequal_type) assert b is not a assert b.base is a equivalent_requirement = np.dtype('i', metadata={'spam': True}) c = np.asarray(b, dtype=equivalent_requirement) # The descriptors are equivalent, but we have created # distinct dtype instances. assert unequal_type == equivalent_requirement assert unequal_type is not equivalent_requirement assert c is not b assert c.dtype is equivalent_requirement
Update comment and obey formatting requirements.
Update comment and obey formatting requirements.
Python
bsd-3-clause
charris/numpy,mhvk/numpy,mattip/numpy,mattip/numpy,mattip/numpy,numpy/numpy,mhvk/numpy,endolith/numpy,charris/numpy,numpy/numpy,endolith/numpy,charris/numpy,numpy/numpy,endolith/numpy,endolith/numpy,charris/numpy,mattip/numpy,numpy/numpy,mhvk/numpy,mhvk/numpy,mhvk/numpy
import numpy as np def test_fast_return(): """""" a = np.array([1, 2, 3], dtype='i') assert np.asarray(a) is a assert np.asarray(a, dtype='i') is a # This may produce a new view or a copy, but is never the same object. assert np.asarray(a, dtype='l') is not a unequal_type = np.dtype('i', metadata={'spam': True}) b = np.asarray(a, dtype=unequal_type) assert b is not a assert b.base is a equivalent_requirement = np.dtype('i', metadata={'spam': True}) c = np.asarray(b, dtype=equivalent_requirement) - # A quirk of the metadata test is that equivalent metadata dicts are still - # separate objects and so don't evaluate as the same array type description. + # The descriptors are equivalent, but we have created + # distinct dtype instances. assert unequal_type == equivalent_requirement assert unequal_type is not equivalent_requirement assert c is not b assert c.dtype is equivalent_requirement
Update comment and obey formatting requirements.
## Code Before: import numpy as np def test_fast_return(): """""" a = np.array([1, 2, 3], dtype='i') assert np.asarray(a) is a assert np.asarray(a, dtype='i') is a # This may produce a new view or a copy, but is never the same object. assert np.asarray(a, dtype='l') is not a unequal_type = np.dtype('i', metadata={'spam': True}) b = np.asarray(a, dtype=unequal_type) assert b is not a assert b.base is a equivalent_requirement = np.dtype('i', metadata={'spam': True}) c = np.asarray(b, dtype=equivalent_requirement) # A quirk of the metadata test is that equivalent metadata dicts are still # separate objects and so don't evaluate as the same array type description. assert unequal_type == equivalent_requirement assert unequal_type is not equivalent_requirement assert c is not b assert c.dtype is equivalent_requirement ## Instruction: Update comment and obey formatting requirements. ## Code After: import numpy as np def test_fast_return(): """""" a = np.array([1, 2, 3], dtype='i') assert np.asarray(a) is a assert np.asarray(a, dtype='i') is a # This may produce a new view or a copy, but is never the same object. assert np.asarray(a, dtype='l') is not a unequal_type = np.dtype('i', metadata={'spam': True}) b = np.asarray(a, dtype=unequal_type) assert b is not a assert b.base is a equivalent_requirement = np.dtype('i', metadata={'spam': True}) c = np.asarray(b, dtype=equivalent_requirement) # The descriptors are equivalent, but we have created # distinct dtype instances. assert unequal_type == equivalent_requirement assert unequal_type is not equivalent_requirement assert c is not b assert c.dtype is equivalent_requirement
import numpy as np def test_fast_return(): """""" a = np.array([1, 2, 3], dtype='i') assert np.asarray(a) is a assert np.asarray(a, dtype='i') is a # This may produce a new view or a copy, but is never the same object. assert np.asarray(a, dtype='l') is not a unequal_type = np.dtype('i', metadata={'spam': True}) b = np.asarray(a, dtype=unequal_type) assert b is not a assert b.base is a equivalent_requirement = np.dtype('i', metadata={'spam': True}) c = np.asarray(b, dtype=equivalent_requirement) - # A quirk of the metadata test is that equivalent metadata dicts are still - # separate objects and so don't evaluate as the same array type description. + # The descriptors are equivalent, but we have created + # distinct dtype instances. assert unequal_type == equivalent_requirement assert unequal_type is not equivalent_requirement assert c is not b assert c.dtype is equivalent_requirement
cf58ebf492cd0dfaf640d2fd8d3cf4e5b2706424
alembic/versions/47dd43c1491_create_category_tabl.py
alembic/versions/47dd43c1491_create_category_tabl.py
# revision identifiers, used by Alembic. revision = '47dd43c1491' down_revision = '27bf0aefa49d' from alembic import op import sqlalchemy as sa import datetime def make_timestamp(): now = datetime.datetime.utcnow() return now.isoformat() def upgrade(): op.create_table( 'category', sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.Text, nullable=False, unique=True), sa.Column('short_name', sa.Text, nullable=False, unique=True), sa.Column('created', sa.Text, default=make_timestamp), ) def downgrade(): op.drop_table('category')
# revision identifiers, used by Alembic. revision = '47dd43c1491' down_revision = '27bf0aefa49d' from alembic import op import sqlalchemy as sa import datetime def make_timestamp(): now = datetime.datetime.utcnow() return now.isoformat() def upgrade(): op.create_table( 'category', sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.Text, nullable=False, unique=True), sa.Column('short_name', sa.Text, nullable=False, unique=True), sa.Column('description', sa.Text, nullable=False), sa.Column('created', sa.Text, default=make_timestamp), ) # Add two categories query = 'INSERT INTO category (name, short_name, description) VALUES (\'Thinking\', \'thinking\', \'Applications where you can help using your skills\')' op.execute(query) query = 'INSERT INTO category (name, short_name, description) VALUES (\'Sensing\', \'sensing\', \'Applications where you can help gathering data\')' op.execute(query) def downgrade(): op.drop_table('category')
Add description to the table and populate it with two categories
Add description to the table and populate it with two categories
Python
agpl-3.0
geotagx/geotagx-pybossa-archive,OpenNewsLabs/pybossa,PyBossa/pybossa,proyectos-analizo-info/pybossa-analizo-info,Scifabric/pybossa,CulturePlex/pybossa,geotagx/pybossa,proyectos-analizo-info/pybossa-analizo-info,CulturePlex/pybossa,OpenNewsLabs/pybossa,geotagx/geotagx-pybossa-archive,harihpr/tweetclickers,geotagx/geotagx-pybossa-archive,PyBossa/pybossa,geotagx/pybossa,harihpr/tweetclickers,stefanhahmann/pybossa,stefanhahmann/pybossa,inteligencia-coletiva-lsd/pybossa,proyectos-analizo-info/pybossa-analizo-info,Scifabric/pybossa,jean/pybossa,inteligencia-coletiva-lsd/pybossa,jean/pybossa,CulturePlex/pybossa,geotagx/geotagx-pybossa-archive,geotagx/geotagx-pybossa-archive
# revision identifiers, used by Alembic. revision = '47dd43c1491' down_revision = '27bf0aefa49d' from alembic import op import sqlalchemy as sa import datetime def make_timestamp(): now = datetime.datetime.utcnow() return now.isoformat() def upgrade(): op.create_table( 'category', sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.Text, nullable=False, unique=True), sa.Column('short_name', sa.Text, nullable=False, unique=True), + sa.Column('description', sa.Text, nullable=False), sa.Column('created', sa.Text, default=make_timestamp), ) + + # Add two categories + query = 'INSERT INTO category (name, short_name, description) VALUES (\'Thinking\', \'thinking\', \'Applications where you can help using your skills\')' + op.execute(query) + query = 'INSERT INTO category (name, short_name, description) VALUES (\'Sensing\', \'sensing\', \'Applications where you can help gathering data\')' + op.execute(query) def downgrade(): op.drop_table('category')
Add description to the table and populate it with two categories
## Code Before: # revision identifiers, used by Alembic. revision = '47dd43c1491' down_revision = '27bf0aefa49d' from alembic import op import sqlalchemy as sa import datetime def make_timestamp(): now = datetime.datetime.utcnow() return now.isoformat() def upgrade(): op.create_table( 'category', sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.Text, nullable=False, unique=True), sa.Column('short_name', sa.Text, nullable=False, unique=True), sa.Column('created', sa.Text, default=make_timestamp), ) def downgrade(): op.drop_table('category') ## Instruction: Add description to the table and populate it with two categories ## Code After: # revision identifiers, used by Alembic. revision = '47dd43c1491' down_revision = '27bf0aefa49d' from alembic import op import sqlalchemy as sa import datetime def make_timestamp(): now = datetime.datetime.utcnow() return now.isoformat() def upgrade(): op.create_table( 'category', sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.Text, nullable=False, unique=True), sa.Column('short_name', sa.Text, nullable=False, unique=True), sa.Column('description', sa.Text, nullable=False), sa.Column('created', sa.Text, default=make_timestamp), ) # Add two categories query = 'INSERT INTO category (name, short_name, description) VALUES (\'Thinking\', \'thinking\', \'Applications where you can help using your skills\')' op.execute(query) query = 'INSERT INTO category (name, short_name, description) VALUES (\'Sensing\', \'sensing\', \'Applications where you can help gathering data\')' op.execute(query) def downgrade(): op.drop_table('category')
# revision identifiers, used by Alembic. revision = '47dd43c1491' down_revision = '27bf0aefa49d' from alembic import op import sqlalchemy as sa import datetime def make_timestamp(): now = datetime.datetime.utcnow() return now.isoformat() def upgrade(): op.create_table( 'category', sa.Column('id', sa.Integer, primary_key=True), sa.Column('name', sa.Text, nullable=False, unique=True), sa.Column('short_name', sa.Text, nullable=False, unique=True), + sa.Column('description', sa.Text, nullable=False), sa.Column('created', sa.Text, default=make_timestamp), ) + + # Add two categories + query = 'INSERT INTO category (name, short_name, description) VALUES (\'Thinking\', \'thinking\', \'Applications where you can help using your skills\')' + op.execute(query) + query = 'INSERT INTO category (name, short_name, description) VALUES (\'Sensing\', \'sensing\', \'Applications where you can help gathering data\')' + op.execute(query) def downgrade(): op.drop_table('category')
c6d68c78ac9391138d2f433248e35dc6fdd1cf98
setup_egg.py
setup_egg.py
"""Wrapper to run setup.py using setuptools.""" if __name__ == '__main__': exec('setup.py', dict(__name__='__main__', __file__='setup.py', # needed in setup.py force_setuptools=True))
"""Wrapper to run setup.py using setuptools.""" if __name__ == '__main__': with open('setup.py') as f: exec(f.read(), dict(__name__='__main__', __file__='setup.py', # needed in setup.py force_setuptools=True))
Update call to `exec` to read the file in and execute the code.
Update call to `exec` to read the file in and execute the code.
Python
bsd-3-clause
FrancoisRheaultUS/dipy,FrancoisRheaultUS/dipy
"""Wrapper to run setup.py using setuptools.""" if __name__ == '__main__': + with open('setup.py') as f: - exec('setup.py', dict(__name__='__main__', + exec(f.read(), dict(__name__='__main__', - __file__='setup.py', # needed in setup.py + __file__='setup.py', # needed in setup.py - force_setuptools=True)) + force_setuptools=True))
Update call to `exec` to read the file in and execute the code.
## Code Before: """Wrapper to run setup.py using setuptools.""" if __name__ == '__main__': exec('setup.py', dict(__name__='__main__', __file__='setup.py', # needed in setup.py force_setuptools=True)) ## Instruction: Update call to `exec` to read the file in and execute the code. ## Code After: """Wrapper to run setup.py using setuptools.""" if __name__ == '__main__': with open('setup.py') as f: exec(f.read(), dict(__name__='__main__', __file__='setup.py', # needed in setup.py force_setuptools=True))
"""Wrapper to run setup.py using setuptools.""" if __name__ == '__main__': + with open('setup.py') as f: - exec('setup.py', dict(__name__='__main__', ? ^^ ^^^^^^^ + exec(f.read(), dict(__name__='__main__', ? ++++ ^^^ ^^^^ - __file__='setup.py', # needed in setup.py + __file__='setup.py', # needed in setup.py ? ++ - force_setuptools=True)) + force_setuptools=True)) ? ++
c692038646417dfcd2e41f186b5814b3978847b6
conf_site/core/context_processors.py
conf_site/core/context_processors.py
from django.conf import settings from django.utils import timezone import pytz def core_context(self): """Context processor for elements appearing on every page.""" context = {} context["google_analytics_id"] = settings.GOOGLE_ANALYTICS_PROPERTY_ID context["sentry_public_dsn"] = settings.SENTRY_PUBLIC_DSN return context def time_zone_context(self): context = {} # Duplicate the functionality of django.template.context_processors.tz. context["TIME_ZONE"] = timezone.get_current_timezone_name() # Add a list of time zones to the context. context["TIME_ZONES"] = pytz.common_timezones return context
from django.conf import settings from django.contrib.sites.models import Site from django.utils import timezone import pytz def core_context(self): """Context processor for elements appearing on every page.""" context = {} context["conference_title"] = Site.objects.get_current().name context["google_analytics_id"] = settings.GOOGLE_ANALYTICS_PROPERTY_ID context["sentry_public_dsn"] = settings.SENTRY_PUBLIC_DSN return context def time_zone_context(self): context = {} # Duplicate the functionality of django.template.context_processors.tz. context["TIME_ZONE"] = timezone.get_current_timezone_name() # Add a list of time zones to the context. context["TIME_ZONES"] = pytz.common_timezones return context
Fix conference title context processor.
Fix conference title context processor.
Python
mit
pydata/conf_site,pydata/conf_site,pydata/conf_site
from django.conf import settings + from django.contrib.sites.models import Site from django.utils import timezone import pytz def core_context(self): """Context processor for elements appearing on every page.""" context = {} + context["conference_title"] = Site.objects.get_current().name context["google_analytics_id"] = settings.GOOGLE_ANALYTICS_PROPERTY_ID context["sentry_public_dsn"] = settings.SENTRY_PUBLIC_DSN return context def time_zone_context(self): context = {} # Duplicate the functionality of django.template.context_processors.tz. context["TIME_ZONE"] = timezone.get_current_timezone_name() # Add a list of time zones to the context. context["TIME_ZONES"] = pytz.common_timezones return context
Fix conference title context processor.
## Code Before: from django.conf import settings from django.utils import timezone import pytz def core_context(self): """Context processor for elements appearing on every page.""" context = {} context["google_analytics_id"] = settings.GOOGLE_ANALYTICS_PROPERTY_ID context["sentry_public_dsn"] = settings.SENTRY_PUBLIC_DSN return context def time_zone_context(self): context = {} # Duplicate the functionality of django.template.context_processors.tz. context["TIME_ZONE"] = timezone.get_current_timezone_name() # Add a list of time zones to the context. context["TIME_ZONES"] = pytz.common_timezones return context ## Instruction: Fix conference title context processor. ## Code After: from django.conf import settings from django.contrib.sites.models import Site from django.utils import timezone import pytz def core_context(self): """Context processor for elements appearing on every page.""" context = {} context["conference_title"] = Site.objects.get_current().name context["google_analytics_id"] = settings.GOOGLE_ANALYTICS_PROPERTY_ID context["sentry_public_dsn"] = settings.SENTRY_PUBLIC_DSN return context def time_zone_context(self): context = {} # Duplicate the functionality of django.template.context_processors.tz. context["TIME_ZONE"] = timezone.get_current_timezone_name() # Add a list of time zones to the context. context["TIME_ZONES"] = pytz.common_timezones return context
from django.conf import settings + from django.contrib.sites.models import Site from django.utils import timezone import pytz def core_context(self): """Context processor for elements appearing on every page.""" context = {} + context["conference_title"] = Site.objects.get_current().name context["google_analytics_id"] = settings.GOOGLE_ANALYTICS_PROPERTY_ID context["sentry_public_dsn"] = settings.SENTRY_PUBLIC_DSN return context def time_zone_context(self): context = {} # Duplicate the functionality of django.template.context_processors.tz. context["TIME_ZONE"] = timezone.get_current_timezone_name() # Add a list of time zones to the context. context["TIME_ZONES"] = pytz.common_timezones return context
29baa0a57fe49c790d4ef5dcdde1e744fc83efde
boundary/alarm_create.py
boundary/alarm_create.py
from boundary import AlarmModify class AlarmCreate(AlarmModify): def __init__(self, **kwargs): AlarmModify.__init__(self, False) self._kwargs = kwargs self.method = "POST" self._alarm_result = None def add_arguments(self): self.parser.add_argument('-n', '--alarm-name', dest='alarm_name', action='store', required=True, metavar='alarm_name', help='Name of the alarm') AlarmModify.add_arguments(self) def get_arguments(self): """ Extracts the specific arguments of this CLI """ AlarmModify.get_arguments(self) def get_description(self): return 'Creates an alarm definition in an {0} account'.format(self.product_name) def get_api_parameters(self): AlarmModify.get_api_parameters(self) self.path = 'v1/alarms'
from boundary import AlarmModify class AlarmCreate(AlarmModify): def __init__(self, **kwargs): AlarmModify.__init__(self, False) self._kwargs = kwargs self.method = "POST" self._alarm_result = None def add_arguments(self): self.parser.add_argument('-n', '--alarm-name', dest='alarm_name', action='store', required=True, metavar='alarm_name', help='Name of the alarm') AlarmModify.add_arguments(self) def get_arguments(self): """ Extracts the specific arguments of this CLI """ AlarmModify.get_arguments(self) def get_description(self): return 'Creates an alarm definition in an {0} account'.format(self.product_name)
Remove no needed to duplicate parent behaviour
Remove no needed to duplicate parent behaviour
Python
apache-2.0
boundary/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/boundary-api-cli,jdgwartney/pulse-api-cli,boundary/pulse-api-cli,jdgwartney/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/boundary-api-cli
from boundary import AlarmModify class AlarmCreate(AlarmModify): def __init__(self, **kwargs): AlarmModify.__init__(self, False) self._kwargs = kwargs self.method = "POST" self._alarm_result = None def add_arguments(self): self.parser.add_argument('-n', '--alarm-name', dest='alarm_name', action='store', required=True, metavar='alarm_name', help='Name of the alarm') AlarmModify.add_arguments(self) def get_arguments(self): """ Extracts the specific arguments of this CLI """ AlarmModify.get_arguments(self) def get_description(self): return 'Creates an alarm definition in an {0} account'.format(self.product_name) - def get_api_parameters(self): - AlarmModify.get_api_parameters(self) - self.path = 'v1/alarms' -
Remove no needed to duplicate parent behaviour
## Code Before: from boundary import AlarmModify class AlarmCreate(AlarmModify): def __init__(self, **kwargs): AlarmModify.__init__(self, False) self._kwargs = kwargs self.method = "POST" self._alarm_result = None def add_arguments(self): self.parser.add_argument('-n', '--alarm-name', dest='alarm_name', action='store', required=True, metavar='alarm_name', help='Name of the alarm') AlarmModify.add_arguments(self) def get_arguments(self): """ Extracts the specific arguments of this CLI """ AlarmModify.get_arguments(self) def get_description(self): return 'Creates an alarm definition in an {0} account'.format(self.product_name) def get_api_parameters(self): AlarmModify.get_api_parameters(self) self.path = 'v1/alarms' ## Instruction: Remove no needed to duplicate parent behaviour ## Code After: from boundary import AlarmModify class AlarmCreate(AlarmModify): def __init__(self, **kwargs): AlarmModify.__init__(self, False) self._kwargs = kwargs self.method = "POST" self._alarm_result = None def add_arguments(self): self.parser.add_argument('-n', '--alarm-name', dest='alarm_name', action='store', required=True, metavar='alarm_name', help='Name of the alarm') AlarmModify.add_arguments(self) def get_arguments(self): """ Extracts the specific arguments of this CLI """ AlarmModify.get_arguments(self) def get_description(self): return 'Creates an alarm definition in an {0} account'.format(self.product_name)
from boundary import AlarmModify class AlarmCreate(AlarmModify): def __init__(self, **kwargs): AlarmModify.__init__(self, False) self._kwargs = kwargs self.method = "POST" self._alarm_result = None def add_arguments(self): self.parser.add_argument('-n', '--alarm-name', dest='alarm_name', action='store', required=True, metavar='alarm_name', help='Name of the alarm') AlarmModify.add_arguments(self) def get_arguments(self): """ Extracts the specific arguments of this CLI """ AlarmModify.get_arguments(self) def get_description(self): return 'Creates an alarm definition in an {0} account'.format(self.product_name) - def get_api_parameters(self): - AlarmModify.get_api_parameters(self) - self.path = 'v1/alarms' -
612e253d0234e1852db61c589418edbb4add4b00
gunicorn.conf.py
gunicorn.conf.py
preload_app = True worker_class = "gunicorn.workers.gthread.ThreadWorker"
forwarded_allow_ips = '*' preload_app = True worker_class = "gunicorn.workers.gthread.ThreadWorker"
Disable checking of Front-end IPs
Disable checking of Front-end IPs
Python
agpl-3.0
City-of-Helsinki/kuulemma,fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma,City-of-Helsinki/kuulemma,fastmonkeys/kuulemma
+ forwarded_allow_ips = '*' preload_app = True worker_class = "gunicorn.workers.gthread.ThreadWorker"
Disable checking of Front-end IPs
## Code Before: preload_app = True worker_class = "gunicorn.workers.gthread.ThreadWorker" ## Instruction: Disable checking of Front-end IPs ## Code After: forwarded_allow_ips = '*' preload_app = True worker_class = "gunicorn.workers.gthread.ThreadWorker"
+ forwarded_allow_ips = '*' preload_app = True worker_class = "gunicorn.workers.gthread.ThreadWorker"
dc50a4ec058f9893e87a069bc64e4715ecfa0bea
haas_rest_test/plugins/assertions.py
haas_rest_test/plugins/assertions.py
from __future__ import absolute_import, unicode_literals class StatusCodeAssertion(object): _schema = { } def __init__(self, valid_codes): super(StatusCodeAssertion, self).__init__() self.valid_codes = valid_codes @classmethod def from_dict(cls, data): # FIXME: Validate input with jsonschema return cls(valid_codes=data['expected'])
from __future__ import absolute_import, unicode_literals from jsonschema.exceptions import ValidationError import jsonschema from ..exceptions import YamlParseError class StatusCodeAssertion(object): _schema = { '$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'Assertion on status code ', 'description': 'Test case markup for Haas Rest Test', 'type': 'object', 'properties': { 'expected': { 'type': 'integer', }, }, 'required': ['expected'] } def __init__(self, expected_status): super(StatusCodeAssertion, self).__init__() self.expected_status = expected_status @classmethod def from_dict(cls, data): try: jsonschema.validate(data, cls._schema) except ValidationError as e: raise YamlParseError(str(e)) return cls(expected_status=data['expected']) def run(self, case, response): case.fail()
Add initial status code assertion
Add initial status code assertion
Python
bsd-3-clause
sjagoe/usagi
from __future__ import absolute_import, unicode_literals + + from jsonschema.exceptions import ValidationError + import jsonschema + + from ..exceptions import YamlParseError class StatusCodeAssertion(object): _schema = { + '$schema': 'http://json-schema.org/draft-04/schema#', + 'title': 'Assertion on status code ', + 'description': 'Test case markup for Haas Rest Test', + 'type': 'object', + 'properties': { + 'expected': { + 'type': 'integer', + }, + }, + 'required': ['expected'] } - def __init__(self, valid_codes): + def __init__(self, expected_status): super(StatusCodeAssertion, self).__init__() - self.valid_codes = valid_codes + self.expected_status = expected_status @classmethod def from_dict(cls, data): - # FIXME: Validate input with jsonschema + try: + jsonschema.validate(data, cls._schema) + except ValidationError as e: + raise YamlParseError(str(e)) - return cls(valid_codes=data['expected']) + return cls(expected_status=data['expected']) + def run(self, case, response): + case.fail() +
Add initial status code assertion
## Code Before: from __future__ import absolute_import, unicode_literals class StatusCodeAssertion(object): _schema = { } def __init__(self, valid_codes): super(StatusCodeAssertion, self).__init__() self.valid_codes = valid_codes @classmethod def from_dict(cls, data): # FIXME: Validate input with jsonschema return cls(valid_codes=data['expected']) ## Instruction: Add initial status code assertion ## Code After: from __future__ import absolute_import, unicode_literals from jsonschema.exceptions import ValidationError import jsonschema from ..exceptions import YamlParseError class StatusCodeAssertion(object): _schema = { '$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'Assertion on status code ', 'description': 'Test case markup for Haas Rest Test', 'type': 'object', 'properties': { 'expected': { 'type': 'integer', }, }, 'required': ['expected'] } def __init__(self, expected_status): super(StatusCodeAssertion, self).__init__() self.expected_status = expected_status @classmethod def from_dict(cls, data): try: jsonschema.validate(data, cls._schema) except ValidationError as e: raise YamlParseError(str(e)) return cls(expected_status=data['expected']) def run(self, case, response): case.fail()
from __future__ import absolute_import, unicode_literals + + from jsonschema.exceptions import ValidationError + import jsonschema + + from ..exceptions import YamlParseError class StatusCodeAssertion(object): _schema = { + '$schema': 'http://json-schema.org/draft-04/schema#', + 'title': 'Assertion on status code ', + 'description': 'Test case markup for Haas Rest Test', + 'type': 'object', + 'properties': { + 'expected': { + 'type': 'integer', + }, + }, + 'required': ['expected'] } - def __init__(self, valid_codes): + def __init__(self, expected_status): super(StatusCodeAssertion, self).__init__() - self.valid_codes = valid_codes + self.expected_status = expected_status @classmethod def from_dict(cls, data): - # FIXME: Validate input with jsonschema + try: + jsonschema.validate(data, cls._schema) + except ValidationError as e: + raise YamlParseError(str(e)) - return cls(valid_codes=data['expected']) ? ^^^^ ^^^^ + return cls(expected_status=data['expected']) ? ^^^^^^^ ^^^^^ + + def run(self, case, response): + case.fail()
25da28f685b9cffa86b9400957089bdd7b5513de
kaptan/handlers/yaml_handler.py
kaptan/handlers/yaml_handler.py
from __future__ import print_function, unicode_literals import yaml from . import BaseHandler class YamlHandler(BaseHandler): def load(self, data): return yaml.load(data) def dump(self, data, safe=False, **kwargs): if not safe: return yaml.dump(data, **kwargs) else: return yaml.safe_dump(data, **kwargs)
from __future__ import print_function, unicode_literals import yaml from . import BaseHandler class YamlHandler(BaseHandler): def load(self, data, safe=True): if safe: func = yaml.safe_load else: func = yaml.load return func(data) def dump(self, data, safe=True, **kwargs): if safe: func = yaml.safe_dump else: func = yaml.dump return func(data, **kwargs)
Make YAML handler safe by default
Make YAML handler safe by default Fixes #43
Python
bsd-3-clause
emre/kaptan
from __future__ import print_function, unicode_literals import yaml from . import BaseHandler class YamlHandler(BaseHandler): - def load(self, data): + def load(self, data, safe=True): + if safe: + func = yaml.safe_load + else: + func = yaml.load - return yaml.load(data) + return func(data) - def dump(self, data, safe=False, **kwargs): + def dump(self, data, safe=True, **kwargs): - if not safe: + if safe: - return yaml.dump(data, **kwargs) + func = yaml.safe_dump else: + func = yaml.dump - return yaml.safe_dump(data, **kwargs) + return func(data, **kwargs)
Make YAML handler safe by default
## Code Before: from __future__ import print_function, unicode_literals import yaml from . import BaseHandler class YamlHandler(BaseHandler): def load(self, data): return yaml.load(data) def dump(self, data, safe=False, **kwargs): if not safe: return yaml.dump(data, **kwargs) else: return yaml.safe_dump(data, **kwargs) ## Instruction: Make YAML handler safe by default ## Code After: from __future__ import print_function, unicode_literals import yaml from . import BaseHandler class YamlHandler(BaseHandler): def load(self, data, safe=True): if safe: func = yaml.safe_load else: func = yaml.load return func(data) def dump(self, data, safe=True, **kwargs): if safe: func = yaml.safe_dump else: func = yaml.dump return func(data, **kwargs)
from __future__ import print_function, unicode_literals import yaml from . import BaseHandler class YamlHandler(BaseHandler): - def load(self, data): + def load(self, data, safe=True): ? +++++++++++ + if safe: + func = yaml.safe_load + else: + func = yaml.load - return yaml.load(data) ? ^^^^^^^^^ + return func(data) ? ^^^^ - def dump(self, data, safe=False, **kwargs): ? ^^^^ + def dump(self, data, safe=True, **kwargs): ? ^^^ - if not safe: ? ---- + if safe: - return yaml.dump(data, **kwargs) + func = yaml.safe_dump else: + func = yaml.dump - return yaml.safe_dump(data, **kwargs) ? ---- ------- --- ^^ + return func(data, **kwargs) ? ^^
df68b821807d25d204f43d7b1805da6c25f42b43
src/lib/pagination.py
src/lib/pagination.py
from collections import OrderedDict from django.utils.translation import ugettext_lazy as _ from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class LegacyPaginator(PageNumberPagination): """ A legacy paginator that mocks the one from Eve Python """ page_size = 25 page_size_query_param = "max_results" def get_paginated_response(self, data): links = OrderedDict() if self.page.has_next(): links['next'] = OrderedDict([ ('href', self.get_next_link()), ('title', _('page suivante')), ]) if self.page.has_previous(): links['prev'] = OrderedDict([ ('href', self.get_previous_link()), ('title', _('page précédente')), ]) meta = OrderedDict([ ('max_results', self.page.paginator.per_page), ('total', self.page.paginator.count), ('page', self.page.number), ]) return Response(OrderedDict([ ('_items', data), ('_links', links), ('_meta', meta), ]))
from collections import OrderedDict from django.utils.translation import ugettext_lazy as _ from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class LegacyPaginator(PageNumberPagination): """ A legacy paginator that mocks the one from Eve Python """ page_size = 25 page_size_query_param = "max_results" max_page_size = 100 def get_paginated_response(self, data): links = OrderedDict() if self.page.has_next(): links['next'] = OrderedDict([ ('href', self.get_next_link()), ('title', _('page suivante')), ]) if self.page.has_previous(): links['prev'] = OrderedDict([ ('href', self.get_previous_link()), ('title', _('page précédente')), ]) meta = OrderedDict([ ('max_results', self.page.paginator.per_page), ('total', self.page.paginator.count), ('page', self.page.number), ]) return Response(OrderedDict([ ('_items', data), ('_links', links), ('_meta', meta), ]))
Set a maximum to the number of elements that may be requested
Set a maximum to the number of elements that may be requested
Python
agpl-3.0
lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django,lafranceinsoumise/api-django
from collections import OrderedDict from django.utils.translation import ugettext_lazy as _ from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class LegacyPaginator(PageNumberPagination): """ A legacy paginator that mocks the one from Eve Python """ page_size = 25 page_size_query_param = "max_results" + max_page_size = 100 def get_paginated_response(self, data): links = OrderedDict() if self.page.has_next(): links['next'] = OrderedDict([ ('href', self.get_next_link()), ('title', _('page suivante')), ]) if self.page.has_previous(): links['prev'] = OrderedDict([ ('href', self.get_previous_link()), ('title', _('page précédente')), ]) meta = OrderedDict([ ('max_results', self.page.paginator.per_page), ('total', self.page.paginator.count), ('page', self.page.number), ]) return Response(OrderedDict([ ('_items', data), ('_links', links), ('_meta', meta), ]))
Set a maximum to the number of elements that may be requested
## Code Before: from collections import OrderedDict from django.utils.translation import ugettext_lazy as _ from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class LegacyPaginator(PageNumberPagination): """ A legacy paginator that mocks the one from Eve Python """ page_size = 25 page_size_query_param = "max_results" def get_paginated_response(self, data): links = OrderedDict() if self.page.has_next(): links['next'] = OrderedDict([ ('href', self.get_next_link()), ('title', _('page suivante')), ]) if self.page.has_previous(): links['prev'] = OrderedDict([ ('href', self.get_previous_link()), ('title', _('page précédente')), ]) meta = OrderedDict([ ('max_results', self.page.paginator.per_page), ('total', self.page.paginator.count), ('page', self.page.number), ]) return Response(OrderedDict([ ('_items', data), ('_links', links), ('_meta', meta), ])) ## Instruction: Set a maximum to the number of elements that may be requested ## Code After: from collections import OrderedDict from django.utils.translation import ugettext_lazy as _ from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class LegacyPaginator(PageNumberPagination): """ A legacy paginator that mocks the one from Eve Python """ page_size = 25 page_size_query_param = "max_results" max_page_size = 100 def get_paginated_response(self, data): links = OrderedDict() if self.page.has_next(): links['next'] = OrderedDict([ ('href', self.get_next_link()), ('title', _('page suivante')), ]) if self.page.has_previous(): links['prev'] = OrderedDict([ ('href', self.get_previous_link()), ('title', _('page précédente')), ]) meta = OrderedDict([ ('max_results', self.page.paginator.per_page), ('total', self.page.paginator.count), ('page', self.page.number), ]) return Response(OrderedDict([ ('_items', data), ('_links', links), ('_meta', meta), ]))
from collections import OrderedDict from django.utils.translation import ugettext_lazy as _ from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response class LegacyPaginator(PageNumberPagination): """ A legacy paginator that mocks the one from Eve Python """ page_size = 25 page_size_query_param = "max_results" + max_page_size = 100 def get_paginated_response(self, data): links = OrderedDict() if self.page.has_next(): links['next'] = OrderedDict([ ('href', self.get_next_link()), ('title', _('page suivante')), ]) if self.page.has_previous(): links['prev'] = OrderedDict([ ('href', self.get_previous_link()), ('title', _('page précédente')), ]) meta = OrderedDict([ ('max_results', self.page.paginator.per_page), ('total', self.page.paginator.count), ('page', self.page.number), ]) return Response(OrderedDict([ ('_items', data), ('_links', links), ('_meta', meta), ]))
0549a85f83bb4fb95aff3c4fc8d8a699c7e73fa9
chainer/utils/argument.py
chainer/utils/argument.py
def check_unexpected_kwargs(kwargs, **unexpected): for key, message in unexpected.items(): if key in kwargs: raise ValueError(message) def parse_kwargs(kwargs, *name_and_values): values = [kwargs.pop(name, default_value) for name, default_value in name_and_values] if kwargs: import inspect caller = inspect.stack()[1] args = ', '.join(repr(arg) for arg in sorted(kwargs.keys())) message = caller[3] + \ '() got unexpected keyword argument(s) {}'.format(args) raise TypeError(message) return tuple(values) def assert_kwargs_empty(kwargs): # It only checks if kwargs is empty. parse_kwargs(kwargs)
import inspect def check_unexpected_kwargs(kwargs, **unexpected): for key, message in unexpected.items(): if key in kwargs: raise ValueError(message) def parse_kwargs(kwargs, *name_and_values): values = [kwargs.pop(name, default_value) for name, default_value in name_and_values] if kwargs: caller = inspect.stack()[1] args = ', '.join(repr(arg) for arg in sorted(kwargs.keys())) message = caller[3] + \ '() got unexpected keyword argument(s) {}'.format(args) raise TypeError(message) return tuple(values) def assert_kwargs_empty(kwargs): # It only checks if kwargs is empty. parse_kwargs(kwargs)
Put `import inspect` at the top of the file
Put `import inspect` at the top of the file
Python
mit
keisuke-umezawa/chainer,niboshi/chainer,wkentaro/chainer,chainer/chainer,rezoo/chainer,keisuke-umezawa/chainer,hvy/chainer,keisuke-umezawa/chainer,okuta/chainer,ktnyt/chainer,jnishi/chainer,niboshi/chainer,pfnet/chainer,keisuke-umezawa/chainer,anaruse/chainer,hvy/chainer,okuta/chainer,chainer/chainer,hvy/chainer,niboshi/chainer,jnishi/chainer,ktnyt/chainer,tkerola/chainer,chainer/chainer,jnishi/chainer,okuta/chainer,jnishi/chainer,ronekko/chainer,wkentaro/chainer,ktnyt/chainer,chainer/chainer,hvy/chainer,wkentaro/chainer,niboshi/chainer,wkentaro/chainer,okuta/chainer,ktnyt/chainer
+ import inspect + + def check_unexpected_kwargs(kwargs, **unexpected): for key, message in unexpected.items(): if key in kwargs: raise ValueError(message) def parse_kwargs(kwargs, *name_and_values): values = [kwargs.pop(name, default_value) for name, default_value in name_and_values] if kwargs: - import inspect caller = inspect.stack()[1] args = ', '.join(repr(arg) for arg in sorted(kwargs.keys())) message = caller[3] + \ '() got unexpected keyword argument(s) {}'.format(args) raise TypeError(message) return tuple(values) def assert_kwargs_empty(kwargs): # It only checks if kwargs is empty. parse_kwargs(kwargs)
Put `import inspect` at the top of the file
## Code Before: def check_unexpected_kwargs(kwargs, **unexpected): for key, message in unexpected.items(): if key in kwargs: raise ValueError(message) def parse_kwargs(kwargs, *name_and_values): values = [kwargs.pop(name, default_value) for name, default_value in name_and_values] if kwargs: import inspect caller = inspect.stack()[1] args = ', '.join(repr(arg) for arg in sorted(kwargs.keys())) message = caller[3] + \ '() got unexpected keyword argument(s) {}'.format(args) raise TypeError(message) return tuple(values) def assert_kwargs_empty(kwargs): # It only checks if kwargs is empty. parse_kwargs(kwargs) ## Instruction: Put `import inspect` at the top of the file ## Code After: import inspect def check_unexpected_kwargs(kwargs, **unexpected): for key, message in unexpected.items(): if key in kwargs: raise ValueError(message) def parse_kwargs(kwargs, *name_and_values): values = [kwargs.pop(name, default_value) for name, default_value in name_and_values] if kwargs: caller = inspect.stack()[1] args = ', '.join(repr(arg) for arg in sorted(kwargs.keys())) message = caller[3] + \ '() got unexpected keyword argument(s) {}'.format(args) raise TypeError(message) return tuple(values) def assert_kwargs_empty(kwargs): # It only checks if kwargs is empty. parse_kwargs(kwargs)
+ import inspect + + def check_unexpected_kwargs(kwargs, **unexpected): for key, message in unexpected.items(): if key in kwargs: raise ValueError(message) def parse_kwargs(kwargs, *name_and_values): values = [kwargs.pop(name, default_value) for name, default_value in name_and_values] if kwargs: - import inspect caller = inspect.stack()[1] args = ', '.join(repr(arg) for arg in sorted(kwargs.keys())) message = caller[3] + \ '() got unexpected keyword argument(s) {}'.format(args) raise TypeError(message) return tuple(values) def assert_kwargs_empty(kwargs): # It only checks if kwargs is empty. parse_kwargs(kwargs)
42bfa6b69697c0c093a961df5708f477288a6efa
icekit/plugins/twitter_embed/forms.py
icekit/plugins/twitter_embed/forms.py
import re from django import forms from fluent_contents.forms import ContentItemForm class TwitterEmbedAdminForm(ContentItemForm): def clean_twitter_url(self): """ Make sure the URL provided matches the twitter URL format. """ url = self.cleaned_data['twitter_url'] if url: pattern = re.compile(r'https?://(www\.)?twitter.com/\S+/status(es)?/\S+') if not pattern.match(url): raise forms.ValidationError('Please provide a valid twitter link.') return url
import re from django import forms from fluent_contents.forms import ContentItemForm from icekit.plugins.twitter_embed.models import TwitterEmbedItem class TwitterEmbedAdminForm(ContentItemForm): class Meta: model = TwitterEmbedItem fields = '__all__' def clean_twitter_url(self): """ Make sure the URL provided matches the twitter URL format. """ url = self.cleaned_data['twitter_url'] if url: pattern = re.compile(r'https?://(www\.)?twitter.com/\S+/status(es)?/\S+') if not pattern.match(url): raise forms.ValidationError('Please provide a valid twitter link.') return url
Add model and firld information to form.
Add model and firld information to form.
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
import re from django import forms from fluent_contents.forms import ContentItemForm + from icekit.plugins.twitter_embed.models import TwitterEmbedItem class TwitterEmbedAdminForm(ContentItemForm): + class Meta: + model = TwitterEmbedItem + fields = '__all__' + def clean_twitter_url(self): """ Make sure the URL provided matches the twitter URL format. """ url = self.cleaned_data['twitter_url'] if url: pattern = re.compile(r'https?://(www\.)?twitter.com/\S+/status(es)?/\S+') if not pattern.match(url): raise forms.ValidationError('Please provide a valid twitter link.') return url -
Add model and firld information to form.
## Code Before: import re from django import forms from fluent_contents.forms import ContentItemForm class TwitterEmbedAdminForm(ContentItemForm): def clean_twitter_url(self): """ Make sure the URL provided matches the twitter URL format. """ url = self.cleaned_data['twitter_url'] if url: pattern = re.compile(r'https?://(www\.)?twitter.com/\S+/status(es)?/\S+') if not pattern.match(url): raise forms.ValidationError('Please provide a valid twitter link.') return url ## Instruction: Add model and firld information to form. ## Code After: import re from django import forms from fluent_contents.forms import ContentItemForm from icekit.plugins.twitter_embed.models import TwitterEmbedItem class TwitterEmbedAdminForm(ContentItemForm): class Meta: model = TwitterEmbedItem fields = '__all__' def clean_twitter_url(self): """ Make sure the URL provided matches the twitter URL format. """ url = self.cleaned_data['twitter_url'] if url: pattern = re.compile(r'https?://(www\.)?twitter.com/\S+/status(es)?/\S+') if not pattern.match(url): raise forms.ValidationError('Please provide a valid twitter link.') return url
import re from django import forms from fluent_contents.forms import ContentItemForm + from icekit.plugins.twitter_embed.models import TwitterEmbedItem class TwitterEmbedAdminForm(ContentItemForm): + class Meta: + model = TwitterEmbedItem + fields = '__all__' + def clean_twitter_url(self): """ Make sure the URL provided matches the twitter URL format. """ url = self.cleaned_data['twitter_url'] if url: pattern = re.compile(r'https?://(www\.)?twitter.com/\S+/status(es)?/\S+') if not pattern.match(url): raise forms.ValidationError('Please provide a valid twitter link.') return url -
4601656b62d9bf6185cf99ebd3ee107d1c82ce9a
paver/tests/test_path.py
paver/tests/test_path.py
import paver.path import sys import os.path def test_join_on_unicode_path(): merged = b'something/\xc3\xb6'.decode('utf-8') # there is ö after something if not os.path.supports_unicode_filenames and sys.version_info[0] < 3: merged = merged.encode('utf-8') assert merged == os.path.join(paver.path.path('something'), (b'\xc3\xb6').decode('utf-8'))
import paver.path import sys import os.path def test_join_on_unicode_path(): # This is why we should drop 2.5 asap :] # b'' strings are not supported in 2.5, while u'' string are not supported in 3.2 # -- even syntactically, so if will not help you here if sys.version_info[0] < 3: expected = 'something/\xc3\xb6' unicode_o = '\xc3\xb6'.decode('utf-8') # path.py on py2 is inheriting from str instead of unicode under this # circumstances, therefore we have to expect string if os.path.supports_unicode_filenames: expected.decode('utf-8') else: expected = 'something/ö' unicode_o = 'ö' assert expected == os.path.join(paver.path.path('something'), unicode_o)
Rewrite unicode join test to work with py25
Rewrite unicode join test to work with py25
Python
bsd-3-clause
nikolas/paver,cecedille1/paver,gregorynicholas/paver,phargogh/paver,gregorynicholas/paver,thedrow/paver,cecedille1/paver
import paver.path import sys import os.path def test_join_on_unicode_path(): - merged = b'something/\xc3\xb6'.decode('utf-8') # there is ö after something - if not os.path.supports_unicode_filenames and sys.version_info[0] < 3: - merged = merged.encode('utf-8') + # This is why we should drop 2.5 asap :] + # b'' strings are not supported in 2.5, while u'' string are not supported in 3.2 + # -- even syntactically, so if will not help you here + if sys.version_info[0] < 3: + expected = 'something/\xc3\xb6' + unicode_o = '\xc3\xb6'.decode('utf-8') + + # path.py on py2 is inheriting from str instead of unicode under this + # circumstances, therefore we have to expect string + if os.path.supports_unicode_filenames: + expected.decode('utf-8') + + else: + expected = 'something/ö' + unicode_o = 'ö' + - assert merged == os.path.join(paver.path.path('something'), (b'\xc3\xb6').decode('utf-8')) + assert expected == os.path.join(paver.path.path('something'), unicode_o)
Rewrite unicode join test to work with py25
## Code Before: import paver.path import sys import os.path def test_join_on_unicode_path(): merged = b'something/\xc3\xb6'.decode('utf-8') # there is ö after something if not os.path.supports_unicode_filenames and sys.version_info[0] < 3: merged = merged.encode('utf-8') assert merged == os.path.join(paver.path.path('something'), (b'\xc3\xb6').decode('utf-8')) ## Instruction: Rewrite unicode join test to work with py25 ## Code After: import paver.path import sys import os.path def test_join_on_unicode_path(): # This is why we should drop 2.5 asap :] # b'' strings are not supported in 2.5, while u'' string are not supported in 3.2 # -- even syntactically, so if will not help you here if sys.version_info[0] < 3: expected = 'something/\xc3\xb6' unicode_o = '\xc3\xb6'.decode('utf-8') # path.py on py2 is inheriting from str instead of unicode under this # circumstances, therefore we have to expect string if os.path.supports_unicode_filenames: expected.decode('utf-8') else: expected = 'something/ö' unicode_o = 'ö' assert expected == os.path.join(paver.path.path('something'), unicode_o)
import paver.path import sys import os.path def test_join_on_unicode_path(): - merged = b'something/\xc3\xb6'.decode('utf-8') # there is ö after something - if not os.path.supports_unicode_filenames and sys.version_info[0] < 3: - merged = merged.encode('utf-8') + # This is why we should drop 2.5 asap :] + # b'' strings are not supported in 2.5, while u'' string are not supported in 3.2 + # -- even syntactically, so if will not help you here + if sys.version_info[0] < 3: + expected = 'something/\xc3\xb6' + unicode_o = '\xc3\xb6'.decode('utf-8') + + # path.py on py2 is inheriting from str instead of unicode under this + # circumstances, therefore we have to expect string + if os.path.supports_unicode_filenames: + expected.decode('utf-8') + + else: + expected = 'something/ö' + unicode_o = 'ö' + - assert merged == os.path.join(paver.path.path('something'), (b'\xc3\xb6').decode('utf-8')) ? - ^^ ^^^^^^^^^^^^^^^^ ^^^^^^^^ - + assert expected == os.path.join(paver.path.path('something'), unicode_o) ? ^^^^^ ^^^ ^^
c1c66caa31506190944c8bd37df6fe056b60c0e2
vote.py
vote.py
import enki import json e = enki.Enki('key', 'http://localhost:5001', 'translations') e.get_all() tasks = [] for t in e.tasks: options = dict() i = 0 for k in e.task_runs_df[t.id]['msgid'].keys(): options[k] = e.task_runs_df[t.id]['msgid'][k] t.info['msgid_options'] = options tasks.append(t.info) file = open('/tmp/translations_voting_tasks.json', 'w') file.write(json.dumps(tasks)) file.close()
import enki import json e = enki.Enki('key', 'http://localhost:5001', 'translations') e.get_all() tasks = [] for t in e.tasks: options = [] i = 0 for k in e.task_runs_df[t.id]['msgid'].keys(): option = dict(task_run_id=None, msgid=None) option['task_run_id'] = k option['msgid'] = e.task_runs_df[t.id]['msgid'][k] options.append(option) t.info['msgid_options'] = options tasks.append(t.info) file = open('/tmp/translations_voting_tasks.json', 'w') file.write(json.dumps(tasks)) file.close()
Save the tasks in the proper way.
Save the tasks in the proper way.
Python
agpl-3.0
PyBossa/app-translations
import enki import json e = enki.Enki('key', 'http://localhost:5001', 'translations') e.get_all() tasks = [] for t in e.tasks: - options = dict() + options = [] i = 0 for k in e.task_runs_df[t.id]['msgid'].keys(): + option = dict(task_run_id=None, msgid=None) + option['task_run_id'] = k - options[k] = e.task_runs_df[t.id]['msgid'][k] + option['msgid'] = e.task_runs_df[t.id]['msgid'][k] + options.append(option) t.info['msgid_options'] = options tasks.append(t.info) file = open('/tmp/translations_voting_tasks.json', 'w') file.write(json.dumps(tasks)) file.close()
Save the tasks in the proper way.
## Code Before: import enki import json e = enki.Enki('key', 'http://localhost:5001', 'translations') e.get_all() tasks = [] for t in e.tasks: options = dict() i = 0 for k in e.task_runs_df[t.id]['msgid'].keys(): options[k] = e.task_runs_df[t.id]['msgid'][k] t.info['msgid_options'] = options tasks.append(t.info) file = open('/tmp/translations_voting_tasks.json', 'w') file.write(json.dumps(tasks)) file.close() ## Instruction: Save the tasks in the proper way. ## Code After: import enki import json e = enki.Enki('key', 'http://localhost:5001', 'translations') e.get_all() tasks = [] for t in e.tasks: options = [] i = 0 for k in e.task_runs_df[t.id]['msgid'].keys(): option = dict(task_run_id=None, msgid=None) option['task_run_id'] = k option['msgid'] = e.task_runs_df[t.id]['msgid'][k] options.append(option) t.info['msgid_options'] = options tasks.append(t.info) file = open('/tmp/translations_voting_tasks.json', 'w') file.write(json.dumps(tasks)) file.close()
import enki import json e = enki.Enki('key', 'http://localhost:5001', 'translations') e.get_all() tasks = [] for t in e.tasks: - options = dict() ? ^^^^^^ + options = [] ? ^^ i = 0 for k in e.task_runs_df[t.id]['msgid'].keys(): + option = dict(task_run_id=None, msgid=None) + option['task_run_id'] = k - options[k] = e.task_runs_df[t.id]['msgid'][k] ? ^^ + option['msgid'] = e.task_runs_df[t.id]['msgid'][k] ? + +++ ^^^^ + options.append(option) t.info['msgid_options'] = options tasks.append(t.info) file = open('/tmp/translations_voting_tasks.json', 'w') file.write(json.dumps(tasks)) file.close()
7947d474da8bb086493890d81a6788d76e00b108
numba/cuda/tests/__init__.py
numba/cuda/tests/__init__.py
from numba.testing import SerialSuite from numba.testing import load_testsuite from numba import cuda from os.path import dirname, join def load_tests(loader, tests, pattern): suite = SerialSuite() this_dir = dirname(__file__) suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda'))) suite.addTests(load_testsuite(loader, join(this_dir, 'cudasim'))) if cuda.is_available(): gpus = cuda.list_devices() if gpus and gpus[0].compute_capability >= (2, 0): suite.addTests(load_testsuite(loader, join(this_dir, 'cudadrv'))) suite.addTests(load_testsuite(loader, join(this_dir, 'cudapy'))) else: print("skipped CUDA tests because GPU CC < 2.0") else: print("skipped CUDA tests") return suite
from numba.testing import SerialSuite from numba.testing import load_testsuite from numba import cuda from os.path import dirname, join def load_tests(loader, tests, pattern): suite = SerialSuite() this_dir = dirname(__file__) suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda'))) if cuda.is_available(): suite.addTests(load_testsuite(loader, join(this_dir, 'cudasim'))) gpus = cuda.list_devices() if gpus and gpus[0].compute_capability >= (2, 0): suite.addTests(load_testsuite(loader, join(this_dir, 'cudadrv'))) suite.addTests(load_testsuite(loader, join(this_dir, 'cudapy'))) else: print("skipped CUDA tests because GPU CC < 2.0") else: print("skipped CUDA tests") return suite
Fix tests on machine without CUDA
Fix tests on machine without CUDA
Python
bsd-2-clause
sklam/numba,numba/numba,seibert/numba,IntelLabs/numba,jriehl/numba,stonebig/numba,gmarkall/numba,cpcloud/numba,IntelLabs/numba,gmarkall/numba,jriehl/numba,cpcloud/numba,sklam/numba,cpcloud/numba,numba/numba,stonebig/numba,stefanseefeld/numba,sklam/numba,cpcloud/numba,seibert/numba,sklam/numba,gmarkall/numba,stefanseefeld/numba,jriehl/numba,numba/numba,cpcloud/numba,stefanseefeld/numba,IntelLabs/numba,numba/numba,IntelLabs/numba,stuartarchibald/numba,jriehl/numba,sklam/numba,IntelLabs/numba,numba/numba,stonebig/numba,stuartarchibald/numba,stonebig/numba,jriehl/numba,gmarkall/numba,stefanseefeld/numba,stuartarchibald/numba,stuartarchibald/numba,stonebig/numba,stefanseefeld/numba,seibert/numba,seibert/numba,gmarkall/numba,stuartarchibald/numba,seibert/numba
from numba.testing import SerialSuite from numba.testing import load_testsuite from numba import cuda from os.path import dirname, join def load_tests(loader, tests, pattern): suite = SerialSuite() this_dir = dirname(__file__) suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda'))) - suite.addTests(load_testsuite(loader, join(this_dir, 'cudasim'))) if cuda.is_available(): + suite.addTests(load_testsuite(loader, join(this_dir, 'cudasim'))) gpus = cuda.list_devices() if gpus and gpus[0].compute_capability >= (2, 0): suite.addTests(load_testsuite(loader, join(this_dir, 'cudadrv'))) suite.addTests(load_testsuite(loader, join(this_dir, 'cudapy'))) else: print("skipped CUDA tests because GPU CC < 2.0") else: print("skipped CUDA tests") return suite
Fix tests on machine without CUDA
## Code Before: from numba.testing import SerialSuite from numba.testing import load_testsuite from numba import cuda from os.path import dirname, join def load_tests(loader, tests, pattern): suite = SerialSuite() this_dir = dirname(__file__) suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda'))) suite.addTests(load_testsuite(loader, join(this_dir, 'cudasim'))) if cuda.is_available(): gpus = cuda.list_devices() if gpus and gpus[0].compute_capability >= (2, 0): suite.addTests(load_testsuite(loader, join(this_dir, 'cudadrv'))) suite.addTests(load_testsuite(loader, join(this_dir, 'cudapy'))) else: print("skipped CUDA tests because GPU CC < 2.0") else: print("skipped CUDA tests") return suite ## Instruction: Fix tests on machine without CUDA ## Code After: from numba.testing import SerialSuite from numba.testing import load_testsuite from numba import cuda from os.path import dirname, join def load_tests(loader, tests, pattern): suite = SerialSuite() this_dir = dirname(__file__) suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda'))) if cuda.is_available(): suite.addTests(load_testsuite(loader, join(this_dir, 'cudasim'))) gpus = cuda.list_devices() if gpus and gpus[0].compute_capability >= (2, 0): suite.addTests(load_testsuite(loader, join(this_dir, 'cudadrv'))) suite.addTests(load_testsuite(loader, join(this_dir, 'cudapy'))) else: print("skipped CUDA tests because GPU CC < 2.0") else: print("skipped CUDA tests") return suite
from numba.testing import SerialSuite from numba.testing import load_testsuite from numba import cuda from os.path import dirname, join def load_tests(loader, tests, pattern): suite = SerialSuite() this_dir = dirname(__file__) suite.addTests(load_testsuite(loader, join(this_dir, 'nocuda'))) - suite.addTests(load_testsuite(loader, join(this_dir, 'cudasim'))) if cuda.is_available(): + suite.addTests(load_testsuite(loader, join(this_dir, 'cudasim'))) gpus = cuda.list_devices() if gpus and gpus[0].compute_capability >= (2, 0): suite.addTests(load_testsuite(loader, join(this_dir, 'cudadrv'))) suite.addTests(load_testsuite(loader, join(this_dir, 'cudapy'))) else: print("skipped CUDA tests because GPU CC < 2.0") else: print("skipped CUDA tests") return suite
c2eeb0a7d8d3a2692537f2004052b9fad9b1527a
tests/test_utils.py
tests/test_utils.py
import os from unittest import TestCase import requests from furikura import utils def test_request(): requests.get('https://example.com') class TestUtils(TestCase): def test_get_file(self): self.assertEqual(utils.get_file("testfile"), "/usr/share/testfile") def test_check_connection(self): self.addTypeEqualityFunc(type, utils.check_connection(test_request)) def test_autostart(self): utils.autostart('add') self.assertTrue(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop'))) utils.autostart('remove') self.assertFalse(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop')))
import os from unittest import TestCase import requests from furikura import utils def test_request(): requests.get('https://example.com') class TestUtils(TestCase): def test_get_file(self): self.assertEqual(utils.get_file("testfile"), "/usr/share/testfile") def test_check_connection(self): self.addTypeEqualityFunc(type, utils.check_connection(test_request)) def test_autostart(self): os.makedirs(os.path.expanduser('~/.config/autostart/'), exist_ok=True) utils.autostart('add') self.assertTrue(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop'))) utils.autostart('remove') self.assertFalse(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop')))
Create autostart folder for tests
Create autostart folder for tests
Python
mit
benjamindean/furi-kura,benjamindean/furi-kura
import os from unittest import TestCase import requests from furikura import utils def test_request(): requests.get('https://example.com') class TestUtils(TestCase): def test_get_file(self): self.assertEqual(utils.get_file("testfile"), "/usr/share/testfile") def test_check_connection(self): self.addTypeEqualityFunc(type, utils.check_connection(test_request)) def test_autostart(self): + os.makedirs(os.path.expanduser('~/.config/autostart/'), exist_ok=True) + utils.autostart('add') self.assertTrue(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop'))) utils.autostart('remove') self.assertFalse(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop')))
Create autostart folder for tests
## Code Before: import os from unittest import TestCase import requests from furikura import utils def test_request(): requests.get('https://example.com') class TestUtils(TestCase): def test_get_file(self): self.assertEqual(utils.get_file("testfile"), "/usr/share/testfile") def test_check_connection(self): self.addTypeEqualityFunc(type, utils.check_connection(test_request)) def test_autostart(self): utils.autostart('add') self.assertTrue(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop'))) utils.autostart('remove') self.assertFalse(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop'))) ## Instruction: Create autostart folder for tests ## Code After: import os from unittest import TestCase import requests from furikura import utils def test_request(): requests.get('https://example.com') class TestUtils(TestCase): def test_get_file(self): self.assertEqual(utils.get_file("testfile"), "/usr/share/testfile") def test_check_connection(self): self.addTypeEqualityFunc(type, utils.check_connection(test_request)) def test_autostart(self): os.makedirs(os.path.expanduser('~/.config/autostart/'), exist_ok=True) utils.autostart('add') self.assertTrue(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop'))) utils.autostart('remove') self.assertFalse(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop')))
import os from unittest import TestCase import requests from furikura import utils def test_request(): requests.get('https://example.com') class TestUtils(TestCase): def test_get_file(self): self.assertEqual(utils.get_file("testfile"), "/usr/share/testfile") def test_check_connection(self): self.addTypeEqualityFunc(type, utils.check_connection(test_request)) def test_autostart(self): + os.makedirs(os.path.expanduser('~/.config/autostart/'), exist_ok=True) + utils.autostart('add') self.assertTrue(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop'))) utils.autostart('remove') self.assertFalse(os.path.islink(os.path.expanduser('~/.config/autostart/furikura.desktop')))
e3c12bd54e143086dd332a51195e4eb3f7305201
exercise3.py
exercise3.py
__author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__ = "MIT License" def diagnose_car(): """ Interactively queries the user with yes/no questions to identify a possible issue with a car. Inputs: Expected Outputs: Errors: """ diagnose_car()
__author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__ = "MIT License" def diagnose_car(): """ Interactively queries the user with yes/no questions to identify a possible issue with a car. Inputs: Expected Outputs: Errors: """ # First Trouble shooting Question print("Troubleshooting Car Issues") print("For all questions answer y for Yes or n for No") # First Question is Yes question1 = raw_input("Is the car silent when you turn the key?") if question1 == "y": question2 = raw_input("Are the battery terminals corroded?") if question2 == "y": print("Clean terminals and try starting again") elif question2 == "n": print("Replace cables and try again!") else: print("Please select y or n only, Try again!") diagnose_car()
Update - First question yes, small coding done
Update - First question yes, small coding done
Python
mit
xueshen3/inf1340_2015_asst1
__author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__ = "MIT License" def diagnose_car(): """ Interactively queries the user with yes/no questions to identify a possible issue with a car. Inputs: Expected Outputs: Errors: """ + # First Trouble shooting Question + print("Troubleshooting Car Issues") + print("For all questions answer y for Yes or n for No") + + # First Question is Yes + question1 = raw_input("Is the car silent when you turn the key?") + if question1 == "y": + question2 = raw_input("Are the battery terminals corroded?") + if question2 == "y": + print("Clean terminals and try starting again") + elif question2 == "n": + print("Replace cables and try again!") + else: + print("Please select y or n only, Try again!") + diagnose_car()
Update - First question yes, small coding done
## Code Before: __author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__ = "MIT License" def diagnose_car(): """ Interactively queries the user with yes/no questions to identify a possible issue with a car. Inputs: Expected Outputs: Errors: """ diagnose_car() ## Instruction: Update - First question yes, small coding done ## Code After: __author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__ = "MIT License" def diagnose_car(): """ Interactively queries the user with yes/no questions to identify a possible issue with a car. Inputs: Expected Outputs: Errors: """ # First Trouble shooting Question print("Troubleshooting Car Issues") print("For all questions answer y for Yes or n for No") # First Question is Yes question1 = raw_input("Is the car silent when you turn the key?") if question1 == "y": question2 = raw_input("Are the battery terminals corroded?") if question2 == "y": print("Clean terminals and try starting again") elif question2 == "n": print("Replace cables and try again!") else: print("Please select y or n only, Try again!") diagnose_car()
__author__ = 'Susan Sim' __email__ = "ses@drsusansim.org" __copyright__ = "2015 Susan Sim" __license__ = "MIT License" def diagnose_car(): """ Interactively queries the user with yes/no questions to identify a possible issue with a car. Inputs: Expected Outputs: Errors: """ + # First Trouble shooting Question + print("Troubleshooting Car Issues") + print("For all questions answer y for Yes or n for No") + + # First Question is Yes + question1 = raw_input("Is the car silent when you turn the key?") + if question1 == "y": + question2 = raw_input("Are the battery terminals corroded?") + if question2 == "y": + print("Clean terminals and try starting again") + elif question2 == "n": + print("Replace cables and try again!") + else: + print("Please select y or n only, Try again!") + diagnose_car()
79f7d8052333fcace914fa27ea2deb5f0d7cdbfc
readers/models.py
readers/models.py
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models from model_utils.models import TimeStampedModel class Reader(TimeStampedModel): IBOOKS = 'iBooks' KINDLE = 'Kindle' TYPES = ( (IBOOKS, IBOOKS), (KINDLE, KINDLE), ) name = models.CharField(max_length=100, null=True) user = models.ForeignKey(User) kind = models.CharField(max_length=10, choices=TYPES) email = models.EmailField() def __str__(self): return "{}'s {}".format(self.user, self.kind) def get_absolute_url(self): return reverse("reader-detail", kwargs={'pk': self.id})
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models from model_utils.models import TimeStampedModel class Reader(TimeStampedModel): IBOOKS = 'iBooks' KINDLE = 'Kindle' TYPES = ( (IBOOKS, 'iBooks (.epub, .pdf)'), (KINDLE, 'Kindle (.mobi, .pdf)'), ) name = models.CharField(max_length=100, null=True) user = models.ForeignKey(User) kind = models.CharField(max_length=10, choices=TYPES) email = models.EmailField() def __str__(self): return "{}'s {}".format(self.user, self.kind) def get_absolute_url(self): return reverse("reader-detail", kwargs={'pk': self.id})
Make what reader can handle what clearer
Make what reader can handle what clearer
Python
mit
phildini/bockus,phildini/bockus,phildini/bockus
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models from model_utils.models import TimeStampedModel class Reader(TimeStampedModel): IBOOKS = 'iBooks' KINDLE = 'Kindle' TYPES = ( - (IBOOKS, IBOOKS), - (KINDLE, KINDLE), + (IBOOKS, 'iBooks (.epub, .pdf)'), + (KINDLE, 'Kindle (.mobi, .pdf)'), ) name = models.CharField(max_length=100, null=True) user = models.ForeignKey(User) kind = models.CharField(max_length=10, choices=TYPES) email = models.EmailField() def __str__(self): return "{}'s {}".format(self.user, self.kind) def get_absolute_url(self): return reverse("reader-detail", kwargs={'pk': self.id})
Make what reader can handle what clearer
## Code Before: from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models from model_utils.models import TimeStampedModel class Reader(TimeStampedModel): IBOOKS = 'iBooks' KINDLE = 'Kindle' TYPES = ( (IBOOKS, IBOOKS), (KINDLE, KINDLE), ) name = models.CharField(max_length=100, null=True) user = models.ForeignKey(User) kind = models.CharField(max_length=10, choices=TYPES) email = models.EmailField() def __str__(self): return "{}'s {}".format(self.user, self.kind) def get_absolute_url(self): return reverse("reader-detail", kwargs={'pk': self.id}) ## Instruction: Make what reader can handle what clearer ## Code After: from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models from model_utils.models import TimeStampedModel class Reader(TimeStampedModel): IBOOKS = 'iBooks' KINDLE = 'Kindle' TYPES = ( (IBOOKS, 'iBooks (.epub, .pdf)'), (KINDLE, 'Kindle (.mobi, .pdf)'), ) name = models.CharField(max_length=100, null=True) user = models.ForeignKey(User) kind = models.CharField(max_length=10, choices=TYPES) email = models.EmailField() def __str__(self): return "{}'s {}".format(self.user, self.kind) def get_absolute_url(self): return reverse("reader-detail", kwargs={'pk': self.id})
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models from model_utils.models import TimeStampedModel class Reader(TimeStampedModel): IBOOKS = 'iBooks' KINDLE = 'Kindle' TYPES = ( - (IBOOKS, IBOOKS), - (KINDLE, KINDLE), + (IBOOKS, 'iBooks (.epub, .pdf)'), + (KINDLE, 'Kindle (.mobi, .pdf)'), ) name = models.CharField(max_length=100, null=True) user = models.ForeignKey(User) kind = models.CharField(max_length=10, choices=TYPES) email = models.EmailField() def __str__(self): return "{}'s {}".format(self.user, self.kind) def get_absolute_url(self): return reverse("reader-detail", kwargs={'pk': self.id})
c83c63a6b1ff1cc6d6d4f71f2da3affbb167738d
tabler/tabler.py
tabler/tabler.py
from parser import TableParser class Tabler: def __init__(self, html): self._html = html self.header = [] self.body = [] self.footer = [] self.parser = TableParser(self.add_header_row, self.add_body_row, self.add_footer_row) self.parser.feed(html) def rows(self): return self.header + self.body + self.footer def add_header_row(self, cells): self.header.append(cells) def add_body_row(self, cells): self.body.append(cells) def add_footer_row(self, cells): self.footer.append(cells)
from parser import TableParser class Tabler: def __init__(self, html): self._html = html self.header = [] self.body = [] self.footer = [] self.parser = TableParser(self.add_header_row, self.add_body_row, self.add_footer_row) self.parser.feed(html) def rows(self): return self.header + self.body + self.footer def body_rows(self): return self.body def add_header_row(self, cells): self.header.append(self.Row(self, cells)) def add_body_row(self, cells): self.body.append(self.Row(self, cells)) def add_footer_row(self, cells): self.footer.append(self.Row(self, cells)) def index_of(self, index): if isinstance(index, str): if len(self.header) > 0: try: return self.header[0].index(index) except ValueError: raise ValueError(index + " is not a valid index value.") raise ValueError(index + " is not a valid index value.") return index class Row: def __init__(self, tabler, cells): self._tabler = tabler self._cells = cells def __getitem__(self, index): return self._cells[self._tabler.index_of(index)] def index(self, elt): return self._cells.index(elt)
Use a class to store row data, and allow lookup via index or header cell value.
Use a class to store row data, and allow lookup via index or header cell value.
Python
bsd-3-clause
bschmeck/tabler
from parser import TableParser class Tabler: def __init__(self, html): self._html = html self.header = [] self.body = [] self.footer = [] self.parser = TableParser(self.add_header_row, self.add_body_row, self.add_footer_row) self.parser.feed(html) def rows(self): return self.header + self.body + self.footer + def body_rows(self): + return self.body + def add_header_row(self, cells): - self.header.append(cells) + self.header.append(self.Row(self, cells)) def add_body_row(self, cells): - self.body.append(cells) + self.body.append(self.Row(self, cells)) def add_footer_row(self, cells): - self.footer.append(cells) + self.footer.append(self.Row(self, cells)) + def index_of(self, index): + if isinstance(index, str): + if len(self.header) > 0: + try: + return self.header[0].index(index) + except ValueError: + raise ValueError(index + " is not a valid index value.") + raise ValueError(index + " is not a valid index value.") + return index + + class Row: + def __init__(self, tabler, cells): + self._tabler = tabler + self._cells = cells + + def __getitem__(self, index): + return self._cells[self._tabler.index_of(index)] + + def index(self, elt): + return self._cells.index(elt) +
Use a class to store row data, and allow lookup via index or header cell value.
## Code Before: from parser import TableParser class Tabler: def __init__(self, html): self._html = html self.header = [] self.body = [] self.footer = [] self.parser = TableParser(self.add_header_row, self.add_body_row, self.add_footer_row) self.parser.feed(html) def rows(self): return self.header + self.body + self.footer def add_header_row(self, cells): self.header.append(cells) def add_body_row(self, cells): self.body.append(cells) def add_footer_row(self, cells): self.footer.append(cells) ## Instruction: Use a class to store row data, and allow lookup via index or header cell value. ## Code After: from parser import TableParser class Tabler: def __init__(self, html): self._html = html self.header = [] self.body = [] self.footer = [] self.parser = TableParser(self.add_header_row, self.add_body_row, self.add_footer_row) self.parser.feed(html) def rows(self): return self.header + self.body + self.footer def body_rows(self): return self.body def add_header_row(self, cells): self.header.append(self.Row(self, cells)) def add_body_row(self, cells): self.body.append(self.Row(self, cells)) def add_footer_row(self, cells): self.footer.append(self.Row(self, cells)) def index_of(self, index): if isinstance(index, str): if len(self.header) > 0: try: return self.header[0].index(index) except ValueError: raise ValueError(index + " is not a valid index value.") raise ValueError(index + " is not a valid index value.") return index class Row: def __init__(self, tabler, cells): self._tabler = tabler self._cells = cells def __getitem__(self, index): return self._cells[self._tabler.index_of(index)] def index(self, elt): return self._cells.index(elt)
from parser import TableParser class Tabler: def __init__(self, html): self._html = html self.header = [] self.body = [] self.footer = [] self.parser = TableParser(self.add_header_row, self.add_body_row, self.add_footer_row) self.parser.feed(html) def rows(self): return self.header + self.body + self.footer + def body_rows(self): + return self.body + def add_header_row(self, cells): - self.header.append(cells) + self.header.append(self.Row(self, cells)) ? +++++++++++++++ + def add_body_row(self, cells): - self.body.append(cells) + self.body.append(self.Row(self, cells)) ? +++++++++++++++ + def add_footer_row(self, cells): - self.footer.append(cells) + self.footer.append(self.Row(self, cells)) ? +++++++++++++++ + + + def index_of(self, index): + if isinstance(index, str): + if len(self.header) > 0: + try: + return self.header[0].index(index) + except ValueError: + raise ValueError(index + " is not a valid index value.") + raise ValueError(index + " is not a valid index value.") + return index + + class Row: + def __init__(self, tabler, cells): + self._tabler = tabler + self._cells = cells + + def __getitem__(self, index): + return self._cells[self._tabler.index_of(index)] + + def index(self, elt): + return self._cells.index(elt)
f1dd26bfb449f8bba69f93cae02ab904e0a9cba0
tasks/hello_world.py
tasks/hello_world.py
import json import pystache class HelloWorld(): def __init__(self): with open('models/hello_world.json') as config_file: self.config = json.load(config_file) self.message = self.config['message'] def process(self): renderer = pystache.Renderer(search_dirs='templates') with open('bin/hello_world.txt', 'w') as output_file: output_file.write(renderer.render(self))
import json import pystache class HelloWorld(): def __init__(self): with open('models/hello_world.json') as config_file: # Map JSON properties to this object self.__dict__.update(json.load(config_file)) def process(self): renderer = pystache.Renderer(search_dirs='templates') with open('bin/hello_world.txt', 'w') as output_file: output_file.write(renderer.render(self))
Copy config settings to task object automatically
Copy config settings to task object automatically
Python
mit
wpkita/automation-station,wpkita/automation-station,wpkita/automation-station
import json import pystache class HelloWorld(): def __init__(self): with open('models/hello_world.json') as config_file: + # Map JSON properties to this object - self.config = json.load(config_file) + self.__dict__.update(json.load(config_file)) - self.message = self.config['message'] def process(self): renderer = pystache.Renderer(search_dirs='templates') with open('bin/hello_world.txt', 'w') as output_file: output_file.write(renderer.render(self))
Copy config settings to task object automatically
## Code Before: import json import pystache class HelloWorld(): def __init__(self): with open('models/hello_world.json') as config_file: self.config = json.load(config_file) self.message = self.config['message'] def process(self): renderer = pystache.Renderer(search_dirs='templates') with open('bin/hello_world.txt', 'w') as output_file: output_file.write(renderer.render(self)) ## Instruction: Copy config settings to task object automatically ## Code After: import json import pystache class HelloWorld(): def __init__(self): with open('models/hello_world.json') as config_file: # Map JSON properties to this object self.__dict__.update(json.load(config_file)) def process(self): renderer = pystache.Renderer(search_dirs='templates') with open('bin/hello_world.txt', 'w') as output_file: output_file.write(renderer.render(self))
import json import pystache class HelloWorld(): def __init__(self): with open('models/hello_world.json') as config_file: + # Map JSON properties to this object - self.config = json.load(config_file) ? ^^^^^^^^ + self.__dict__.update(json.load(config_file)) ? ++++ ^^^^^^^^^^^ + - self.message = self.config['message'] def process(self): renderer = pystache.Renderer(search_dirs='templates') with open('bin/hello_world.txt', 'w') as output_file: output_file.write(renderer.render(self))
d95d817bdb1fba7eb0ce0cdabcd64a9908796d2a
tests/unit/test_ls.py
tests/unit/test_ls.py
from tests.framework.cli_testcase import CliTestCase from tests.framework.constants import GO_EP1_ID class LsTests(CliTestCase): """ Tests globus ls command """ def test_path(self): """ Does an ls on EP1:/, confirms expected results. """ path = "/" output = self.run_line("globus ls {}:{}".format(GO_EP1_ID, path)) expected = ["home/", "mnt/", "not shareable/", "share/"] for item in expected: self.assertIn(item, output) def test_recursive(self): """ Confirms --recursive ls on EP1:/share/ finds file1.txt """ output = self.run_line("globus ls -r {}:/share/".format(GO_EP1_ID)) self.assertIn("file1.txt", output) def test_depth(self): """ Confirms setting depth to 1 on a --recursive ls of EP1:/ finds godata but not file1.txt """ output = self.run_line(("globus ls -r --recursive-depth-limit 1 {}:/" .format(GO_EP1_ID))) self.assertNotIn("file1.txt", output) def test_recursive_json(self): """ Confirms -F json works with the RecursiveLsResponse """ output = self.run_line("globus ls -r -F json {}:/".format(GO_EP1_ID)) self.assertIn('"DATA":', output) self.assertIn('"name": "share/godata/file1.txt"', output)
from tests.framework.cli_testcase import CliTestCase from tests.framework.constants import GO_EP1_ID class LsTests(CliTestCase): """ Tests globus ls command """ def test_path(self): """ Does an ls on EP1:/, confirms expected results. """ path = "/" output = self.run_line("globus ls {}:{}".format(GO_EP1_ID, path)) expected = ["home/", "mnt/", "not shareable/", "share/"] for item in expected: self.assertIn(item, output) def test_recursive(self): """ Confirms --recursive ls on EP1:/share/ finds file1.txt """ output = self.run_line("globus ls -r {}:/share/".format(GO_EP1_ID)) self.assertIn("file1.txt", output) def test_depth(self): """ Confirms setting depth to 1 on a --recursive ls of EP1:/ finds godata but not file1.txt """ output = self.run_line(("globus ls -r --recursive-depth-limit 1 {}:/" .format(GO_EP1_ID))) self.assertNotIn("file1.txt", output) def test_recursive_json(self): """ Confirms -F json works with the RecursiveLsResponse """ output = self.run_line( "globus ls -r -F json {}:/share".format(GO_EP1_ID)) self.assertIn('"DATA":', output) self.assertIn('"name": "godata/file1.txt"', output)
Fix concurrency bug in ls tests
Fix concurrency bug in ls tests
Python
apache-2.0
globus/globus-cli,globus/globus-cli
from tests.framework.cli_testcase import CliTestCase from tests.framework.constants import GO_EP1_ID class LsTests(CliTestCase): """ Tests globus ls command """ def test_path(self): """ Does an ls on EP1:/, confirms expected results. """ path = "/" output = self.run_line("globus ls {}:{}".format(GO_EP1_ID, path)) expected = ["home/", "mnt/", "not shareable/", "share/"] for item in expected: self.assertIn(item, output) def test_recursive(self): """ Confirms --recursive ls on EP1:/share/ finds file1.txt """ output = self.run_line("globus ls -r {}:/share/".format(GO_EP1_ID)) self.assertIn("file1.txt", output) def test_depth(self): """ Confirms setting depth to 1 on a --recursive ls of EP1:/ finds godata but not file1.txt """ output = self.run_line(("globus ls -r --recursive-depth-limit 1 {}:/" .format(GO_EP1_ID))) self.assertNotIn("file1.txt", output) def test_recursive_json(self): """ Confirms -F json works with the RecursiveLsResponse """ + output = self.run_line( - output = self.run_line("globus ls -r -F json {}:/".format(GO_EP1_ID)) + "globus ls -r -F json {}:/share".format(GO_EP1_ID)) self.assertIn('"DATA":', output) - self.assertIn('"name": "share/godata/file1.txt"', output) + self.assertIn('"name": "godata/file1.txt"', output)
Fix concurrency bug in ls tests
## Code Before: from tests.framework.cli_testcase import CliTestCase from tests.framework.constants import GO_EP1_ID class LsTests(CliTestCase): """ Tests globus ls command """ def test_path(self): """ Does an ls on EP1:/, confirms expected results. """ path = "/" output = self.run_line("globus ls {}:{}".format(GO_EP1_ID, path)) expected = ["home/", "mnt/", "not shareable/", "share/"] for item in expected: self.assertIn(item, output) def test_recursive(self): """ Confirms --recursive ls on EP1:/share/ finds file1.txt """ output = self.run_line("globus ls -r {}:/share/".format(GO_EP1_ID)) self.assertIn("file1.txt", output) def test_depth(self): """ Confirms setting depth to 1 on a --recursive ls of EP1:/ finds godata but not file1.txt """ output = self.run_line(("globus ls -r --recursive-depth-limit 1 {}:/" .format(GO_EP1_ID))) self.assertNotIn("file1.txt", output) def test_recursive_json(self): """ Confirms -F json works with the RecursiveLsResponse """ output = self.run_line("globus ls -r -F json {}:/".format(GO_EP1_ID)) self.assertIn('"DATA":', output) self.assertIn('"name": "share/godata/file1.txt"', output) ## Instruction: Fix concurrency bug in ls tests ## Code After: from tests.framework.cli_testcase import CliTestCase from tests.framework.constants import GO_EP1_ID class LsTests(CliTestCase): """ Tests globus ls command """ def test_path(self): """ Does an ls on EP1:/, confirms expected results. """ path = "/" output = self.run_line("globus ls {}:{}".format(GO_EP1_ID, path)) expected = ["home/", "mnt/", "not shareable/", "share/"] for item in expected: self.assertIn(item, output) def test_recursive(self): """ Confirms --recursive ls on EP1:/share/ finds file1.txt """ output = self.run_line("globus ls -r {}:/share/".format(GO_EP1_ID)) self.assertIn("file1.txt", output) def test_depth(self): """ Confirms setting depth to 1 on a --recursive ls of EP1:/ finds godata but not file1.txt """ output = self.run_line(("globus ls -r --recursive-depth-limit 1 {}:/" .format(GO_EP1_ID))) self.assertNotIn("file1.txt", output) def test_recursive_json(self): """ Confirms -F json works with the RecursiveLsResponse """ output = self.run_line( "globus ls -r -F json {}:/share".format(GO_EP1_ID)) self.assertIn('"DATA":', output) self.assertIn('"name": "godata/file1.txt"', output)
from tests.framework.cli_testcase import CliTestCase from tests.framework.constants import GO_EP1_ID class LsTests(CliTestCase): """ Tests globus ls command """ def test_path(self): """ Does an ls on EP1:/, confirms expected results. """ path = "/" output = self.run_line("globus ls {}:{}".format(GO_EP1_ID, path)) expected = ["home/", "mnt/", "not shareable/", "share/"] for item in expected: self.assertIn(item, output) def test_recursive(self): """ Confirms --recursive ls on EP1:/share/ finds file1.txt """ output = self.run_line("globus ls -r {}:/share/".format(GO_EP1_ID)) self.assertIn("file1.txt", output) def test_depth(self): """ Confirms setting depth to 1 on a --recursive ls of EP1:/ finds godata but not file1.txt """ output = self.run_line(("globus ls -r --recursive-depth-limit 1 {}:/" .format(GO_EP1_ID))) self.assertNotIn("file1.txt", output) def test_recursive_json(self): """ Confirms -F json works with the RecursiveLsResponse """ + output = self.run_line( - output = self.run_line("globus ls -r -F json {}:/".format(GO_EP1_ID)) ? ------ - ^^^^^^^^^^^^^^ + "globus ls -r -F json {}:/share".format(GO_EP1_ID)) ? ^^ +++++ self.assertIn('"DATA":', output) - self.assertIn('"name": "share/godata/file1.txt"', output) ? ------ + self.assertIn('"name": "godata/file1.txt"', output)
3e3ead7d9eb05c2fd713d83510cf08b46cf21f15
skimage/viewer/qt/QtCore.py
skimage/viewer/qt/QtCore.py
from . import qt_api if qt_api == 'pyside': from PySide.QtCore import * elif qt_api == 'pyqt': from PyQt4.QtCore import * else: # Mock objects Qt = None
from . import qt_api if qt_api == 'pyside': from PySide.QtCore import * elif qt_api == 'pyqt': from PyQt4.QtCore import * else: # Mock objects Qt = None pyqtSignal = None
Add mock pyqtSignal to try to get Travis to build
Add mock pyqtSignal to try to get Travis to build
Python
bsd-3-clause
Britefury/scikit-image,oew1v07/scikit-image,almarklein/scikit-image,Hiyorimi/scikit-image,GaZ3ll3/scikit-image,Hiyorimi/scikit-image,dpshelio/scikit-image,ofgulban/scikit-image,ClinicalGraphics/scikit-image,paalge/scikit-image,vighneshbirodkar/scikit-image,youprofit/scikit-image,jwiggins/scikit-image,chriscrosscutler/scikit-image,oew1v07/scikit-image,chintak/scikit-image,SamHames/scikit-image,rjeli/scikit-image,Britefury/scikit-image,michaelaye/scikit-image,emon10005/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,blink1073/scikit-image,rjeli/scikit-image,robintw/scikit-image,dpshelio/scikit-image,michaelpacer/scikit-image,michaelaye/scikit-image,michaelpacer/scikit-image,Midafi/scikit-image,ajaybhat/scikit-image,jwiggins/scikit-image,bsipocz/scikit-image,ClinicalGraphics/scikit-image,rjeli/scikit-image,almarklein/scikit-image,juliusbierk/scikit-image,youprofit/scikit-image,pratapvardhan/scikit-image,bennlich/scikit-image,bsipocz/scikit-image,emon10005/scikit-image,Midafi/scikit-image,GaZ3ll3/scikit-image,paalge/scikit-image,vighneshbirodkar/scikit-image,paalge/scikit-image,warmspringwinds/scikit-image,WarrenWeckesser/scikits-image,juliusbierk/scikit-image,vighneshbirodkar/scikit-image,almarklein/scikit-image,warmspringwinds/scikit-image,robintw/scikit-image,chintak/scikit-image,SamHames/scikit-image,bennlich/scikit-image,keflavich/scikit-image,pratapvardhan/scikit-image,newville/scikit-image,almarklein/scikit-image,chintak/scikit-image,chintak/scikit-image,ajaybhat/scikit-image,newville/scikit-image,keflavich/scikit-image,chriscrosscutler/scikit-image,SamHames/scikit-image,SamHames/scikit-image,blink1073/scikit-image,ofgulban/scikit-image
from . import qt_api if qt_api == 'pyside': from PySide.QtCore import * elif qt_api == 'pyqt': from PyQt4.QtCore import * else: # Mock objects Qt = None + pyqtSignal = None
Add mock pyqtSignal to try to get Travis to build
## Code Before: from . import qt_api if qt_api == 'pyside': from PySide.QtCore import * elif qt_api == 'pyqt': from PyQt4.QtCore import * else: # Mock objects Qt = None ## Instruction: Add mock pyqtSignal to try to get Travis to build ## Code After: from . import qt_api if qt_api == 'pyside': from PySide.QtCore import * elif qt_api == 'pyqt': from PyQt4.QtCore import * else: # Mock objects Qt = None pyqtSignal = None
from . import qt_api if qt_api == 'pyside': from PySide.QtCore import * elif qt_api == 'pyqt': from PyQt4.QtCore import * else: # Mock objects Qt = None + pyqtSignal = None
659321fafc7379f32f45f86eb4c366de884cce35
tests/test_ping.py
tests/test_ping.py
from rohrpost.handlers import handle_ping def test_ping(message): handle_ping(message, request={'id': 123}) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert 'data' not in data def test_ping_additional_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': {'some': 'data', 'other': 'data'} }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['some'] == 'data' def test_ping_additional_non_dict_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': 1 }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['data'] == 1
from rohrpost.handlers import handle_ping def test_ping(message): handle_ping(message, request={'id': 123}) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert 'data' not in data def test_ping_additional_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': {'some': 'data', 'other': 'data', 'handler': 'foo'} }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['some'] == 'data' assert data['data']['handler'] == 'foo' def test_ping_additional_non_dict_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': 1 }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['data'] == 1
Add a failing test that demonstrates wrong handling of data
[tests] Add a failing test that demonstrates wrong handling of data The ping handler adds the data directly to the response_kwargs, allowing internal kwargs to be overwritten. `send_message()` and `build_message()` should not accept `**additional_data`, but `additional_data: dict = None` instead.
Python
mit
axsemantics/rohrpost,axsemantics/rohrpost
from rohrpost.handlers import handle_ping def test_ping(message): handle_ping(message, request={'id': 123}) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert 'data' not in data def test_ping_additional_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', - 'data': {'some': 'data', 'other': 'data'} + 'data': {'some': 'data', 'other': 'data', 'handler': 'foo'} }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['some'] == 'data' + assert data['data']['handler'] == 'foo' def test_ping_additional_non_dict_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': 1 }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['data'] == 1
Add a failing test that demonstrates wrong handling of data
## Code Before: from rohrpost.handlers import handle_ping def test_ping(message): handle_ping(message, request={'id': 123}) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert 'data' not in data def test_ping_additional_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': {'some': 'data', 'other': 'data'} }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['some'] == 'data' def test_ping_additional_non_dict_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': 1 }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['data'] == 1 ## Instruction: Add a failing test that demonstrates wrong handling of data ## Code After: from rohrpost.handlers import handle_ping def test_ping(message): handle_ping(message, request={'id': 123}) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert 'data' not in data def test_ping_additional_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': {'some': 'data', 'other': 'data', 'handler': 'foo'} }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['some'] == 'data' assert data['data']['handler'] == 'foo' def test_ping_additional_non_dict_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': 1 }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['data'] == 1
from rohrpost.handlers import handle_ping def test_ping(message): handle_ping(message, request={'id': 123}) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert 'data' not in data def test_ping_additional_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', - 'data': {'some': 'data', 'other': 'data'} + 'data': {'some': 'data', 'other': 'data', 'handler': 'foo'} ? ++++++++++++++++++ }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['some'] == 'data' + assert data['data']['handler'] == 'foo' def test_ping_additional_non_dict_data(message): handle_ping(message, request={ 'id': 123, 'type': 'ping', 'data': 1 }) assert message.reply_channel.closed is False assert len(message.reply_channel.data) == 1 data = message.reply_channel.data[-1] assert data['id'] == 123 assert data['type'] == 'pong' assert data['data']['data'] == 1
28fe6a0a1e5e5d8781854aad4f22d368d3d73b12
ld37/common/utils/libutils.py
ld37/common/utils/libutils.py
import math def update_image_rect(image, rect): image_rect = image.get_rect() image_rect.x = rect.x image_rect.y = rect.y def distance_between_rects(rect1, rect2): (r1_center_x, r1_center_y) = rect1.center (r2_center_x, r2_center_y) = rect2.center x_squared = (r1_center_x - r2_center_x)**2 y_squared = (r1_center_y - r2_center_y)**2 math.sqrt(x_squared + y_squared)
import math def update_image_rect(image, rect): image_rect = image.get_rect() image_rect.x = rect.x image_rect.y = rect.y def distance_between_rects(rect1, rect2): (r1_center_x, r1_center_y) = rect1.center (r2_center_x, r2_center_y) = rect2.center x_squared = (r2_center_x - r1_center_x)**2 y_squared = (r2_center_y - r1_center_y)**2 return math.sqrt(x_squared + y_squared)
Update distance formula to be more standard
Update distance formula to be more standard
Python
mit
Daihiro/ldjam37,maximx1/ldjam37
import math def update_image_rect(image, rect): image_rect = image.get_rect() image_rect.x = rect.x image_rect.y = rect.y def distance_between_rects(rect1, rect2): (r1_center_x, r1_center_y) = rect1.center (r2_center_x, r2_center_y) = rect2.center - x_squared = (r1_center_x - r2_center_x)**2 + x_squared = (r2_center_x - r1_center_x)**2 - y_squared = (r1_center_y - r2_center_y)**2 + y_squared = (r2_center_y - r1_center_y)**2 - math.sqrt(x_squared + y_squared) + return math.sqrt(x_squared + y_squared)
Update distance formula to be more standard
## Code Before: import math def update_image_rect(image, rect): image_rect = image.get_rect() image_rect.x = rect.x image_rect.y = rect.y def distance_between_rects(rect1, rect2): (r1_center_x, r1_center_y) = rect1.center (r2_center_x, r2_center_y) = rect2.center x_squared = (r1_center_x - r2_center_x)**2 y_squared = (r1_center_y - r2_center_y)**2 math.sqrt(x_squared + y_squared) ## Instruction: Update distance formula to be more standard ## Code After: import math def update_image_rect(image, rect): image_rect = image.get_rect() image_rect.x = rect.x image_rect.y = rect.y def distance_between_rects(rect1, rect2): (r1_center_x, r1_center_y) = rect1.center (r2_center_x, r2_center_y) = rect2.center x_squared = (r2_center_x - r1_center_x)**2 y_squared = (r2_center_y - r1_center_y)**2 return math.sqrt(x_squared + y_squared)
import math def update_image_rect(image, rect): image_rect = image.get_rect() image_rect.x = rect.x image_rect.y = rect.y def distance_between_rects(rect1, rect2): (r1_center_x, r1_center_y) = rect1.center (r2_center_x, r2_center_y) = rect2.center - x_squared = (r1_center_x - r2_center_x)**2 ? ^ ^ + x_squared = (r2_center_x - r1_center_x)**2 ? ^ ^ - y_squared = (r1_center_y - r2_center_y)**2 ? ^ ^ + y_squared = (r2_center_y - r1_center_y)**2 ? ^ ^ - math.sqrt(x_squared + y_squared) + return math.sqrt(x_squared + y_squared) ? +++++++
e35d55f46ffb9d42736ad4e57ae2a6c29838b054
board/tests.py
board/tests.py
from django.test import TestCase # Create your tests here.
from test_plus.test import TestCase class BoardTest(TestCase): def test_get_board_list(self): board_list_url = self.reverse("board:list") self.get_check_200(board_list_url)
Add board list test code.
Add board list test code.
Python
mit
9XD/9XD,9XD/9XD,9XD/9XD,9XD/9XD
- from django.test import TestCase + from test_plus.test import TestCase - # Create your tests here. + class BoardTest(TestCase): + def test_get_board_list(self): + board_list_url = self.reverse("board:list") + self.get_check_200(board_list_url) + +
Add board list test code.
## Code Before: from django.test import TestCase # Create your tests here. ## Instruction: Add board list test code. ## Code After: from test_plus.test import TestCase class BoardTest(TestCase): def test_get_board_list(self): board_list_url = self.reverse("board:list") self.get_check_200(board_list_url)
- from django.test import TestCase ? ^^^^^^ + from test_plus.test import TestCase ? ^^^^^^^^^ - # Create your tests here. + + class BoardTest(TestCase): + def test_get_board_list(self): + board_list_url = self.reverse("board:list") + self.get_check_200(board_list_url) +
5dc2ee040b5de973233ea04a310f7b6b3b0b9de9
mangacork/__init__.py
mangacork/__init__.py
import logging from flask import Flask log = logging.getLogger(__name__) app = Flask(__name__) import mangacork.views
import os import logging from flask import Flask log = logging.getLogger(__name__) app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) import mangacork.views
Add config for different env
Add config for different env
Python
mit
ma3lstrom/manga-cork,ma3lstrom/manga-cork,ma3lstrom/manga-cork
+ import os import logging from flask import Flask log = logging.getLogger(__name__) app = Flask(__name__) + app.config.from_object(os.environ['APP_SETTINGS']) import mangacork.views
Add config for different env
## Code Before: import logging from flask import Flask log = logging.getLogger(__name__) app = Flask(__name__) import mangacork.views ## Instruction: Add config for different env ## Code After: import os import logging from flask import Flask log = logging.getLogger(__name__) app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) import mangacork.views
+ import os import logging from flask import Flask log = logging.getLogger(__name__) app = Flask(__name__) + app.config.from_object(os.environ['APP_SETTINGS']) import mangacork.views
a600543515c286ed7bcba2bad5a0746588b62f9a
app/views.py
app/views.py
import logging import hashlib import json from django.http import HttpResponse, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from app.models import SocialNetworkApp logger = logging.getLogger(__name__) def _get_facebook_app(): apps = SocialNetworkApp.objects.all() for app in apps: if app.connector.name.lower() == 'facebook': return app return None @csrf_exempt def fb_real_time_updates(request): fb_app = _get_facebook_app() if fb_app: if request.method == 'GET': challenge = request.GET.get('hub.challenge') token = request.GET.get('hub.verify_token') if fb_app.token_real_time_updates == token: logger.info('Token received!') return HttpResponse(challenge) elif request.method == 'POST': logger.info(request.body) req_signature = request.META.get('HTTP_X_HUB_SIGNATURE') logger.info(req_signature) exp_signature = 'sha1=' + hashlib.sha1('sha1='+unicode(request.body)+fb_app.app_secret).hexdigest() logger.info(exp_signature) req_json = json.loads(request.body) if req_signature == exp_signature: logger.info(req_json) return HttpResponse() else: logger.info('The received signature does not correspond to the expected one!') return HttpResponseForbidden()
import logging import hashlib import hmac import json from django.http import HttpResponse, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from app.models import SocialNetworkApp logger = logging.getLogger(__name__) def _get_facebook_app(): apps = SocialNetworkApp.objects.all() for app in apps: if app.connector.name.lower() == 'facebook': return app return None def _valid_request(app_secret, req_signature, payload): exp_signature = 'sha1=' + hmac.new(app_secret, msg=unicode(payload), digestmod=hashlib.sha1).hexdigest() return exp_signature == req_signature @csrf_exempt def fb_real_time_updates(request): fb_app = _get_facebook_app() if fb_app: if request.method == 'GET': challenge = request.GET.get('hub.challenge') token = request.GET.get('hub.verify_token') if fb_app.token_real_time_updates == token: logger.info('Token received!') return HttpResponse(challenge) elif request.method == 'POST': logger.info(request.body) req_signature = request.META.get('HTTP_X_HUB_SIGNATURE') if _valid_request(fb_app.app_secret,req_signature,request.body): req_json = json.loads(request.body) logger.info(req_json) return HttpResponse() else: logger.info('The received signature does not correspond to the expected one!') return HttpResponseForbidden()
Modify function that calculate the expected signature
Modify function that calculate the expected signature
Python
mit
rebearteta/social-ideation,joausaga/social-ideation,rebearteta/social-ideation,joausaga/social-ideation,joausaga/social-ideation,rebearteta/social-ideation,rebearteta/social-ideation,joausaga/social-ideation
import logging import hashlib + import hmac import json from django.http import HttpResponse, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from app.models import SocialNetworkApp logger = logging.getLogger(__name__) def _get_facebook_app(): apps = SocialNetworkApp.objects.all() for app in apps: if app.connector.name.lower() == 'facebook': return app return None + + def _valid_request(app_secret, req_signature, payload): + exp_signature = 'sha1=' + hmac.new(app_secret, msg=unicode(payload), digestmod=hashlib.sha1).hexdigest() + return exp_signature == req_signature + + @csrf_exempt def fb_real_time_updates(request): fb_app = _get_facebook_app() if fb_app: if request.method == 'GET': challenge = request.GET.get('hub.challenge') token = request.GET.get('hub.verify_token') if fb_app.token_real_time_updates == token: logger.info('Token received!') return HttpResponse(challenge) elif request.method == 'POST': logger.info(request.body) req_signature = request.META.get('HTTP_X_HUB_SIGNATURE') + if _valid_request(fb_app.app_secret,req_signature,request.body): - logger.info(req_signature) - exp_signature = 'sha1=' + hashlib.sha1('sha1='+unicode(request.body)+fb_app.app_secret).hexdigest() - logger.info(exp_signature) - req_json = json.loads(request.body) + req_json = json.loads(request.body) - if req_signature == exp_signature: logger.info(req_json) return HttpResponse() else: logger.info('The received signature does not correspond to the expected one!') return HttpResponseForbidden()
Modify function that calculate the expected signature
## Code Before: import logging import hashlib import json from django.http import HttpResponse, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from app.models import SocialNetworkApp logger = logging.getLogger(__name__) def _get_facebook_app(): apps = SocialNetworkApp.objects.all() for app in apps: if app.connector.name.lower() == 'facebook': return app return None @csrf_exempt def fb_real_time_updates(request): fb_app = _get_facebook_app() if fb_app: if request.method == 'GET': challenge = request.GET.get('hub.challenge') token = request.GET.get('hub.verify_token') if fb_app.token_real_time_updates == token: logger.info('Token received!') return HttpResponse(challenge) elif request.method == 'POST': logger.info(request.body) req_signature = request.META.get('HTTP_X_HUB_SIGNATURE') logger.info(req_signature) exp_signature = 'sha1=' + hashlib.sha1('sha1='+unicode(request.body)+fb_app.app_secret).hexdigest() logger.info(exp_signature) req_json = json.loads(request.body) if req_signature == exp_signature: logger.info(req_json) return HttpResponse() else: logger.info('The received signature does not correspond to the expected one!') return HttpResponseForbidden() ## Instruction: Modify function that calculate the expected signature ## Code After: import logging import hashlib import hmac import json from django.http import HttpResponse, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from app.models import SocialNetworkApp logger = logging.getLogger(__name__) def _get_facebook_app(): apps = SocialNetworkApp.objects.all() for app in apps: if app.connector.name.lower() == 'facebook': return app return None def _valid_request(app_secret, req_signature, payload): exp_signature = 'sha1=' + hmac.new(app_secret, msg=unicode(payload), digestmod=hashlib.sha1).hexdigest() return exp_signature == req_signature @csrf_exempt def fb_real_time_updates(request): fb_app = _get_facebook_app() if fb_app: if request.method == 'GET': challenge = request.GET.get('hub.challenge') token = request.GET.get('hub.verify_token') if fb_app.token_real_time_updates == token: logger.info('Token received!') return HttpResponse(challenge) elif request.method == 'POST': logger.info(request.body) req_signature = request.META.get('HTTP_X_HUB_SIGNATURE') if _valid_request(fb_app.app_secret,req_signature,request.body): req_json = json.loads(request.body) logger.info(req_json) return HttpResponse() else: logger.info('The received signature does not correspond to the expected one!') return HttpResponseForbidden()
import logging import hashlib + import hmac import json from django.http import HttpResponse, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from app.models import SocialNetworkApp logger = logging.getLogger(__name__) def _get_facebook_app(): apps = SocialNetworkApp.objects.all() for app in apps: if app.connector.name.lower() == 'facebook': return app return None + + def _valid_request(app_secret, req_signature, payload): + exp_signature = 'sha1=' + hmac.new(app_secret, msg=unicode(payload), digestmod=hashlib.sha1).hexdigest() + return exp_signature == req_signature + + @csrf_exempt def fb_real_time_updates(request): fb_app = _get_facebook_app() if fb_app: if request.method == 'GET': challenge = request.GET.get('hub.challenge') token = request.GET.get('hub.verify_token') if fb_app.token_real_time_updates == token: logger.info('Token received!') return HttpResponse(challenge) elif request.method == 'POST': logger.info(request.body) req_signature = request.META.get('HTTP_X_HUB_SIGNATURE') + if _valid_request(fb_app.app_secret,req_signature,request.body): - logger.info(req_signature) - exp_signature = 'sha1=' + hashlib.sha1('sha1='+unicode(request.body)+fb_app.app_secret).hexdigest() - logger.info(exp_signature) - req_json = json.loads(request.body) + req_json = json.loads(request.body) ? ++++ - if req_signature == exp_signature: logger.info(req_json) return HttpResponse() else: logger.info('The received signature does not correspond to the expected one!') return HttpResponseForbidden()
2b4b4ac3ec238a039717feff727316217c13d294
test/test_cronquot.py
test/test_cronquot.py
import unittest from cronquot.cronquot import has_directory class CronquotTest(unittest.TestCase): def test_has_directory(self): self.assertTrue(has_directory('/tmp')) if __name__ == '__main__': unittest.test()
import unittest import os from cronquot.cronquot import has_directory class CronquotTest(unittest.TestCase): def test_has_directory(self): sample_dir = os.path.join( os.path.dirname(__file__), 'crontab') self.assertTrue(has_directory(sample_dir)) if __name__ == '__main__': unittest.test()
Fix to test crontab dir
Fix to test crontab dir
Python
mit
pyohei/cronquot,pyohei/cronquot
import unittest + import os from cronquot.cronquot import has_directory class CronquotTest(unittest.TestCase): def test_has_directory(self): + sample_dir = os.path.join( + os.path.dirname(__file__), 'crontab') - self.assertTrue(has_directory('/tmp')) + self.assertTrue(has_directory(sample_dir)) if __name__ == '__main__': unittest.test()
Fix to test crontab dir
## Code Before: import unittest from cronquot.cronquot import has_directory class CronquotTest(unittest.TestCase): def test_has_directory(self): self.assertTrue(has_directory('/tmp')) if __name__ == '__main__': unittest.test() ## Instruction: Fix to test crontab dir ## Code After: import unittest import os from cronquot.cronquot import has_directory class CronquotTest(unittest.TestCase): def test_has_directory(self): sample_dir = os.path.join( os.path.dirname(__file__), 'crontab') self.assertTrue(has_directory(sample_dir)) if __name__ == '__main__': unittest.test()
import unittest + import os from cronquot.cronquot import has_directory class CronquotTest(unittest.TestCase): def test_has_directory(self): + sample_dir = os.path.join( + os.path.dirname(__file__), 'crontab') - self.assertTrue(has_directory('/tmp')) ? ^^^ ^ + self.assertTrue(has_directory(sample_dir)) ? ^^ ^^^^^^ if __name__ == '__main__': unittest.test()
a26dc400c479572be59bfe90d8e809d2e9e65a63
python_humble_utils/pytest_commands.py
python_humble_utils/pytest_commands.py
import os def generate_tmp_file_path(tmpdir_factory, file_name_with_extension: str, tmp_dir_path: str = None) -> str: """ Generate file path rooted in a temporary dir. :param tmpdir_factory: py.test's tmpdir_factory fixture. :param file_name_with_extension: e.g. 'file.ext' :param tmp_dir_path: generated tmp file directory path relative to base tmp dir, e.g. 'file/is/here'. :return: generated file path. """ basetemp = tmpdir_factory.getbasetemp() if tmp_dir_path: if os.path.isabs(tmp_dir_path): raise ValueError('tmp_dir_path is not a relative path!') # http://stackoverflow.com/a/16595356/1557013 for tmp_file_dir_path_part in os.path.normpath(tmp_dir_path).split(os.sep): # Accounting for possible path separator at the end. if tmp_file_dir_path_part: tmpdir_factory.mktemp(tmp_file_dir_path_part) tmp_file_path = os.path.join(str(basetemp), tmp_dir_path, file_name_with_extension) else: tmp_file_path = str(basetemp.join(file_name_with_extension)) return tmp_file_path
import os def generate_tmp_file_path(tmpdir_factory, file_name_with_extension: str, tmp_dir_path: str = None) -> str: """ Generate file path relative to a temporary directory. :param tmpdir_factory: py.test's `tmpdir_factory` fixture. :param file_name_with_extension: file name with extension e.g. `file_name.ext`. :param tmp_dir_path: path to directory (relative to the temporary one created by `tmpdir_factory`) where the generated file path should reside. # noqa :return: file path. """ basetemp = tmpdir_factory.getbasetemp() if tmp_dir_path: if os.path.isabs(tmp_dir_path): raise ValueError('tmp_dir_path is not a relative path!') # http://stackoverflow.com/a/16595356/1557013 for tmp_file_dir_path_part in os.path.normpath(tmp_dir_path).split(os.sep): # Accounting for possible path separator at the end. if tmp_file_dir_path_part: tmpdir_factory.mktemp(tmp_file_dir_path_part) tmp_file_path = os.path.join(str(basetemp), tmp_dir_path, file_name_with_extension) else: tmp_file_path = str(basetemp.join(file_name_with_extension)) return tmp_file_path
Improve generate_tmp_file_path pytest command docs
Improve generate_tmp_file_path pytest command docs
Python
mit
webyneter/python-humble-utils
import os def generate_tmp_file_path(tmpdir_factory, file_name_with_extension: str, tmp_dir_path: str = None) -> str: """ - Generate file path rooted in a temporary dir. + Generate file path relative to a temporary directory. - :param tmpdir_factory: py.test's tmpdir_factory fixture. + :param tmpdir_factory: py.test's `tmpdir_factory` fixture. + :param file_name_with_extension: file name with extension e.g. `file_name.ext`. + :param tmp_dir_path: path to directory (relative to the temporary one created by `tmpdir_factory`) where the generated file path should reside. # noqa - :param file_name_with_extension: e.g. 'file.ext' - :param tmp_dir_path: generated tmp file directory path relative to base tmp dir, - e.g. 'file/is/here'. - :return: generated file path. + :return: file path. """ basetemp = tmpdir_factory.getbasetemp() if tmp_dir_path: if os.path.isabs(tmp_dir_path): raise ValueError('tmp_dir_path is not a relative path!') # http://stackoverflow.com/a/16595356/1557013 for tmp_file_dir_path_part in os.path.normpath(tmp_dir_path).split(os.sep): # Accounting for possible path separator at the end. if tmp_file_dir_path_part: tmpdir_factory.mktemp(tmp_file_dir_path_part) tmp_file_path = os.path.join(str(basetemp), tmp_dir_path, file_name_with_extension) else: tmp_file_path = str(basetemp.join(file_name_with_extension)) return tmp_file_path
Improve generate_tmp_file_path pytest command docs
## Code Before: import os def generate_tmp_file_path(tmpdir_factory, file_name_with_extension: str, tmp_dir_path: str = None) -> str: """ Generate file path rooted in a temporary dir. :param tmpdir_factory: py.test's tmpdir_factory fixture. :param file_name_with_extension: e.g. 'file.ext' :param tmp_dir_path: generated tmp file directory path relative to base tmp dir, e.g. 'file/is/here'. :return: generated file path. """ basetemp = tmpdir_factory.getbasetemp() if tmp_dir_path: if os.path.isabs(tmp_dir_path): raise ValueError('tmp_dir_path is not a relative path!') # http://stackoverflow.com/a/16595356/1557013 for tmp_file_dir_path_part in os.path.normpath(tmp_dir_path).split(os.sep): # Accounting for possible path separator at the end. if tmp_file_dir_path_part: tmpdir_factory.mktemp(tmp_file_dir_path_part) tmp_file_path = os.path.join(str(basetemp), tmp_dir_path, file_name_with_extension) else: tmp_file_path = str(basetemp.join(file_name_with_extension)) return tmp_file_path ## Instruction: Improve generate_tmp_file_path pytest command docs ## Code After: import os def generate_tmp_file_path(tmpdir_factory, file_name_with_extension: str, tmp_dir_path: str = None) -> str: """ Generate file path relative to a temporary directory. :param tmpdir_factory: py.test's `tmpdir_factory` fixture. :param file_name_with_extension: file name with extension e.g. `file_name.ext`. :param tmp_dir_path: path to directory (relative to the temporary one created by `tmpdir_factory`) where the generated file path should reside. # noqa :return: file path. """ basetemp = tmpdir_factory.getbasetemp() if tmp_dir_path: if os.path.isabs(tmp_dir_path): raise ValueError('tmp_dir_path is not a relative path!') # http://stackoverflow.com/a/16595356/1557013 for tmp_file_dir_path_part in os.path.normpath(tmp_dir_path).split(os.sep): # Accounting for possible path separator at the end. if tmp_file_dir_path_part: tmpdir_factory.mktemp(tmp_file_dir_path_part) tmp_file_path = os.path.join(str(basetemp), tmp_dir_path, file_name_with_extension) else: tmp_file_path = str(basetemp.join(file_name_with_extension)) return tmp_file_path
import os def generate_tmp_file_path(tmpdir_factory, file_name_with_extension: str, tmp_dir_path: str = None) -> str: """ - Generate file path rooted in a temporary dir. ? ------- + Generate file path relative to a temporary directory. ? +++++++++ ++++++ - :param tmpdir_factory: py.test's tmpdir_factory fixture. + :param tmpdir_factory: py.test's `tmpdir_factory` fixture. ? + + + :param file_name_with_extension: file name with extension e.g. `file_name.ext`. + :param tmp_dir_path: path to directory (relative to the temporary one created by `tmpdir_factory`) where the generated file path should reside. # noqa - :param file_name_with_extension: e.g. 'file.ext' - :param tmp_dir_path: generated tmp file directory path relative to base tmp dir, - e.g. 'file/is/here'. - :return: generated file path. ? ---------- + :return: file path. """ basetemp = tmpdir_factory.getbasetemp() if tmp_dir_path: if os.path.isabs(tmp_dir_path): raise ValueError('tmp_dir_path is not a relative path!') # http://stackoverflow.com/a/16595356/1557013 for tmp_file_dir_path_part in os.path.normpath(tmp_dir_path).split(os.sep): # Accounting for possible path separator at the end. if tmp_file_dir_path_part: tmpdir_factory.mktemp(tmp_file_dir_path_part) tmp_file_path = os.path.join(str(basetemp), tmp_dir_path, file_name_with_extension) else: tmp_file_path = str(basetemp.join(file_name_with_extension)) return tmp_file_path
094380f4e30608713de549389adc1657f55b97b6
UCP/login/serializers.py
UCP/login/serializers.py
from rest_framework import serializers from django.contrib.auth.models import User from login.models import UserProfile class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') write_only_fields = ('password',) read_only_fields = ('id',) class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id', 'first_name', 'last_name', 'designation', 'profile_image') read_only_fields = ('id',)
from rest_framework import serializers from django.contrib.auth.models import User from login.models import UserProfile class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') write_only_fields = ('password',) read_only_fields = ('id',) def create(self, validated_data): user = User(email=validated_data['email'], username=validated_data['username']) user.set_password(validated_data['password']) user.save() return user class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id', 'first_name', 'last_name', 'designation', 'profile_image') read_only_fields = ('id',)
Fix saving passwords in Register API
Fix saving passwords in Register API override the create method in UserSerializer and set password there
Python
bsd-3-clause
BuildmLearn/University-Campus-Portal-UCP,BuildmLearn/University-Campus-Portal-UCP,BuildmLearn/University-Campus-Portal-UCP
from rest_framework import serializers from django.contrib.auth.models import User from login.models import UserProfile class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') write_only_fields = ('password',) read_only_fields = ('id',) + + def create(self, validated_data): + user = User(email=validated_data['email'], username=validated_data['username']) + user.set_password(validated_data['password']) + user.save() + return user class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id', 'first_name', 'last_name', 'designation', 'profile_image') read_only_fields = ('id',)
Fix saving passwords in Register API
## Code Before: from rest_framework import serializers from django.contrib.auth.models import User from login.models import UserProfile class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') write_only_fields = ('password',) read_only_fields = ('id',) class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id', 'first_name', 'last_name', 'designation', 'profile_image') read_only_fields = ('id',) ## Instruction: Fix saving passwords in Register API ## Code After: from rest_framework import serializers from django.contrib.auth.models import User from login.models import UserProfile class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') write_only_fields = ('password',) read_only_fields = ('id',) def create(self, validated_data): user = User(email=validated_data['email'], username=validated_data['username']) user.set_password(validated_data['password']) user.save() return user class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id', 'first_name', 'last_name', 'designation', 'profile_image') read_only_fields = ('id',)
from rest_framework import serializers from django.contrib.auth.models import User from login.models import UserProfile class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') write_only_fields = ('password',) read_only_fields = ('id',) + + def create(self, validated_data): + user = User(email=validated_data['email'], username=validated_data['username']) + user.set_password(validated_data['password']) + user.save() + return user class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id', 'first_name', 'last_name', 'designation', 'profile_image') read_only_fields = ('id',)
3a6d76201104b928c1b9053317c9e61804814ff5
pyresticd.py
pyresticd.py
import os import getpass import time from twisted.internet import task from twisted.internet import reactor # Configuration timeout = 3600*24*3 # Period restic_command = "/home/mebus/restic" # your restic command here # Program def do_restic_backup(): print "\nStarting Backup at " + str(time.ctime()) os.system(restic_command) print "\nRestic Scheduler\n----------------------------\n" print "Timout ist: " + str(timeout) restic_password = getpass.getpass(prompt="Please enter the restic encryption password: ") os.environ["RESTIC_PASSWORD"] = restic_password l = task.LoopingCall(do_restic_backup) l.start(timeout) reactor.run()
import os import getpass import time from twisted.internet import task from twisted.internet import reactor # Configuration timeout = 3600*24*3 # Period restic_command = "/home/mebus/restic" # your restic command here # Program def do_restic_backup(): print('Starting Backup at {}'.format(time.ctime())) os.system(restic_command) print('Restic Scheduler') print('-' * 30) print('Timeout: {}'.format(timeout)) restic_password = getpass.getpass(prompt="Please enter the restic encryption password: ") os.environ["RESTIC_PASSWORD"] = restic_password l = task.LoopingCall(do_restic_backup) l.start(timeout) reactor.run()
Use py3-style print and string-formatting
Use py3-style print and string-formatting
Python
mit
Mebus/pyresticd,Mebus/pyresticd
import os import getpass import time from twisted.internet import task from twisted.internet import reactor - # Configuration + # Configuration timeout = 3600*24*3 # Period restic_command = "/home/mebus/restic" # your restic command here # Program + def do_restic_backup(): - print "\nStarting Backup at " + str(time.ctime()) + print('Starting Backup at {}'.format(time.ctime())) os.system(restic_command) - print "\nRestic Scheduler\n----------------------------\n" - print "Timout ist: " + str(timeout) + print('Restic Scheduler') + print('-' * 30) + print('Timeout: {}'.format(timeout)) restic_password = getpass.getpass(prompt="Please enter the restic encryption password: ") os.environ["RESTIC_PASSWORD"] = restic_password l = task.LoopingCall(do_restic_backup) l.start(timeout) reactor.run()
Use py3-style print and string-formatting
## Code Before: import os import getpass import time from twisted.internet import task from twisted.internet import reactor # Configuration timeout = 3600*24*3 # Period restic_command = "/home/mebus/restic" # your restic command here # Program def do_restic_backup(): print "\nStarting Backup at " + str(time.ctime()) os.system(restic_command) print "\nRestic Scheduler\n----------------------------\n" print "Timout ist: " + str(timeout) restic_password = getpass.getpass(prompt="Please enter the restic encryption password: ") os.environ["RESTIC_PASSWORD"] = restic_password l = task.LoopingCall(do_restic_backup) l.start(timeout) reactor.run() ## Instruction: Use py3-style print and string-formatting ## Code After: import os import getpass import time from twisted.internet import task from twisted.internet import reactor # Configuration timeout = 3600*24*3 # Period restic_command = "/home/mebus/restic" # your restic command here # Program def do_restic_backup(): print('Starting Backup at {}'.format(time.ctime())) os.system(restic_command) print('Restic Scheduler') print('-' * 30) print('Timeout: {}'.format(timeout)) restic_password = getpass.getpass(prompt="Please enter the restic encryption password: ") os.environ["RESTIC_PASSWORD"] = restic_password l = task.LoopingCall(do_restic_backup) l.start(timeout) reactor.run()
import os import getpass import time from twisted.internet import task from twisted.internet import reactor - # Configuration ? - + # Configuration timeout = 3600*24*3 # Period restic_command = "/home/mebus/restic" # your restic command here # Program + def do_restic_backup(): - print "\nStarting Backup at " + str(time.ctime()) ? ^^^^ ^^^^^ - + print('Starting Backup at {}'.format(time.ctime())) ? ^^ ^^^^^^^^^ + os.system(restic_command) - print "\nRestic Scheduler\n----------------------------\n" - print "Timout ist: " + str(timeout) + print('Restic Scheduler') + print('-' * 30) + print('Timeout: {}'.format(timeout)) restic_password = getpass.getpass(prompt="Please enter the restic encryption password: ") os.environ["RESTIC_PASSWORD"] = restic_password l = task.LoopingCall(do_restic_backup) l.start(timeout) reactor.run()
8d34496986e68de8aa1a691a494da08f523cb034
oauthenticator/tests/conftest.py
oauthenticator/tests/conftest.py
"""Py.Test fixtures""" from tornado.httpclient import AsyncHTTPClient from pytest import fixture from .mocks import MockAsyncHTTPClient @fixture def client(io_loop, request): """Return mocked AsyncHTTPClient""" before = AsyncHTTPClient.configured_class() AsyncHTTPClient.configure(MockAsyncHTTPClient) request.addfinalizer(lambda : AsyncHTTPClient.configure(before)) c = AsyncHTTPClient() assert isinstance(c, MockAsyncHTTPClient) return c
"""Py.Test fixtures""" from tornado.httpclient import AsyncHTTPClient from tornado import ioloop from pytest import fixture from .mocks import MockAsyncHTTPClient @fixture def io_loop(request): """Same as pytest-tornado.io_loop, adapted for tornado 5""" io_loop = ioloop.IOLoop() io_loop.make_current() def _close(): io_loop.clear_current() io_loop.close(all_fds=True) request.addfinalizer(_close) return io_loop @fixture def client(io_loop, request): """Return mocked AsyncHTTPClient""" before = AsyncHTTPClient.configured_class() AsyncHTTPClient.configure(MockAsyncHTTPClient) request.addfinalizer(lambda : AsyncHTTPClient.configure(before)) c = AsyncHTTPClient() assert isinstance(c, MockAsyncHTTPClient) return c
Add ioloop fixture that works with tornado 5
Add ioloop fixture that works with tornado 5
Python
bsd-3-clause
maltevogl/oauthenticator,minrk/oauthenticator,NickolausDS/oauthenticator,jupyterhub/oauthenticator,jupyter/oauthenticator,jupyter/oauthenticator,enolfc/oauthenticator
"""Py.Test fixtures""" from tornado.httpclient import AsyncHTTPClient + from tornado import ioloop from pytest import fixture from .mocks import MockAsyncHTTPClient + + + @fixture + def io_loop(request): + """Same as pytest-tornado.io_loop, adapted for tornado 5""" + io_loop = ioloop.IOLoop() + io_loop.make_current() + + def _close(): + io_loop.clear_current() + io_loop.close(all_fds=True) + + request.addfinalizer(_close) + return io_loop + @fixture def client(io_loop, request): """Return mocked AsyncHTTPClient""" before = AsyncHTTPClient.configured_class() AsyncHTTPClient.configure(MockAsyncHTTPClient) request.addfinalizer(lambda : AsyncHTTPClient.configure(before)) c = AsyncHTTPClient() assert isinstance(c, MockAsyncHTTPClient) return c
Add ioloop fixture that works with tornado 5
## Code Before: """Py.Test fixtures""" from tornado.httpclient import AsyncHTTPClient from pytest import fixture from .mocks import MockAsyncHTTPClient @fixture def client(io_loop, request): """Return mocked AsyncHTTPClient""" before = AsyncHTTPClient.configured_class() AsyncHTTPClient.configure(MockAsyncHTTPClient) request.addfinalizer(lambda : AsyncHTTPClient.configure(before)) c = AsyncHTTPClient() assert isinstance(c, MockAsyncHTTPClient) return c ## Instruction: Add ioloop fixture that works with tornado 5 ## Code After: """Py.Test fixtures""" from tornado.httpclient import AsyncHTTPClient from tornado import ioloop from pytest import fixture from .mocks import MockAsyncHTTPClient @fixture def io_loop(request): """Same as pytest-tornado.io_loop, adapted for tornado 5""" io_loop = ioloop.IOLoop() io_loop.make_current() def _close(): io_loop.clear_current() io_loop.close(all_fds=True) request.addfinalizer(_close) return io_loop @fixture def client(io_loop, request): """Return mocked AsyncHTTPClient""" before = AsyncHTTPClient.configured_class() AsyncHTTPClient.configure(MockAsyncHTTPClient) request.addfinalizer(lambda : AsyncHTTPClient.configure(before)) c = AsyncHTTPClient() assert isinstance(c, MockAsyncHTTPClient) return c
"""Py.Test fixtures""" from tornado.httpclient import AsyncHTTPClient + from tornado import ioloop from pytest import fixture from .mocks import MockAsyncHTTPClient + + + @fixture + def io_loop(request): + """Same as pytest-tornado.io_loop, adapted for tornado 5""" + io_loop = ioloop.IOLoop() + io_loop.make_current() + + def _close(): + io_loop.clear_current() + io_loop.close(all_fds=True) + + request.addfinalizer(_close) + return io_loop + @fixture def client(io_loop, request): """Return mocked AsyncHTTPClient""" before = AsyncHTTPClient.configured_class() AsyncHTTPClient.configure(MockAsyncHTTPClient) request.addfinalizer(lambda : AsyncHTTPClient.configure(before)) c = AsyncHTTPClient() assert isinstance(c, MockAsyncHTTPClient) return c
a0baec4446efb96483d414a11bc71a483ded1d2b
tests/alerts/alert_test_case.py
tests/alerts/alert_test_case.py
import os.path import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts")) from alert_test_suite import AlertTestSuite class AlertTestCase(object): def __init__(self, description, events=[], events_type='event', expected_alert=None): self.description = description # As a result of defining our test cases as class level variables # we need to copy each event so that other tests dont # mess with the same instance in memory self.events = AlertTestSuite.copy(events) assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.' self.events_type = events_type self.expected_alert = expected_alert self.full_events = [] def run(self, alert_filename, alert_classname): alert_file_module = __import__(alert_filename) alert_class_attr = getattr(alert_file_module, alert_classname) alert_task = alert_class_attr() alert_task.run() return alert_task
import os.path import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts")) from alert_test_suite import AlertTestSuite class AlertTestCase(object): def __init__(self, description, events=[], expected_alert=None): self.description = description # As a result of defining our test cases as class level variables # we need to copy each event so that other tests dont # mess with the same instance in memory self.events = AlertTestSuite.copy(events) assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.' self.expected_alert = expected_alert self.full_events = [] def run(self, alert_filename, alert_classname): alert_file_module = __import__(alert_filename) alert_class_attr = getattr(alert_file_module, alert_classname) alert_task = alert_class_attr() alert_task.run() return alert_task
Remove events_type from alert test case
Remove events_type from alert test case
Python
mpl-2.0
mpurzynski/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,mozilla/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mozilla/MozDef,mozilla/MozDef,mozilla/MozDef,jeffbryner/MozDef,jeffbryner/MozDef
import os.path import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts")) from alert_test_suite import AlertTestSuite class AlertTestCase(object): - def __init__(self, description, events=[], events_type='event', expected_alert=None): + def __init__(self, description, events=[], expected_alert=None): self.description = description # As a result of defining our test cases as class level variables # we need to copy each event so that other tests dont # mess with the same instance in memory self.events = AlertTestSuite.copy(events) assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.' - self.events_type = events_type self.expected_alert = expected_alert self.full_events = [] def run(self, alert_filename, alert_classname): alert_file_module = __import__(alert_filename) alert_class_attr = getattr(alert_file_module, alert_classname) alert_task = alert_class_attr() alert_task.run() return alert_task
Remove events_type from alert test case
## Code Before: import os.path import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts")) from alert_test_suite import AlertTestSuite class AlertTestCase(object): def __init__(self, description, events=[], events_type='event', expected_alert=None): self.description = description # As a result of defining our test cases as class level variables # we need to copy each event so that other tests dont # mess with the same instance in memory self.events = AlertTestSuite.copy(events) assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.' self.events_type = events_type self.expected_alert = expected_alert self.full_events = [] def run(self, alert_filename, alert_classname): alert_file_module = __import__(alert_filename) alert_class_attr = getattr(alert_file_module, alert_classname) alert_task = alert_class_attr() alert_task.run() return alert_task ## Instruction: Remove events_type from alert test case ## Code After: import os.path import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts")) from alert_test_suite import AlertTestSuite class AlertTestCase(object): def __init__(self, description, events=[], expected_alert=None): self.description = description # As a result of defining our test cases as class level variables # we need to copy each event so that other tests dont # mess with the same instance in memory self.events = AlertTestSuite.copy(events) assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.' self.expected_alert = expected_alert self.full_events = [] def run(self, alert_filename, alert_classname): alert_file_module = __import__(alert_filename) alert_class_attr = getattr(alert_file_module, alert_classname) alert_task = alert_class_attr() alert_task.run() return alert_task
import os.path import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts")) from alert_test_suite import AlertTestSuite class AlertTestCase(object): - def __init__(self, description, events=[], events_type='event', expected_alert=None): ? --------------------- + def __init__(self, description, events=[], expected_alert=None): self.description = description # As a result of defining our test cases as class level variables # we need to copy each event so that other tests dont # mess with the same instance in memory self.events = AlertTestSuite.copy(events) assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.' - self.events_type = events_type self.expected_alert = expected_alert self.full_events = [] def run(self, alert_filename, alert_classname): alert_file_module = __import__(alert_filename) alert_class_attr = getattr(alert_file_module, alert_classname) alert_task = alert_class_attr() alert_task.run() return alert_task
e9b7c19a7080bd9e9a88f0e2eb53a662ee5b154b
tests/python/verify_image.py
tests/python/verify_image.py
import unittest import os from selenium import webdriver from time import sleep class TestClaimsLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.PhantomJS() self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') def test_verify_main_screen_loaded(self): self.driver.get('http://%s/eclaim/login/' % self.ip) self.driver.find_element_by_id('id_user_name').send_keys("implementer") self.driver.find_element_by_id('id_password').send_keys("eclaim_implementer") self.driver.find_element_by_css_selector('button.btn.btn-primary').click() self.driver.implicitly_wait(30) greeting = self.driver.find_element_by_id("user-greeting") self.assertTrue(greeting.is_displayed()) self.assertIn(greeting.text, u'Hello, Implementer') # import ipdb; ipdb.set_trace() self.driver.execute_script("set_language('ms')") sleep(5) self.assertEqual(self.driver.find_element_by_id("logo").text, u'Staff Claims') def tearDown(self): self.driver.get('http://%s/eclaim/logout' % self.ip) self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2)
import unittest import os from selenium import webdriver from time import sleep class TestClaimsLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.PhantomJS() self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') def test_verify_main_screen_loaded(self): self.driver.get('http://%s/eclaim/login/' % self.ip) self.driver.find_element_by_id('id_user_name').send_keys("implementer") self.driver.find_element_by_id('id_password').send_keys("eclaim_implementer") self.driver.find_element_by_css_selector('button.btn.btn-primary').click() self.driver.implicitly_wait(30) greeting = self.driver.find_element_by_id("user-greeting") self.assertTrue(greeting.is_displayed()) self.assertTrue('Hello, Implementer' in greeting.text) # import ipdb; ipdb.set_trace() self.driver.execute_script("set_language('ms')") sleep(5) self.assertEqual(self.driver.find_element_by_id("logo").text, u'Staff Claims') def tearDown(self): self.driver.get('http://%s/eclaim/logout' % self.ip) self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2)
Change self.assertIn to self.assertTrue('Hello Implementer' in greeting.txt)
Change self.assertIn to self.assertTrue('Hello Implementer' in greeting.txt)
Python
mit
censof/ansible-deployment,censof/ansible-deployment,censof/ansible-deployment
import unittest import os from selenium import webdriver from time import sleep class TestClaimsLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.PhantomJS() self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') def test_verify_main_screen_loaded(self): self.driver.get('http://%s/eclaim/login/' % self.ip) self.driver.find_element_by_id('id_user_name').send_keys("implementer") self.driver.find_element_by_id('id_password').send_keys("eclaim_implementer") self.driver.find_element_by_css_selector('button.btn.btn-primary').click() self.driver.implicitly_wait(30) greeting = self.driver.find_element_by_id("user-greeting") self.assertTrue(greeting.is_displayed()) - self.assertIn(greeting.text, u'Hello, Implementer') + self.assertTrue('Hello, Implementer' in greeting.text) # import ipdb; ipdb.set_trace() self.driver.execute_script("set_language('ms')") sleep(5) self.assertEqual(self.driver.find_element_by_id("logo").text, u'Staff Claims') def tearDown(self): self.driver.get('http://%s/eclaim/logout' % self.ip) self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2)
Change self.assertIn to self.assertTrue('Hello Implementer' in greeting.txt)
## Code Before: import unittest import os from selenium import webdriver from time import sleep class TestClaimsLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.PhantomJS() self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') def test_verify_main_screen_loaded(self): self.driver.get('http://%s/eclaim/login/' % self.ip) self.driver.find_element_by_id('id_user_name').send_keys("implementer") self.driver.find_element_by_id('id_password').send_keys("eclaim_implementer") self.driver.find_element_by_css_selector('button.btn.btn-primary').click() self.driver.implicitly_wait(30) greeting = self.driver.find_element_by_id("user-greeting") self.assertTrue(greeting.is_displayed()) self.assertIn(greeting.text, u'Hello, Implementer') # import ipdb; ipdb.set_trace() self.driver.execute_script("set_language('ms')") sleep(5) self.assertEqual(self.driver.find_element_by_id("logo").text, u'Staff Claims') def tearDown(self): self.driver.get('http://%s/eclaim/logout' % self.ip) self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2) ## Instruction: Change self.assertIn to self.assertTrue('Hello Implementer' in greeting.txt) ## Code After: import unittest import os from selenium import webdriver from time import sleep class TestClaimsLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.PhantomJS() self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') def test_verify_main_screen_loaded(self): self.driver.get('http://%s/eclaim/login/' % self.ip) self.driver.find_element_by_id('id_user_name').send_keys("implementer") self.driver.find_element_by_id('id_password').send_keys("eclaim_implementer") self.driver.find_element_by_css_selector('button.btn.btn-primary').click() self.driver.implicitly_wait(30) greeting = self.driver.find_element_by_id("user-greeting") self.assertTrue(greeting.is_displayed()) self.assertTrue('Hello, Implementer' in greeting.text) # import ipdb; ipdb.set_trace() self.driver.execute_script("set_language('ms')") sleep(5) self.assertEqual(self.driver.find_element_by_id("logo").text, u'Staff Claims') def tearDown(self): self.driver.get('http://%s/eclaim/logout' % self.ip) self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2)
import unittest import os from selenium import webdriver from time import sleep class TestClaimsLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.PhantomJS() self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') def test_verify_main_screen_loaded(self): self.driver.get('http://%s/eclaim/login/' % self.ip) self.driver.find_element_by_id('id_user_name').send_keys("implementer") self.driver.find_element_by_id('id_password').send_keys("eclaim_implementer") self.driver.find_element_by_css_selector('button.btn.btn-primary').click() self.driver.implicitly_wait(30) greeting = self.driver.find_element_by_id("user-greeting") self.assertTrue(greeting.is_displayed()) - self.assertIn(greeting.text, u'Hello, Implementer') + self.assertTrue('Hello, Implementer' in greeting.text) # import ipdb; ipdb.set_trace() self.driver.execute_script("set_language('ms')") sleep(5) self.assertEqual(self.driver.find_element_by_id("logo").text, u'Staff Claims') def tearDown(self): self.driver.get('http://%s/eclaim/logout' % self.ip) self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2)
fdd87814f68810a390c50f7bf2a08359430722fa
conda_build/main_index.py
conda_build/main_index.py
from __future__ import absolute_import, division, print_function import argparse import os from locale import getpreferredencoding from os.path import abspath from conda.compat import PY3 from conda_build.index import update_index def main(): p = argparse.ArgumentParser( description="Update package index metadata files in given directories") p.add_argument('dir', help='Directory that contains an index to be updated.', nargs='*', default=[os.getcwd()]) p.add_argument('-c', "--check-md5", action="store_true", help="Use MD5 values instead of file modification times for\ determining if a package's metadata needs to be \ updated.") p.add_argument('-f', "--force", action="store_true", help="force reading all files") p.add_argument('-q', "--quiet", action="store_true") args = p.parse_args() dir_paths = [abspath(path) for path in args.dir] # Don't use byte strings in Python 2 if not PY3: dir_paths = [path.decode(getpreferredencoding()) for path in dir_paths] for path in dir_paths: update_index(path, verbose=(not args.quiet), force=args.force) if __name__ == '__main__': main()
from __future__ import absolute_import, division, print_function import os from locale import getpreferredencoding from os.path import abspath from conda.compat import PY3 from conda.cli.conda_argparse import ArgumentParser from conda_build.index import update_index def main(): p = ArgumentParser( description="Update package index metadata files in given directories.") p.add_argument( 'dir', help='Directory that contains an index to be updated.', nargs='*', default=[os.getcwd()], ) p.add_argument( '-c', "--check-md5", action="store_true", help="""Use MD5 values instead of file modification times for determining if a package's metadata needs to be updated.""", ) p.add_argument( '-f', "--force", action="store_true", help="Force reading all files.", ) p.add_argument( '-q', "--quiet", action="store_true", help="Don't show any output.", ) args = p.parse_args() dir_paths = [abspath(path) for path in args.dir] # Don't use byte strings in Python 2 if not PY3: dir_paths = [path.decode(getpreferredencoding()) for path in dir_paths] for path in dir_paths: update_index(path, verbose=(not args.quiet), force=args.force) if __name__ == '__main__': main()
Update command docs for conda index
Update command docs for conda index
Python
bsd-3-clause
frol/conda-build,rmcgibbo/conda-build,shastings517/conda-build,mwcraig/conda-build,mwcraig/conda-build,dan-blanchard/conda-build,mwcraig/conda-build,dan-blanchard/conda-build,sandhujasmine/conda-build,frol/conda-build,rmcgibbo/conda-build,ilastik/conda-build,dan-blanchard/conda-build,shastings517/conda-build,frol/conda-build,rmcgibbo/conda-build,sandhujasmine/conda-build,shastings517/conda-build,sandhujasmine/conda-build,ilastik/conda-build,ilastik/conda-build
from __future__ import absolute_import, division, print_function - import argparse import os from locale import getpreferredencoding from os.path import abspath from conda.compat import PY3 + from conda.cli.conda_argparse import ArgumentParser from conda_build.index import update_index def main(): - p = argparse.ArgumentParser( + p = ArgumentParser( - description="Update package index metadata files in given directories") + description="Update package index metadata files in given directories.") - p.add_argument('dir', + p.add_argument( + 'dir', - help='Directory that contains an index to be updated.', + help='Directory that contains an index to be updated.', - nargs='*', + nargs='*', - default=[os.getcwd()]) + default=[os.getcwd()], + ) - p.add_argument('-c', "--check-md5", + p.add_argument( + '-c', "--check-md5", - action="store_true", + action="store_true", - help="Use MD5 values instead of file modification times for\ + help="""Use MD5 values instead of file modification times for determining if a - determining if a package's metadata needs to be \ - updated.") + package's metadata needs to be updated.""", + ) - p.add_argument('-f', "--force", + p.add_argument( + '-f', "--force", - action="store_true", + action="store_true", - help="force reading all files") + help="Force reading all files.", + ) - p.add_argument('-q', "--quiet", + p.add_argument( + '-q', "--quiet", - action="store_true") + action="store_true", + help="Don't show any output.", + ) args = p.parse_args() dir_paths = [abspath(path) for path in args.dir] # Don't use byte strings in Python 2 if not PY3: dir_paths = [path.decode(getpreferredencoding()) for path in dir_paths] for path in dir_paths: update_index(path, verbose=(not args.quiet), force=args.force) if __name__ == '__main__': main()
Update command docs for conda index
## Code Before: from __future__ import absolute_import, division, print_function import argparse import os from locale import getpreferredencoding from os.path import abspath from conda.compat import PY3 from conda_build.index import update_index def main(): p = argparse.ArgumentParser( description="Update package index metadata files in given directories") p.add_argument('dir', help='Directory that contains an index to be updated.', nargs='*', default=[os.getcwd()]) p.add_argument('-c', "--check-md5", action="store_true", help="Use MD5 values instead of file modification times for\ determining if a package's metadata needs to be \ updated.") p.add_argument('-f', "--force", action="store_true", help="force reading all files") p.add_argument('-q', "--quiet", action="store_true") args = p.parse_args() dir_paths = [abspath(path) for path in args.dir] # Don't use byte strings in Python 2 if not PY3: dir_paths = [path.decode(getpreferredencoding()) for path in dir_paths] for path in dir_paths: update_index(path, verbose=(not args.quiet), force=args.force) if __name__ == '__main__': main() ## Instruction: Update command docs for conda index ## Code After: from __future__ import absolute_import, division, print_function import os from locale import getpreferredencoding from os.path import abspath from conda.compat import PY3 from conda.cli.conda_argparse import ArgumentParser from conda_build.index import update_index def main(): p = ArgumentParser( description="Update package index metadata files in given directories.") p.add_argument( 'dir', help='Directory that contains an index to be updated.', nargs='*', default=[os.getcwd()], ) p.add_argument( '-c', "--check-md5", action="store_true", help="""Use MD5 values instead of file modification times for determining if a package's metadata needs to be updated.""", ) p.add_argument( '-f', "--force", action="store_true", help="Force reading all files.", ) p.add_argument( '-q', "--quiet", action="store_true", help="Don't show any output.", ) args = p.parse_args() dir_paths = [abspath(path) for path in args.dir] # Don't use byte strings in Python 2 if not PY3: dir_paths = [path.decode(getpreferredencoding()) for path in dir_paths] for path in dir_paths: update_index(path, verbose=(not args.quiet), force=args.force) if __name__ == '__main__': main()
from __future__ import absolute_import, division, print_function - import argparse import os from locale import getpreferredencoding from os.path import abspath from conda.compat import PY3 + from conda.cli.conda_argparse import ArgumentParser from conda_build.index import update_index def main(): - p = argparse.ArgumentParser( ? --------- + p = ArgumentParser( - description="Update package index metadata files in given directories") + description="Update package index metadata files in given directories.") ? + - p.add_argument('dir', ? ------ + p.add_argument( + 'dir', - help='Directory that contains an index to be updated.', ? ----------- + help='Directory that contains an index to be updated.', - nargs='*', ? ----------- + nargs='*', - default=[os.getcwd()]) ? ----------- ^ + default=[os.getcwd()], ? ^ + ) - p.add_argument('-c', "--check-md5", + p.add_argument( + '-c', "--check-md5", - action="store_true", ? ----------- + action="store_true", - help="Use MD5 values instead of file modification times for\ ? ----------- ^ + help="""Use MD5 values instead of file modification times for determining if a ? ++ ^^^^^^^^^^^^^^^^^ - determining if a package's metadata needs to be \ - updated.") + package's metadata needs to be updated.""", + ) - p.add_argument('-f', "--force", + p.add_argument( + '-f', "--force", - action="store_true", ? ----------- + action="store_true", - help="force reading all files") ? ----------- ^ ^ + help="Force reading all files.", ? ^ + ^ + ) - p.add_argument('-q', "--quiet", + p.add_argument( + '-q', "--quiet", - action="store_true") ? ----------- ^ + action="store_true", ? ^ + help="Don't show any output.", + ) args = p.parse_args() dir_paths = [abspath(path) for path in args.dir] # Don't use byte strings in Python 2 if not PY3: dir_paths = [path.decode(getpreferredencoding()) for path in dir_paths] for path in dir_paths: update_index(path, verbose=(not args.quiet), force=args.force) if __name__ == '__main__': main()
f7caec9d0c0058b5d760992172b434b461f70d90
molecule/default/tests/test_default.py
molecule/default/tests/test_default.py
import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_docker_service_enabled(host): service = host.service('docker') assert service.is_enabled def test_docker_service_running(host): service = host.service('docker') assert service.is_running @pytest.mark.parametrize('socket_def', [ # listening on localhost, for tcp sockets on port 1883 (MQQT) ('tcp://127.0.0.1:1883'), # all IPv4 tcp sockets on port 8883 (MQQTS) ('tcp://8883'), ]) def test_listening_sockets(host, socket_def): socket = host.socket(socket_def) assert socket.is_listening # Tests to write: # - using the localhost listener: # - verify that a message can be published # - verify that a published message can be subscribed to
import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_docker_service_enabled(host): service = host.service('docker') assert service.is_enabled def test_docker_service_running(host): service = host.service('docker') assert service.is_running @pytest.mark.parametrize('socket_def', [ # all IPv4 tcp sockets on port 8883 (MQQTS) ('tcp://8883'), ]) def test_listening_sockets(host, socket_def): socket = host.socket(socket_def) assert socket.is_listening # Tests to write: # - using the localhost listener: # - verify that a message can be published # - verify that a published message can be subscribed to
Remove test enforcing listening on port 1883
Remove test enforcing listening on port 1883
Python
mit
triplepoint/ansible-mosquitto
import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_docker_service_enabled(host): service = host.service('docker') assert service.is_enabled def test_docker_service_running(host): service = host.service('docker') assert service.is_running @pytest.mark.parametrize('socket_def', [ - # listening on localhost, for tcp sockets on port 1883 (MQQT) - ('tcp://127.0.0.1:1883'), # all IPv4 tcp sockets on port 8883 (MQQTS) ('tcp://8883'), ]) def test_listening_sockets(host, socket_def): socket = host.socket(socket_def) assert socket.is_listening # Tests to write: # - using the localhost listener: # - verify that a message can be published # - verify that a published message can be subscribed to
Remove test enforcing listening on port 1883
## Code Before: import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_docker_service_enabled(host): service = host.service('docker') assert service.is_enabled def test_docker_service_running(host): service = host.service('docker') assert service.is_running @pytest.mark.parametrize('socket_def', [ # listening on localhost, for tcp sockets on port 1883 (MQQT) ('tcp://127.0.0.1:1883'), # all IPv4 tcp sockets on port 8883 (MQQTS) ('tcp://8883'), ]) def test_listening_sockets(host, socket_def): socket = host.socket(socket_def) assert socket.is_listening # Tests to write: # - using the localhost listener: # - verify that a message can be published # - verify that a published message can be subscribed to ## Instruction: Remove test enforcing listening on port 1883 ## Code After: import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_docker_service_enabled(host): service = host.service('docker') assert service.is_enabled def test_docker_service_running(host): service = host.service('docker') assert service.is_running @pytest.mark.parametrize('socket_def', [ # all IPv4 tcp sockets on port 8883 (MQQTS) ('tcp://8883'), ]) def test_listening_sockets(host, socket_def): socket = host.socket(socket_def) assert socket.is_listening # Tests to write: # - using the localhost listener: # - verify that a message can be published # - verify that a published message can be subscribed to
import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_docker_service_enabled(host): service = host.service('docker') assert service.is_enabled def test_docker_service_running(host): service = host.service('docker') assert service.is_running @pytest.mark.parametrize('socket_def', [ - # listening on localhost, for tcp sockets on port 1883 (MQQT) - ('tcp://127.0.0.1:1883'), # all IPv4 tcp sockets on port 8883 (MQQTS) ('tcp://8883'), ]) def test_listening_sockets(host, socket_def): socket = host.socket(socket_def) assert socket.is_listening # Tests to write: # - using the localhost listener: # - verify that a message can be published # - verify that a published message can be subscribed to
8836c5a5274c2a3573d2e706b67a1288de6e59bd
utils/repl.py
utils/repl.py
from nex.state import GlobalState from nex.reader import Reader, EndOfFile from nex.lexer import Lexer from nex.instructioner import Instructioner from nex.banisher import Banisher from nex.parsing.command_parser import command_parser from nex.parsing.utils import ChunkGrabber from nex.box_writer import write_to_file from nex.utils import TidyEnd reader = Reader() state = GlobalState.from_defaults(font_search_paths=['/Users/ejm/projects/nex/example/fonts']) font_id = state.define_new_font(file_name='cmr10', at_clause=None) state.select_font(is_global=True, font_id=font_id) lexer = Lexer(reader, get_cat_code_func=state.codes.get_cat_code) instructioner = Instructioner(lexer) banisher = Banisher(instructioner, state, reader) command_grabber = ChunkGrabber(banisher, command_parser) while True: s = input('In: ') reader.insert_string(s + '\n') try: state.execute_commands(command_grabber, banisher, reader) except TidyEnd: break # out_path = sys.stdout.buffer write_to_file(state, 'done.dvi')
from nex.state import GlobalState from nex.reader import Reader from nex.lexer import Lexer from nex.instructioner import Instructioner from nex.banisher import Banisher from nex.parsing.command_parser import command_parser from nex.parsing.utils import ChunkGrabber from nex.box_writer import write_to_dvi_file from nex.utils import TidyEnd reader = Reader() state = GlobalState.from_defaults(font_search_paths=['/Users/ejm/projects/nex/fonts']) font_id = state.define_new_font(file_name='cmr10', at_clause=None) state.select_font(is_global=True, font_id=font_id) lexer = Lexer(reader, get_cat_code_func=state.codes.get_cat_code) instructioner = Instructioner(lexer) banisher = Banisher(instructioner, state, reader) command_grabber = ChunkGrabber(banisher, command_parser) reader.insert_file('/Users/ejm/projects/nex/tex/plain.tex') state.execute_commands(command_grabber, banisher, reader) while True: s = input('In: ') reader.insert_string(s + '\n') try: state.execute_commands(command_grabber, banisher, reader) except TidyEnd: break # out_path = sys.stdout.buffer write_to_dvi_file(state, 'repl.dvi', write_pdf=True)
Insert plain.tex into REPL state
Insert plain.tex into REPL state
Python
mit
eddiejessup/nex
from nex.state import GlobalState - from nex.reader import Reader, EndOfFile + from nex.reader import Reader from nex.lexer import Lexer from nex.instructioner import Instructioner from nex.banisher import Banisher from nex.parsing.command_parser import command_parser from nex.parsing.utils import ChunkGrabber - from nex.box_writer import write_to_file + from nex.box_writer import write_to_dvi_file from nex.utils import TidyEnd reader = Reader() - state = GlobalState.from_defaults(font_search_paths=['/Users/ejm/projects/nex/example/fonts']) + state = GlobalState.from_defaults(font_search_paths=['/Users/ejm/projects/nex/fonts']) font_id = state.define_new_font(file_name='cmr10', at_clause=None) state.select_font(is_global=True, font_id=font_id) lexer = Lexer(reader, get_cat_code_func=state.codes.get_cat_code) instructioner = Instructioner(lexer) banisher = Banisher(instructioner, state, reader) command_grabber = ChunkGrabber(banisher, command_parser) + + reader.insert_file('/Users/ejm/projects/nex/tex/plain.tex') + state.execute_commands(command_grabber, banisher, reader) while True: s = input('In: ') reader.insert_string(s + '\n') try: state.execute_commands(command_grabber, banisher, reader) except TidyEnd: break # out_path = sys.stdout.buffer - write_to_file(state, 'done.dvi') + write_to_dvi_file(state, 'repl.dvi', write_pdf=True)
Insert plain.tex into REPL state
## Code Before: from nex.state import GlobalState from nex.reader import Reader, EndOfFile from nex.lexer import Lexer from nex.instructioner import Instructioner from nex.banisher import Banisher from nex.parsing.command_parser import command_parser from nex.parsing.utils import ChunkGrabber from nex.box_writer import write_to_file from nex.utils import TidyEnd reader = Reader() state = GlobalState.from_defaults(font_search_paths=['/Users/ejm/projects/nex/example/fonts']) font_id = state.define_new_font(file_name='cmr10', at_clause=None) state.select_font(is_global=True, font_id=font_id) lexer = Lexer(reader, get_cat_code_func=state.codes.get_cat_code) instructioner = Instructioner(lexer) banisher = Banisher(instructioner, state, reader) command_grabber = ChunkGrabber(banisher, command_parser) while True: s = input('In: ') reader.insert_string(s + '\n') try: state.execute_commands(command_grabber, banisher, reader) except TidyEnd: break # out_path = sys.stdout.buffer write_to_file(state, 'done.dvi') ## Instruction: Insert plain.tex into REPL state ## Code After: from nex.state import GlobalState from nex.reader import Reader from nex.lexer import Lexer from nex.instructioner import Instructioner from nex.banisher import Banisher from nex.parsing.command_parser import command_parser from nex.parsing.utils import ChunkGrabber from nex.box_writer import write_to_dvi_file from nex.utils import TidyEnd reader = Reader() state = GlobalState.from_defaults(font_search_paths=['/Users/ejm/projects/nex/fonts']) font_id = state.define_new_font(file_name='cmr10', at_clause=None) state.select_font(is_global=True, font_id=font_id) lexer = Lexer(reader, get_cat_code_func=state.codes.get_cat_code) instructioner = Instructioner(lexer) banisher = Banisher(instructioner, state, reader) command_grabber = ChunkGrabber(banisher, command_parser) reader.insert_file('/Users/ejm/projects/nex/tex/plain.tex') state.execute_commands(command_grabber, banisher, reader) while True: s = input('In: ') reader.insert_string(s + '\n') try: state.execute_commands(command_grabber, banisher, reader) except TidyEnd: break # out_path = sys.stdout.buffer write_to_dvi_file(state, 'repl.dvi', write_pdf=True)
from nex.state import GlobalState - from nex.reader import Reader, EndOfFile ? ----------- + from nex.reader import Reader from nex.lexer import Lexer from nex.instructioner import Instructioner from nex.banisher import Banisher from nex.parsing.command_parser import command_parser from nex.parsing.utils import ChunkGrabber - from nex.box_writer import write_to_file + from nex.box_writer import write_to_dvi_file ? ++++ from nex.utils import TidyEnd reader = Reader() - state = GlobalState.from_defaults(font_search_paths=['/Users/ejm/projects/nex/example/fonts']) ? -------- + state = GlobalState.from_defaults(font_search_paths=['/Users/ejm/projects/nex/fonts']) font_id = state.define_new_font(file_name='cmr10', at_clause=None) state.select_font(is_global=True, font_id=font_id) lexer = Lexer(reader, get_cat_code_func=state.codes.get_cat_code) instructioner = Instructioner(lexer) banisher = Banisher(instructioner, state, reader) command_grabber = ChunkGrabber(banisher, command_parser) + + reader.insert_file('/Users/ejm/projects/nex/tex/plain.tex') + state.execute_commands(command_grabber, banisher, reader) while True: s = input('In: ') reader.insert_string(s + '\n') try: state.execute_commands(command_grabber, banisher, reader) except TidyEnd: break # out_path = sys.stdout.buffer - write_to_file(state, 'done.dvi') + write_to_dvi_file(state, 'repl.dvi', write_pdf=True)
5e7daffadbd523e1d2a457d10977b1c8a2880d9d
docs/example-plugins/directAPIcall.py
docs/example-plugins/directAPIcall.py
from __future__ import unicode_literals from client import slack_client as sc for user in sc.api_call("users.list")["members"]: print(user["name"], user["id"])
from __future__ import unicode_literals from client import slack_client as sc def process_message(data): '''If a user passes 'print users' in a message, print the users in the slack team to the console. (Don't run this in production probably)''' if 'print users' in data['text']: for user in sc.api_call("users.list")["members"]: print(user["name"], user["id"])
Add a bit more info into the example plugin.
Add a bit more info into the example plugin.
Python
mit
erynofwales/ubot2,aerickson/python-rtmbot,jammons/python-rtmbot,slackhq/python-rtmbot,ChihChengLiang/python-rtmbot,erynofwales/ubot2
from __future__ import unicode_literals from client import slack_client as sc - for user in sc.api_call("users.list")["members"]: - print(user["name"], user["id"]) + def process_message(data): + '''If a user passes 'print users' in a message, print the users in the slack + team to the console. (Don't run this in production probably)''' + + if 'print users' in data['text']: + for user in sc.api_call("users.list")["members"]: + print(user["name"], user["id"]) +
Add a bit more info into the example plugin.
## Code Before: from __future__ import unicode_literals from client import slack_client as sc for user in sc.api_call("users.list")["members"]: print(user["name"], user["id"]) ## Instruction: Add a bit more info into the example plugin. ## Code After: from __future__ import unicode_literals from client import slack_client as sc def process_message(data): '''If a user passes 'print users' in a message, print the users in the slack team to the console. (Don't run this in production probably)''' if 'print users' in data['text']: for user in sc.api_call("users.list")["members"]: print(user["name"], user["id"])
from __future__ import unicode_literals from client import slack_client as sc + + def process_message(data): + '''If a user passes 'print users' in a message, print the users in the slack + team to the console. (Don't run this in production probably)''' + + if 'print users' in data['text']: - for user in sc.api_call("users.list")["members"]: + for user in sc.api_call("users.list")["members"]: ? ++++++++ - print(user["name"], user["id"]) + print(user["name"], user["id"]) ? ++++++++
9ce80d4b4a27e5a32504c6b00ffcff846c53a649
froide/publicbody/widgets.py
froide/publicbody/widgets.py
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super().get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': pb.as_data() if pb is not None else None } } }) }) return context
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': pb.as_data() if pb is not None else None } } }) }) return context
Fix super call for Python 2.7
Fix super call for Python 2.7
Python
mit
fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass - context = super().get_context(name, value, attrs) + context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': pb.as_data() if pb is not None else None } } }) }) return context
Fix super call for Python 2.7
## Code Before: import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super().get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': pb.as_data() if pb is not None else None } } }) }) return context ## Instruction: Fix super call for Python 2.7 ## Code After: import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass context = super(PublicBodySelect, self).get_context(name, value, attrs) context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': pb.as_data() if pb is not None else None } } }) }) return context
import json from django import forms from .models import PublicBody class PublicBodySelect(forms.Widget): input_type = "text" template_name = 'publicbody/_chooser.html' initial_search = None class Media: extend = False js = ('js/publicbody.js',) def set_initial_search(self, search): self.initial_search = search def get_context(self, name, value=None, attrs=None): pb, pb_desc = None, None if value is not None: try: pb = PublicBody.objects.get(pk=int(value)) pb_desc = pb.get_label() except (ValueError, PublicBody.DoesNotExist): pass - context = super().get_context(name, value, attrs) + context = super(PublicBodySelect, self).get_context(name, value, attrs) ? ++++++++++++++++++++++ context['widget'].update({ 'value_label': pb_desc, 'search': self.initial_search, 'publicbody': pb, 'json': json.dumps({ 'fields': { name: { 'value': value, 'objects': pb.as_data() if pb is not None else None } } }) }) return context
26f984a7732491e87e4eb756caf0056a7ac71484
contract_invoice_merge_by_partner/models/account_analytic_analysis.py
contract_invoice_merge_by_partner/models/account_analytic_analysis.py
from openerp import api, models class PurchaseOrderLine(models.Model): _inherit = 'account.analytic.account' @api.multi def _recurring_create_invoice(self, automatic=False): invoice_obj = self.env['account.invoice'] invoices = invoice_obj.browse( super(PurchaseOrderLine, self)._recurring_create_invoice(automatic)) res = [] unlink_list = [] for partner in invoices.mapped('partner_id'): inv_to_merge = invoices.filtered( lambda x: x.partner_id.id == partner) if partner.contract_invoice_merge: invoices_merged = inv_to_merge.do_merge() res.extend(invoices_merged) unlink_list.extend(inv_to_merge) else: res.extend(inv_to_merge) if unlink_list: invoice_obj.unlink([x.id for x in unlink_list]) return res
from openerp import api, models class PurchaseOrderLine(models.Model): _inherit = 'account.analytic.account' @api.multi def _recurring_create_invoice(self, automatic=False): invoice_obj = self.env['account.invoice'] invoices = invoice_obj.browse( super(PurchaseOrderLine, self)._recurring_create_invoice( automatic)) res = [] unlink_list = [] for partner in invoices.mapped('partner_id'): inv_to_merge = invoices.filtered( lambda x: x.partner_id.id == partner) if partner.contract_invoice_merge and len(inv_to_merge) > 1: invoices_merged = inv_to_merge.do_merge() res.extend(invoices_merged) unlink_list.extend(inv_to_merge) else: res.extend(inv_to_merge) if unlink_list: invoice_obj.browse(unlink_list).unlink() return res
Fix unlink, >1 filter and lines too long
Fix unlink, >1 filter and lines too long
Python
agpl-3.0
bullet92/contract,open-synergy/contract
from openerp import api, models class PurchaseOrderLine(models.Model): _inherit = 'account.analytic.account' @api.multi def _recurring_create_invoice(self, automatic=False): invoice_obj = self.env['account.invoice'] invoices = invoice_obj.browse( - super(PurchaseOrderLine, self)._recurring_create_invoice(automatic)) + super(PurchaseOrderLine, self)._recurring_create_invoice( + automatic)) res = [] unlink_list = [] for partner in invoices.mapped('partner_id'): inv_to_merge = invoices.filtered( lambda x: x.partner_id.id == partner) - if partner.contract_invoice_merge: + if partner.contract_invoice_merge and len(inv_to_merge) > 1: invoices_merged = inv_to_merge.do_merge() res.extend(invoices_merged) unlink_list.extend(inv_to_merge) else: res.extend(inv_to_merge) if unlink_list: - invoice_obj.unlink([x.id for x in unlink_list]) + invoice_obj.browse(unlink_list).unlink() return res
Fix unlink, >1 filter and lines too long
## Code Before: from openerp import api, models class PurchaseOrderLine(models.Model): _inherit = 'account.analytic.account' @api.multi def _recurring_create_invoice(self, automatic=False): invoice_obj = self.env['account.invoice'] invoices = invoice_obj.browse( super(PurchaseOrderLine, self)._recurring_create_invoice(automatic)) res = [] unlink_list = [] for partner in invoices.mapped('partner_id'): inv_to_merge = invoices.filtered( lambda x: x.partner_id.id == partner) if partner.contract_invoice_merge: invoices_merged = inv_to_merge.do_merge() res.extend(invoices_merged) unlink_list.extend(inv_to_merge) else: res.extend(inv_to_merge) if unlink_list: invoice_obj.unlink([x.id for x in unlink_list]) return res ## Instruction: Fix unlink, >1 filter and lines too long ## Code After: from openerp import api, models class PurchaseOrderLine(models.Model): _inherit = 'account.analytic.account' @api.multi def _recurring_create_invoice(self, automatic=False): invoice_obj = self.env['account.invoice'] invoices = invoice_obj.browse( super(PurchaseOrderLine, self)._recurring_create_invoice( automatic)) res = [] unlink_list = [] for partner in invoices.mapped('partner_id'): inv_to_merge = invoices.filtered( lambda x: x.partner_id.id == partner) if partner.contract_invoice_merge and len(inv_to_merge) > 1: invoices_merged = inv_to_merge.do_merge() res.extend(invoices_merged) unlink_list.extend(inv_to_merge) else: res.extend(inv_to_merge) if unlink_list: invoice_obj.browse(unlink_list).unlink() return res
from openerp import api, models class PurchaseOrderLine(models.Model): _inherit = 'account.analytic.account' @api.multi def _recurring_create_invoice(self, automatic=False): invoice_obj = self.env['account.invoice'] invoices = invoice_obj.browse( - super(PurchaseOrderLine, self)._recurring_create_invoice(automatic)) ? ----------- + super(PurchaseOrderLine, self)._recurring_create_invoice( + automatic)) res = [] unlink_list = [] for partner in invoices.mapped('partner_id'): inv_to_merge = invoices.filtered( lambda x: x.partner_id.id == partner) - if partner.contract_invoice_merge: + if partner.contract_invoice_merge and len(inv_to_merge) > 1: ? ++++++++++++++++++++++++++ invoices_merged = inv_to_merge.do_merge() res.extend(invoices_merged) unlink_list.extend(inv_to_merge) else: res.extend(inv_to_merge) if unlink_list: - invoice_obj.unlink([x.id for x in unlink_list]) + invoice_obj.browse(unlink_list).unlink() return res
da9c0743657ecc890c2a8503ea4bbb681ae00178
tests/chainer_tests/functions_tests/math_tests/test_arctanh.py
tests/chainer_tests/functions_tests/math_tests/test_arctanh.py
import unittest from chainer import testing import chainer.functions as F import numpy def make_data(shape, dtype): # Input values close to -1 or 1 would make tests unstable x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False) gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False) ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False) return x, gy, ggx @testing.unary_math_function_unittest(F.arctanh, make_data=make_data) class TestArctanh(unittest.TestCase): pass
import unittest from chainer import testing import chainer.functions as F import numpy def make_data(shape, dtype): # Input values close to -1 or 1 would make tests unstable x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False) gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False) ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False) return x, gy, ggx @testing.unary_math_function_unittest(F.arctanh, make_data=make_data) class TestArctanh(unittest.TestCase): pass testing.run_module(__name__, __file__)
Call testing.run_module at the end of the test
Call testing.run_module at the end of the test
Python
mit
okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,wkentaro/chainer,okuta/chainer,chainer/chainer,niboshi/chainer,okuta/chainer,pfnet/chainer,chainer/chainer,tkerola/chainer,chainer/chainer,niboshi/chainer,keisuke-umezawa/chainer,okuta/chainer,wkentaro/chainer,hvy/chainer,wkentaro/chainer,niboshi/chainer,niboshi/chainer,keisuke-umezawa/chainer,chainer/chainer,hvy/chainer,keisuke-umezawa/chainer,hvy/chainer,hvy/chainer
import unittest from chainer import testing import chainer.functions as F import numpy def make_data(shape, dtype): # Input values close to -1 or 1 would make tests unstable x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False) gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False) ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False) return x, gy, ggx @testing.unary_math_function_unittest(F.arctanh, make_data=make_data) class TestArctanh(unittest.TestCase): pass + + testing.run_module(__name__, __file__) +
Call testing.run_module at the end of the test
## Code Before: import unittest from chainer import testing import chainer.functions as F import numpy def make_data(shape, dtype): # Input values close to -1 or 1 would make tests unstable x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False) gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False) ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False) return x, gy, ggx @testing.unary_math_function_unittest(F.arctanh, make_data=make_data) class TestArctanh(unittest.TestCase): pass ## Instruction: Call testing.run_module at the end of the test ## Code After: import unittest from chainer import testing import chainer.functions as F import numpy def make_data(shape, dtype): # Input values close to -1 or 1 would make tests unstable x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False) gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False) ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False) return x, gy, ggx @testing.unary_math_function_unittest(F.arctanh, make_data=make_data) class TestArctanh(unittest.TestCase): pass testing.run_module(__name__, __file__)
import unittest from chainer import testing import chainer.functions as F import numpy def make_data(shape, dtype): # Input values close to -1 or 1 would make tests unstable x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False) gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False) ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False) return x, gy, ggx @testing.unary_math_function_unittest(F.arctanh, make_data=make_data) class TestArctanh(unittest.TestCase): pass + + + testing.run_module(__name__, __file__)
a0211fa99dfb0647bf78ce672ebb3a778f6fb6b7
flaskext/lesscss.py
flaskext/lesscss.py
import os, subprocess def lesscss(app): @app.before_request def _render_less_css(): static_dir = app.root_path + app.static_path less_paths = [] for path, subdirs, filenames in os.walk(static_dir): less_paths.extend([ os.path.join(path, f) for f in filenames if os.path.splitext(f)[1] == '.less' ]) for less_path in less_paths: css_path = os.path.splitext(less_path)[0] + '.css' css_mtime, less_mtime = os.path.getmtime(css_path), os.path.getmtime(less_path) if less_mtime >= css_mtime: subprocess.call(['lessc', less_path, css_path], shell=False)
import os, subprocess def lesscss(app): @app.before_request def _render_less_css(): static_dir = app.root_path + app.static_path less_paths = [] for path, subdirs, filenames in os.walk(static_dir): less_paths.extend([ os.path.join(path, f) for f in filenames if os.path.splitext(f)[1] == '.less' ]) for less_path in less_paths: css_path = os.path.splitext(less_path)[0] + '.css' if not os.path.isfile(css_path): css_mtime = -1 else: css_mtime = os.path.getmtime(css_path) less_mtime = os.path.getmtime(less_path) if less_mtime >= css_mtime: subprocess.call(['lessc', less_path, css_path], shell=False)
Fix errors when the css files do not exist.
Fix errors when the css files do not exist.
Python
mit
bpollack/flask-lesscss,fitoria/flask-lesscss,b4oshany/flask-lesscss,fitoria/flask-lesscss,sjl/flask-lesscss
import os, subprocess def lesscss(app): @app.before_request def _render_less_css(): static_dir = app.root_path + app.static_path less_paths = [] for path, subdirs, filenames in os.walk(static_dir): less_paths.extend([ os.path.join(path, f) for f in filenames if os.path.splitext(f)[1] == '.less' ]) for less_path in less_paths: css_path = os.path.splitext(less_path)[0] + '.css' - css_mtime, less_mtime = os.path.getmtime(css_path), os.path.getmtime(less_path) + if not os.path.isfile(css_path): + css_mtime = -1 + else: + css_mtime = os.path.getmtime(css_path) + less_mtime = os.path.getmtime(less_path) if less_mtime >= css_mtime: subprocess.call(['lessc', less_path, css_path], shell=False)
Fix errors when the css files do not exist.
## Code Before: import os, subprocess def lesscss(app): @app.before_request def _render_less_css(): static_dir = app.root_path + app.static_path less_paths = [] for path, subdirs, filenames in os.walk(static_dir): less_paths.extend([ os.path.join(path, f) for f in filenames if os.path.splitext(f)[1] == '.less' ]) for less_path in less_paths: css_path = os.path.splitext(less_path)[0] + '.css' css_mtime, less_mtime = os.path.getmtime(css_path), os.path.getmtime(less_path) if less_mtime >= css_mtime: subprocess.call(['lessc', less_path, css_path], shell=False) ## Instruction: Fix errors when the css files do not exist. ## Code After: import os, subprocess def lesscss(app): @app.before_request def _render_less_css(): static_dir = app.root_path + app.static_path less_paths = [] for path, subdirs, filenames in os.walk(static_dir): less_paths.extend([ os.path.join(path, f) for f in filenames if os.path.splitext(f)[1] == '.less' ]) for less_path in less_paths: css_path = os.path.splitext(less_path)[0] + '.css' if not os.path.isfile(css_path): css_mtime = -1 else: css_mtime = os.path.getmtime(css_path) less_mtime = os.path.getmtime(less_path) if less_mtime >= css_mtime: subprocess.call(['lessc', less_path, css_path], shell=False)
import os, subprocess def lesscss(app): @app.before_request def _render_less_css(): static_dir = app.root_path + app.static_path less_paths = [] for path, subdirs, filenames in os.walk(static_dir): less_paths.extend([ os.path.join(path, f) for f in filenames if os.path.splitext(f)[1] == '.less' ]) for less_path in less_paths: css_path = os.path.splitext(less_path)[0] + '.css' - css_mtime, less_mtime = os.path.getmtime(css_path), os.path.getmtime(less_path) + if not os.path.isfile(css_path): + css_mtime = -1 + else: + css_mtime = os.path.getmtime(css_path) + less_mtime = os.path.getmtime(less_path) if less_mtime >= css_mtime: subprocess.call(['lessc', less_path, css_path], shell=False)
4a2b7b775d65aa95f160e1b1f16b7101fbd1e949
jellyblog/models.py
jellyblog/models.py
from django.db import models class Category(models.Model): category_id = models.AutoField(primary_key=True) category_parent_id = models.IntegerField(null=True) category_name = models.CharField(max_length=20) class Document(models.Model): document_id = models.AutoField(primary_key=True) category_id = models.ForeignKey(Category) document_title = models.CharField(max_length=100) document_content = models.TextField() document_time = models.DateTimeField()
import datetime from django.db import models from django.utils import timezone class Category(models.Model): def __str__(self): return self.category_name category_id = models.AutoField(primary_key=True) category_parent_id = models.IntegerField(null=True) category_name = models.CharField(max_length=20) class Document(models.Model): def __str__(self): return self.choice_text document_id = models.AutoField(primary_key=True) category = models.ForeignKey(Category) document_title = models.CharField(max_length=100) document_content = models.TextField() document_time = models.DateTimeField()
Document 모델의 category 칼럼명 수정
Document 모델의 category 칼럼명 수정
Python
apache-2.0
kyunooh/JellyBlog,kyunooh/JellyBlog,kyunooh/JellyBlog
+ import datetime + from django.db import models + from django.utils import timezone + class Category(models.Model): + def __str__(self): + return self.category_name category_id = models.AutoField(primary_key=True) category_parent_id = models.IntegerField(null=True) category_name = models.CharField(max_length=20) class Document(models.Model): + def __str__(self): + return self.choice_text document_id = models.AutoField(primary_key=True) - category_id = models.ForeignKey(Category) + category = models.ForeignKey(Category) document_title = models.CharField(max_length=100) document_content = models.TextField() document_time = models.DateTimeField()
Document 모델의 category 칼럼명 수정
## Code Before: from django.db import models class Category(models.Model): category_id = models.AutoField(primary_key=True) category_parent_id = models.IntegerField(null=True) category_name = models.CharField(max_length=20) class Document(models.Model): document_id = models.AutoField(primary_key=True) category_id = models.ForeignKey(Category) document_title = models.CharField(max_length=100) document_content = models.TextField() document_time = models.DateTimeField() ## Instruction: Document 모델의 category 칼럼명 수정 ## Code After: import datetime from django.db import models from django.utils import timezone class Category(models.Model): def __str__(self): return self.category_name category_id = models.AutoField(primary_key=True) category_parent_id = models.IntegerField(null=True) category_name = models.CharField(max_length=20) class Document(models.Model): def __str__(self): return self.choice_text document_id = models.AutoField(primary_key=True) category = models.ForeignKey(Category) document_title = models.CharField(max_length=100) document_content = models.TextField() document_time = models.DateTimeField()
+ import datetime + from django.db import models + from django.utils import timezone + class Category(models.Model): + def __str__(self): + return self.category_name category_id = models.AutoField(primary_key=True) category_parent_id = models.IntegerField(null=True) category_name = models.CharField(max_length=20) class Document(models.Model): + def __str__(self): + return self.choice_text document_id = models.AutoField(primary_key=True) - category_id = models.ForeignKey(Category) ? --- + category = models.ForeignKey(Category) document_title = models.CharField(max_length=100) document_content = models.TextField() document_time = models.DateTimeField()
3b9a86bdb85aa04c2f2a0e40387f56d65fb54d46
bin/trigger_upload.py
bin/trigger_upload.py
""" Triggers an upload process with the specified raw.xz URL. """ import argparse import logging import logging.config import multiprocessing.pool import fedmsg.config import fedimg.uploader logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') def trigger_upload(compose_id, url, push_notifications): upload_pool = multiprocessing.pool.ThreadPool(processes=4) compose_meta = {'compose_id': compose_id} fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta, push_notifications=push_notifications) def get_args(): parser = argparse.ArgumentParser( description="Trigger a manual upload process with the " "specified raw.xz URL") parser.add_argument( "-u", "--url", type=str, help=".raw.xz URL", required=True) parser.add_argument( "-c", "--compose-id", type=str, help="compose id of the .raw.xz file", required=True) parser.add_argument( "-p", "--push-notifications", help="Bool to check if we need to push fedmsg notifications", action="store_true", required=False) args = parser.parse_args() return args.url, args.compose_id, args.push_notifications def main(): url, compose_id, push_notifications = get_args() trigger_upload(url, compose_id, push_notifications) if __name__ == '__main__': main()
""" Triggers an upload process with the specified raw.xz URL. """ import argparse import logging import logging.config import multiprocessing.pool import fedmsg.config import fedimg.uploader logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') def trigger_upload(compose_id, url, push_notifications): upload_pool = multiprocessing.pool.ThreadPool(processes=4) fedimg.uploader.upload(upload_pool, [url], compose_id=compose_id, push_notifications=push_notifications) def get_args(): parser = argparse.ArgumentParser( description="Trigger a manual upload process with the " "specified raw.xz URL") parser.add_argument( "-u", "--url", type=str, help=".raw.xz URL", required=True) parser.add_argument( "-c", "--compose-id", type=str, help="compose id of the .raw.xz file", required=True) parser.add_argument( "-p", "--push-notifications", help="Bool to check if we need to push fedmsg notifications", action="store_true", required=False) args = parser.parse_args() return args.url, args.compose_id, args.push_notifications def main(): url, compose_id, push_notifications = get_args() trigger_upload(url, compose_id, push_notifications) if __name__ == '__main__': main()
Fix the script to send proper format of compose id
scripts: Fix the script to send proper format of compose id Signed-off-by: Sayan Chowdhury <5f0367a2b3b757615b57f51d912cf16f2c0ad827@gmail.com>
Python
agpl-3.0
fedora-infra/fedimg,fedora-infra/fedimg
""" Triggers an upload process with the specified raw.xz URL. """ import argparse import logging import logging.config import multiprocessing.pool import fedmsg.config import fedimg.uploader logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') def trigger_upload(compose_id, url, push_notifications): upload_pool = multiprocessing.pool.ThreadPool(processes=4) - compose_meta = {'compose_id': compose_id} - fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta, + fedimg.uploader.upload(upload_pool, [url], + compose_id=compose_id, - push_notifications=push_notifications) + push_notifications=push_notifications) def get_args(): parser = argparse.ArgumentParser( description="Trigger a manual upload process with the " "specified raw.xz URL") parser.add_argument( "-u", "--url", type=str, help=".raw.xz URL", required=True) parser.add_argument( "-c", "--compose-id", type=str, help="compose id of the .raw.xz file", required=True) parser.add_argument( "-p", "--push-notifications", help="Bool to check if we need to push fedmsg notifications", action="store_true", required=False) args = parser.parse_args() return args.url, args.compose_id, args.push_notifications def main(): url, compose_id, push_notifications = get_args() trigger_upload(url, compose_id, push_notifications) if __name__ == '__main__': main()
Fix the script to send proper format of compose id
## Code Before: """ Triggers an upload process with the specified raw.xz URL. """ import argparse import logging import logging.config import multiprocessing.pool import fedmsg.config import fedimg.uploader logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') def trigger_upload(compose_id, url, push_notifications): upload_pool = multiprocessing.pool.ThreadPool(processes=4) compose_meta = {'compose_id': compose_id} fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta, push_notifications=push_notifications) def get_args(): parser = argparse.ArgumentParser( description="Trigger a manual upload process with the " "specified raw.xz URL") parser.add_argument( "-u", "--url", type=str, help=".raw.xz URL", required=True) parser.add_argument( "-c", "--compose-id", type=str, help="compose id of the .raw.xz file", required=True) parser.add_argument( "-p", "--push-notifications", help="Bool to check if we need to push fedmsg notifications", action="store_true", required=False) args = parser.parse_args() return args.url, args.compose_id, args.push_notifications def main(): url, compose_id, push_notifications = get_args() trigger_upload(url, compose_id, push_notifications) if __name__ == '__main__': main() ## Instruction: Fix the script to send proper format of compose id ## Code After: """ Triggers an upload process with the specified raw.xz URL. """ import argparse import logging import logging.config import multiprocessing.pool import fedmsg.config import fedimg.uploader logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') def trigger_upload(compose_id, url, push_notifications): upload_pool = multiprocessing.pool.ThreadPool(processes=4) fedimg.uploader.upload(upload_pool, [url], compose_id=compose_id, push_notifications=push_notifications) def get_args(): parser = argparse.ArgumentParser( description="Trigger a manual upload process with the " "specified raw.xz URL") parser.add_argument( "-u", "--url", type=str, help=".raw.xz URL", required=True) parser.add_argument( "-c", "--compose-id", type=str, help="compose id of the .raw.xz file", required=True) parser.add_argument( "-p", "--push-notifications", help="Bool to check if we need to push fedmsg notifications", action="store_true", required=False) args = parser.parse_args() return args.url, args.compose_id, args.push_notifications def main(): url, compose_id, push_notifications = get_args() trigger_upload(url, compose_id, push_notifications) if __name__ == '__main__': main()
""" Triggers an upload process with the specified raw.xz URL. """ import argparse import logging import logging.config import multiprocessing.pool import fedmsg.config import fedimg.uploader logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLogger('fedmsg') def trigger_upload(compose_id, url, push_notifications): upload_pool = multiprocessing.pool.ThreadPool(processes=4) - compose_meta = {'compose_id': compose_id} - fedimg.uploader.upload(upload_pool, [url], compose_meta=compose_meta, ? --------------------------- + fedimg.uploader.upload(upload_pool, [url], + compose_id=compose_id, - push_notifications=push_notifications) + push_notifications=push_notifications) ? +++++++++++++++ def get_args(): parser = argparse.ArgumentParser( description="Trigger a manual upload process with the " "specified raw.xz URL") parser.add_argument( "-u", "--url", type=str, help=".raw.xz URL", required=True) parser.add_argument( "-c", "--compose-id", type=str, help="compose id of the .raw.xz file", required=True) parser.add_argument( "-p", "--push-notifications", help="Bool to check if we need to push fedmsg notifications", action="store_true", required=False) args = parser.parse_args() return args.url, args.compose_id, args.push_notifications def main(): url, compose_id, push_notifications = get_args() trigger_upload(url, compose_id, push_notifications) if __name__ == '__main__': main()
0774388eec3e405966828d5e2137abbd3dd29f1c
createcppfiles.py
createcppfiles.py
import sys import os def createHeader(guard, namespace): return "#ifndef {}_HPP\n#define {}_HPP\n\n{}\n\n#endif".format(guard, guard, namespace) def createSource(name, namespace): return '#include "{}.hpp"\n\n{}'.format(name, namespace) def createNamespace(namespace): return "namespace {}\n{{\n\n}}".format(namespace) if len(sys.argv) > 1: path, name = os.path.split(sys.argv[1]) if not name: print("No name specified") sys.exit(1) if path: path += "/" namespace = createNamespace(sys.argv[2]) if len(sys.argv) > 2 else "" guard = name.replace(" ", "_").upper() name = name.replace(" ", "") # Remove spaces for filename path += name with open(path + ".hpp", "w") as f: f.write(createHeader(guard, namespace)) with open(path + ".cpp", "w") as f: f.write(createSource(name, namespace)) else: print("Create a C++ header and source file.") print("Usage:\n\t{} <fname> [namespace]".format(sys.argv[0])) print("\n<fname>\t\tThe name of the file. Spaces will be removed. Include guards will have the same name but spaces replaced with underscores (_).") print("[namespace]\tA namespace (what a surprise).")
import sys import os def createHeader(guard, namespace): return "#ifndef {}_HPP\n#define {}_HPP\n\n{}\n\n#endif".format(guard, guard, namespace) def createSource(name, namespace): return '#include "{}.hpp"\n\n{}'.format(name, namespace) def createNamespace(namespace): return "namespace {}\n{{\n\n}}".format(namespace) if len(sys.argv) > 1: path, name = os.path.split(sys.argv[1]) if not name: print("No name specified") sys.exit(1) if path: path += "/" namespace = createNamespace(sys.argv[2]) if len(sys.argv) > 2 else "" if namespace: guard = "{}_{}".format(sys.argv[2], name.replace(" ", "_")).upper() else: guard = name.replace(" ", "_").upper() name = name.replace(" ", "") # Remove spaces for filename path += name with open(path + ".hpp", "w") as f: f.write(createHeader(guard, namespace)) with open(path + ".cpp", "w") as f: f.write(createSource(name, namespace)) else: print("Create a C++ header and source file.") print("Usage:\n\t{} <fname> [namespace]".format(sys.argv[0])) print("\n<fname>\t\tThe name of the file. Spaces will be removed. Include guards will have the same name but spaces replaced with underscores (_).") print("[namespace]\tA namespace (what a surprise).")
Prepend namespace in include guards
Prepend namespace in include guards
Python
mit
mphe/scripts,mall0c/scripts,mall0c/scripts,mphe/scripts
import sys import os def createHeader(guard, namespace): return "#ifndef {}_HPP\n#define {}_HPP\n\n{}\n\n#endif".format(guard, guard, namespace) - + def createSource(name, namespace): return '#include "{}.hpp"\n\n{}'.format(name, namespace) def createNamespace(namespace): return "namespace {}\n{{\n\n}}".format(namespace) if len(sys.argv) > 1: path, name = os.path.split(sys.argv[1]) if not name: print("No name specified") sys.exit(1) if path: path += "/" namespace = createNamespace(sys.argv[2]) if len(sys.argv) > 2 else "" + + if namespace: + guard = "{}_{}".format(sys.argv[2], name.replace(" ", "_")).upper() + else: - guard = name.replace(" ", "_").upper() + guard = name.replace(" ", "_").upper() + name = name.replace(" ", "") # Remove spaces for filename path += name with open(path + ".hpp", "w") as f: f.write(createHeader(guard, namespace)) - + with open(path + ".cpp", "w") as f: f.write(createSource(name, namespace)) else: print("Create a C++ header and source file.") print("Usage:\n\t{} <fname> [namespace]".format(sys.argv[0])) print("\n<fname>\t\tThe name of the file. Spaces will be removed. Include guards will have the same name but spaces replaced with underscores (_).") print("[namespace]\tA namespace (what a surprise).")
Prepend namespace in include guards
## Code Before: import sys import os def createHeader(guard, namespace): return "#ifndef {}_HPP\n#define {}_HPP\n\n{}\n\n#endif".format(guard, guard, namespace) def createSource(name, namespace): return '#include "{}.hpp"\n\n{}'.format(name, namespace) def createNamespace(namespace): return "namespace {}\n{{\n\n}}".format(namespace) if len(sys.argv) > 1: path, name = os.path.split(sys.argv[1]) if not name: print("No name specified") sys.exit(1) if path: path += "/" namespace = createNamespace(sys.argv[2]) if len(sys.argv) > 2 else "" guard = name.replace(" ", "_").upper() name = name.replace(" ", "") # Remove spaces for filename path += name with open(path + ".hpp", "w") as f: f.write(createHeader(guard, namespace)) with open(path + ".cpp", "w") as f: f.write(createSource(name, namespace)) else: print("Create a C++ header and source file.") print("Usage:\n\t{} <fname> [namespace]".format(sys.argv[0])) print("\n<fname>\t\tThe name of the file. Spaces will be removed. Include guards will have the same name but spaces replaced with underscores (_).") print("[namespace]\tA namespace (what a surprise).") ## Instruction: Prepend namespace in include guards ## Code After: import sys import os def createHeader(guard, namespace): return "#ifndef {}_HPP\n#define {}_HPP\n\n{}\n\n#endif".format(guard, guard, namespace) def createSource(name, namespace): return '#include "{}.hpp"\n\n{}'.format(name, namespace) def createNamespace(namespace): return "namespace {}\n{{\n\n}}".format(namespace) if len(sys.argv) > 1: path, name = os.path.split(sys.argv[1]) if not name: print("No name specified") sys.exit(1) if path: path += "/" namespace = createNamespace(sys.argv[2]) if len(sys.argv) > 2 else "" if namespace: guard = "{}_{}".format(sys.argv[2], name.replace(" ", "_")).upper() else: guard = name.replace(" ", "_").upper() name = name.replace(" ", "") # Remove spaces for filename path += name with open(path + ".hpp", "w") as f: f.write(createHeader(guard, namespace)) with open(path + ".cpp", "w") as f: f.write(createSource(name, namespace)) else: print("Create a C++ header and source file.") print("Usage:\n\t{} <fname> [namespace]".format(sys.argv[0])) print("\n<fname>\t\tThe name of the file. Spaces will be removed. Include guards will have the same name but spaces replaced with underscores (_).") print("[namespace]\tA namespace (what a surprise).")
import sys import os def createHeader(guard, namespace): return "#ifndef {}_HPP\n#define {}_HPP\n\n{}\n\n#endif".format(guard, guard, namespace) - + def createSource(name, namespace): return '#include "{}.hpp"\n\n{}'.format(name, namespace) def createNamespace(namespace): return "namespace {}\n{{\n\n}}".format(namespace) if len(sys.argv) > 1: path, name = os.path.split(sys.argv[1]) if not name: print("No name specified") sys.exit(1) if path: path += "/" namespace = createNamespace(sys.argv[2]) if len(sys.argv) > 2 else "" + + if namespace: + guard = "{}_{}".format(sys.argv[2], name.replace(" ", "_")).upper() + else: - guard = name.replace(" ", "_").upper() + guard = name.replace(" ", "_").upper() ? ++++ + name = name.replace(" ", "") # Remove spaces for filename path += name with open(path + ".hpp", "w") as f: f.write(createHeader(guard, namespace)) - + with open(path + ".cpp", "w") as f: f.write(createSource(name, namespace)) else: print("Create a C++ header and source file.") print("Usage:\n\t{} <fname> [namespace]".format(sys.argv[0])) print("\n<fname>\t\tThe name of the file. Spaces will be removed. Include guards will have the same name but spaces replaced with underscores (_).") print("[namespace]\tA namespace (what a surprise).")
067bbbc6c9edbf55606fe6f236c70affd86a1fc0
tests/convert/test_unit.py
tests/convert/test_unit.py
from unittest.mock import patch from smif.convert.unit import parse_unit def test_parse_unit_valid(): """Parse a valid unit """ meter = parse_unit('m') assert str(meter) == 'meter' @patch('smif.convert.unit.LOGGER.warning') def test_parse_unit_invalid(warning_logger): """Warn if unit not recognised """ unit = 'unrecognisable' parse_unit(unit) msg = "Unrecognised unit: %s" warning_logger.assert_called_with(msg, unit)
import numpy as np from unittest.mock import patch from smif.convert.unit import parse_unit from smif.convert import UnitConvertor def test_parse_unit_valid(): """Parse a valid unit """ meter = parse_unit('m') assert str(meter) == 'meter' @patch('smif.convert.unit.LOGGER.warning') def test_parse_unit_invalid(warning_logger): """Warn if unit not recognised """ unit = 'unrecognisable' parse_unit(unit) msg = "Unrecognised unit: %s" warning_logger.assert_called_with(msg, unit) def test_convert_unit(): data = np.array([[1, 2], [3, 4]], dtype=float) convertor = UnitConvertor() actual = convertor.convert(data, 'liter', 'milliliter') expected = np.array([[1000, 2000], [3000, 4000]], dtype=float) np.allclose(actual, expected)
Add test for normal unit conversion
Add test for normal unit conversion
Python
mit
tomalrussell/smif,tomalrussell/smif,nismod/smif,nismod/smif,tomalrussell/smif,nismod/smif,nismod/smif,willu47/smif,willu47/smif,willu47/smif,willu47/smif,tomalrussell/smif
+ import numpy as np from unittest.mock import patch from smif.convert.unit import parse_unit + from smif.convert import UnitConvertor def test_parse_unit_valid(): """Parse a valid unit """ meter = parse_unit('m') assert str(meter) == 'meter' @patch('smif.convert.unit.LOGGER.warning') def test_parse_unit_invalid(warning_logger): """Warn if unit not recognised """ unit = 'unrecognisable' parse_unit(unit) msg = "Unrecognised unit: %s" warning_logger.assert_called_with(msg, unit) + + def test_convert_unit(): + + data = np.array([[1, 2], [3, 4]], dtype=float) + + convertor = UnitConvertor() + actual = convertor.convert(data, 'liter', 'milliliter') + + expected = np.array([[1000, 2000], [3000, 4000]], dtype=float) + + np.allclose(actual, expected) +
Add test for normal unit conversion
## Code Before: from unittest.mock import patch from smif.convert.unit import parse_unit def test_parse_unit_valid(): """Parse a valid unit """ meter = parse_unit('m') assert str(meter) == 'meter' @patch('smif.convert.unit.LOGGER.warning') def test_parse_unit_invalid(warning_logger): """Warn if unit not recognised """ unit = 'unrecognisable' parse_unit(unit) msg = "Unrecognised unit: %s" warning_logger.assert_called_with(msg, unit) ## Instruction: Add test for normal unit conversion ## Code After: import numpy as np from unittest.mock import patch from smif.convert.unit import parse_unit from smif.convert import UnitConvertor def test_parse_unit_valid(): """Parse a valid unit """ meter = parse_unit('m') assert str(meter) == 'meter' @patch('smif.convert.unit.LOGGER.warning') def test_parse_unit_invalid(warning_logger): """Warn if unit not recognised """ unit = 'unrecognisable' parse_unit(unit) msg = "Unrecognised unit: %s" warning_logger.assert_called_with(msg, unit) def test_convert_unit(): data = np.array([[1, 2], [3, 4]], dtype=float) convertor = UnitConvertor() actual = convertor.convert(data, 'liter', 'milliliter') expected = np.array([[1000, 2000], [3000, 4000]], dtype=float) np.allclose(actual, expected)
+ import numpy as np from unittest.mock import patch from smif.convert.unit import parse_unit + from smif.convert import UnitConvertor def test_parse_unit_valid(): """Parse a valid unit """ meter = parse_unit('m') assert str(meter) == 'meter' @patch('smif.convert.unit.LOGGER.warning') def test_parse_unit_invalid(warning_logger): """Warn if unit not recognised """ unit = 'unrecognisable' parse_unit(unit) msg = "Unrecognised unit: %s" warning_logger.assert_called_with(msg, unit) + + + def test_convert_unit(): + + data = np.array([[1, 2], [3, 4]], dtype=float) + + convertor = UnitConvertor() + actual = convertor.convert(data, 'liter', 'milliliter') + + expected = np.array([[1000, 2000], [3000, 4000]], dtype=float) + + np.allclose(actual, expected)
3af2a5b6eda4af972e3a208e727483384f313cb9
octotribble/csv2tex.py
octotribble/csv2tex.py
"""Convert a CSV table into a latex tabular using pandas.""" import argparse import pandas as pd def convert(filename, transpose=False): """convert csv to tex table.""" df = pd.read_csv(filename) if transpose: df = df.transpose() tex_name = filename.replace(".csv", "_transpose.tex") else: tex_name = filename.replace(".csv", ".tex") with open(tex_name, "w") as f: f.write(r"\begin{table}") f.write("\n") f.write(r"\label{}") f.write("\n") f.write(r"\caption{}") f.write("\n") f.write(df.to_latex(na_rep="-")) f.write(r"\end{table}") f.write("\n") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Convert csv to latex tabular") parser.add_argument("filename", help="Name of csv file", type=str) parser.add_argument( "-t", "--transpose", help="Transpose table", action="store_true" ) args = parser.parse_args() convert(args.filename, args.transpose)
"""Convert a CSV table into a latex tabular using pandas.""" import argparse import pandas as pd def convert(filename, transpose=False): """convert csv to tex table.""" df = pd.read_csv(filename) if transpose: df = df.transpose() tex_name = filename.replace(".csv", "_transpose.tex") index = True else: tex_name = filename.replace(".csv", ".tex") index=False assert tex_name != filename, "This will overwrite the file, did you pass in a csv?" latex = df.to_latex(na_rep="-", index=index) with open(tex_name, "w") as f: f.write(r"\begin{table}") f.write("\n") f.write(r"\label{}") f.write("\n") f.write(r"\caption{}") f.write("\n") f.write(latex) f.write(r"\end{table}") f.write("\n") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Convert csv to latex tabular") parser.add_argument("filename", help="Name of csv file", type=str) parser.add_argument( "-t", "--transpose", help="Transpose table", action="store_true" ) args = parser.parse_args() convert(args.filename, args.transpose)
Remove index and check filename
Remove index and check filename
Python
mit
jason-neal/equanimous-octo-tribble,jason-neal/equanimous-octo-tribble,jason-neal/equanimous-octo-tribble
"""Convert a CSV table into a latex tabular using pandas.""" import argparse import pandas as pd def convert(filename, transpose=False): """convert csv to tex table.""" df = pd.read_csv(filename) if transpose: df = df.transpose() tex_name = filename.replace(".csv", "_transpose.tex") + index = True else: tex_name = filename.replace(".csv", ".tex") + index=False + + assert tex_name != filename, "This will overwrite the file, did you pass in a csv?" + + + latex = df.to_latex(na_rep="-", index=index) + with open(tex_name, "w") as f: f.write(r"\begin{table}") f.write("\n") f.write(r"\label{}") f.write("\n") f.write(r"\caption{}") f.write("\n") - f.write(df.to_latex(na_rep="-")) + f.write(latex) f.write(r"\end{table}") f.write("\n") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Convert csv to latex tabular") parser.add_argument("filename", help="Name of csv file", type=str) parser.add_argument( "-t", "--transpose", help="Transpose table", action="store_true" ) args = parser.parse_args() convert(args.filename, args.transpose)
Remove index and check filename
## Code Before: """Convert a CSV table into a latex tabular using pandas.""" import argparse import pandas as pd def convert(filename, transpose=False): """convert csv to tex table.""" df = pd.read_csv(filename) if transpose: df = df.transpose() tex_name = filename.replace(".csv", "_transpose.tex") else: tex_name = filename.replace(".csv", ".tex") with open(tex_name, "w") as f: f.write(r"\begin{table}") f.write("\n") f.write(r"\label{}") f.write("\n") f.write(r"\caption{}") f.write("\n") f.write(df.to_latex(na_rep="-")) f.write(r"\end{table}") f.write("\n") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Convert csv to latex tabular") parser.add_argument("filename", help="Name of csv file", type=str) parser.add_argument( "-t", "--transpose", help="Transpose table", action="store_true" ) args = parser.parse_args() convert(args.filename, args.transpose) ## Instruction: Remove index and check filename ## Code After: """Convert a CSV table into a latex tabular using pandas.""" import argparse import pandas as pd def convert(filename, transpose=False): """convert csv to tex table.""" df = pd.read_csv(filename) if transpose: df = df.transpose() tex_name = filename.replace(".csv", "_transpose.tex") index = True else: tex_name = filename.replace(".csv", ".tex") index=False assert tex_name != filename, "This will overwrite the file, did you pass in a csv?" latex = df.to_latex(na_rep="-", index=index) with open(tex_name, "w") as f: f.write(r"\begin{table}") f.write("\n") f.write(r"\label{}") f.write("\n") f.write(r"\caption{}") f.write("\n") f.write(latex) f.write(r"\end{table}") f.write("\n") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Convert csv to latex tabular") parser.add_argument("filename", help="Name of csv file", type=str) parser.add_argument( "-t", "--transpose", help="Transpose table", action="store_true" ) args = parser.parse_args() convert(args.filename, args.transpose)
"""Convert a CSV table into a latex tabular using pandas.""" import argparse import pandas as pd def convert(filename, transpose=False): """convert csv to tex table.""" df = pd.read_csv(filename) if transpose: df = df.transpose() tex_name = filename.replace(".csv", "_transpose.tex") + index = True else: tex_name = filename.replace(".csv", ".tex") + index=False + + assert tex_name != filename, "This will overwrite the file, did you pass in a csv?" + + + latex = df.to_latex(na_rep="-", index=index) + with open(tex_name, "w") as f: f.write(r"\begin{table}") f.write("\n") f.write(r"\label{}") f.write("\n") f.write(r"\caption{}") f.write("\n") - f.write(df.to_latex(na_rep="-")) + f.write(latex) f.write(r"\end{table}") f.write("\n") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Convert csv to latex tabular") parser.add_argument("filename", help="Name of csv file", type=str) parser.add_argument( "-t", "--transpose", help="Transpose table", action="store_true" ) args = parser.parse_args() convert(args.filename, args.transpose)
964da81ef5a90130a47ff726839798a7a7b716ef
buildcert.py
buildcert.py
import datetime from subprocess import call from ca import app, db, mail from ca.models import Request from flask import Flask, render_template from flask_mail import Message def mail_certificate(id, email): msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) msg.body = render_template('mail.txt') with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp: msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
import datetime from subprocess import call from ca import app, db, mail from ca.models import Request from flask import Flask, render_template from flask_mail import Message def mail_certificate(id, email): with app.app_context(): msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) msg.body = render_template('mail.txt') with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp: msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
Add app.context() to populate context for render_template
Add app.context() to populate context for render_template
Python
mit
freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net
import datetime from subprocess import call from ca import app, db, mail from ca.models import Request from flask import Flask, render_template from flask_mail import Message def mail_certificate(id, email): + with app.app_context(): - msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) + msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) - msg.body = render_template('mail.txt') + msg.body = render_template('mail.txt') - with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp: + with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp: - msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) + msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) - mail.send(msg) + mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
Add app.context() to populate context for render_template
## Code Before: import datetime from subprocess import call from ca import app, db, mail from ca.models import Request from flask import Flask, render_template from flask_mail import Message def mail_certificate(id, email): msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) msg.body = render_template('mail.txt') with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp: msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n') ## Instruction: Add app.context() to populate context for render_template ## Code After: import datetime from subprocess import call from ca import app, db, mail from ca.models import Request from flask import Flask, render_template from flask_mail import Message def mail_certificate(id, email): with app.app_context(): msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) msg.body = render_template('mail.txt') with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp: msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) mail.send(msg) for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
import datetime from subprocess import call from ca import app, db, mail from ca.models import Request from flask import Flask, render_template from flask_mail import Message def mail_certificate(id, email): + with app.app_context(): - msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) + msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca.berlin.freifunk.net', recipients = [email]) ? ++++ - msg.body = render_template('mail.txt') + msg.body = render_template('mail.txt') ? ++++ - with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp: + with app.open_resource("/etc/openvpn/clients/freifunk_{}.tgz".format(id)) as fp: ? ++++ - msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) + msg.attach("freifunk_{}.tgz".format(id), "application/gzip", fp.read()) ? ++++ - mail.send(msg) + mail.send(msg) ? ++++ for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(request.id, request.email)) print("Type y to continue") confirm = input('>') if confirm in ['Y', 'y']: print('generating certificate') call([app.config['COMMAND_BUILD'], request.id, request.email]) #call([app.config['COMMAND_MAIL'], request.id, request.email]) mail_certificate(request.id, request.email) request.generation_date = datetime.date.today() db.session.commit() print() else: print('skipping generation \n')
2d9fce5715b2d7d5b920d2e77212f076e9ebd1be
staticgen_demo/staticgen_views.py
staticgen_demo/staticgen_views.py
from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView class StaicgenDemoStaticViews(StaticgenView): def items(self): return ( 'sitemap.xml', 'robots.txt', 'page_not_found', 'server_error', ) staticgen_pool.register(StaicgenDemoStaticViews)
from __future__ import unicode_literals from django.conf import settings from django.utils import translation from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView class StaicgenDemoStaticViews(StaticgenView): def items(self): return ( 'sitemap.xml', 'robots.txt', 'page_not_found', 'server_error', ) staticgen_pool.register(StaicgenDemoStaticViews) class StaticgenCMSView(StaticgenView): def items(self): try: from cms.models import Title except ImportError: # pragma: no cover # django-cms is not installed. return super(StaticgenCMSView, self).items() items = Title.objects.public().filter( page__login_required=False, page__site_id=settings.SITE_ID, ).order_by('page__path') return items def url(self, obj): translation.activate(obj.language) url = obj.page.get_absolute_url(obj.language) translation.deactivate() return url staticgen_pool.register(StaticgenCMSView)
Add CMS Pages to staticgen registry.
Add CMS Pages to staticgen registry.
Python
bsd-3-clause
mishbahr/staticgen-demo,mishbahr/staticgen-demo,mishbahr/staticgen-demo
from __future__ import unicode_literals + + from django.conf import settings + from django.utils import translation from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView class StaicgenDemoStaticViews(StaticgenView): def items(self): return ( 'sitemap.xml', 'robots.txt', 'page_not_found', 'server_error', ) staticgen_pool.register(StaicgenDemoStaticViews) + + class StaticgenCMSView(StaticgenView): + + def items(self): + try: + from cms.models import Title + except ImportError: # pragma: no cover + # django-cms is not installed. + return super(StaticgenCMSView, self).items() + + items = Title.objects.public().filter( + page__login_required=False, + page__site_id=settings.SITE_ID, + ).order_by('page__path') + return items + + def url(self, obj): + translation.activate(obj.language) + url = obj.page.get_absolute_url(obj.language) + translation.deactivate() + return url + + staticgen_pool.register(StaticgenCMSView) +
Add CMS Pages to staticgen registry.
## Code Before: from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView class StaicgenDemoStaticViews(StaticgenView): def items(self): return ( 'sitemap.xml', 'robots.txt', 'page_not_found', 'server_error', ) staticgen_pool.register(StaicgenDemoStaticViews) ## Instruction: Add CMS Pages to staticgen registry. ## Code After: from __future__ import unicode_literals from django.conf import settings from django.utils import translation from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView class StaicgenDemoStaticViews(StaticgenView): def items(self): return ( 'sitemap.xml', 'robots.txt', 'page_not_found', 'server_error', ) staticgen_pool.register(StaicgenDemoStaticViews) class StaticgenCMSView(StaticgenView): def items(self): try: from cms.models import Title except ImportError: # pragma: no cover # django-cms is not installed. return super(StaticgenCMSView, self).items() items = Title.objects.public().filter( page__login_required=False, page__site_id=settings.SITE_ID, ).order_by('page__path') return items def url(self, obj): translation.activate(obj.language) url = obj.page.get_absolute_url(obj.language) translation.deactivate() return url staticgen_pool.register(StaticgenCMSView)
from __future__ import unicode_literals + + from django.conf import settings + from django.utils import translation from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView class StaicgenDemoStaticViews(StaticgenView): def items(self): return ( 'sitemap.xml', 'robots.txt', 'page_not_found', 'server_error', ) staticgen_pool.register(StaicgenDemoStaticViews) + + + class StaticgenCMSView(StaticgenView): + + def items(self): + try: + from cms.models import Title + except ImportError: # pragma: no cover + # django-cms is not installed. + return super(StaticgenCMSView, self).items() + + items = Title.objects.public().filter( + page__login_required=False, + page__site_id=settings.SITE_ID, + ).order_by('page__path') + return items + + def url(self, obj): + translation.activate(obj.language) + url = obj.page.get_absolute_url(obj.language) + translation.deactivate() + return url + + staticgen_pool.register(StaticgenCMSView)
4889f26d51cafca6e36d29e6bcf62f4af6c6712d
openfisca_country_template/entities.py
openfisca_country_template/entities.py
from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', roles = [ { 'key': 'parent', 'plural': 'parents', 'label': u'Parents', 'max': 2, 'subroles': ['first_parent', 'second_parent'] }, { 'key': 'child', 'plural': 'children', 'label': u'Child', } ] ) Person = build_entity( key = "person", plural = "persons", label = u'Person', is_person = True, ) entities = [Household, Person]
from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', roles = [ { 'key': 'parent', 'plural': 'parents', 'label': u'Parents', 'max': 2, 'subroles': ['first_parent', 'second_parent'] }, { 'key': 'child', 'plural': 'children', 'label': u'Child', } ] ) """ A group entity. Contains multiple natural persons with specific roles. From zero to two parents with 'first_parent' and 'second_parent' subroles. And an unlimited number of children. """ Person = build_entity( key = "person", plural = "persons", label = u'Person', is_person = True, ) """ The minimal legal entity on which a legislation might be applied. Represents a natural person. """ entities = [Household, Person]
Add docstring on every entity
Add docstring on every entity
Python
agpl-3.0
openfisca/country-template,openfisca/country-template
from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', roles = [ { 'key': 'parent', 'plural': 'parents', 'label': u'Parents', 'max': 2, 'subroles': ['first_parent', 'second_parent'] }, { 'key': 'child', 'plural': 'children', 'label': u'Child', } ] ) - + """ + A group entity. + Contains multiple natural persons with specific roles. + From zero to two parents with 'first_parent' and 'second_parent' subroles. + And an unlimited number of children. + """ Person = build_entity( key = "person", plural = "persons", label = u'Person', is_person = True, ) + """ + The minimal legal entity on which a legislation might be applied. + Represents a natural person. + """ entities = [Household, Person]
Add docstring on every entity
## Code Before: from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', roles = [ { 'key': 'parent', 'plural': 'parents', 'label': u'Parents', 'max': 2, 'subroles': ['first_parent', 'second_parent'] }, { 'key': 'child', 'plural': 'children', 'label': u'Child', } ] ) Person = build_entity( key = "person", plural = "persons", label = u'Person', is_person = True, ) entities = [Household, Person] ## Instruction: Add docstring on every entity ## Code After: from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', roles = [ { 'key': 'parent', 'plural': 'parents', 'label': u'Parents', 'max': 2, 'subroles': ['first_parent', 'second_parent'] }, { 'key': 'child', 'plural': 'children', 'label': u'Child', } ] ) """ A group entity. Contains multiple natural persons with specific roles. From zero to two parents with 'first_parent' and 'second_parent' subroles. And an unlimited number of children. """ Person = build_entity( key = "person", plural = "persons", label = u'Person', is_person = True, ) """ The minimal legal entity on which a legislation might be applied. Represents a natural person. """ entities = [Household, Person]
from openfisca_core.entities import build_entity Household = build_entity( key = "household", plural = "households", label = u'Household', roles = [ { 'key': 'parent', 'plural': 'parents', 'label': u'Parents', 'max': 2, 'subroles': ['first_parent', 'second_parent'] }, { 'key': 'child', 'plural': 'children', 'label': u'Child', } ] ) - + """ + A group entity. + Contains multiple natural persons with specific roles. + From zero to two parents with 'first_parent' and 'second_parent' subroles. + And an unlimited number of children. + """ Person = build_entity( key = "person", plural = "persons", label = u'Person', is_person = True, ) + """ + The minimal legal entity on which a legislation might be applied. + Represents a natural person. + """ entities = [Household, Person]
7700aad28e7bd0053e3e8dba823b446822e2be73
conftest.py
conftest.py
from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False
from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # Compressors is not fast, disable it in tests. settings.COMPRESS_ENABLED = False # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False
Disable compressor in test suite (compressor makes the test suite run 50% slower)
Disable compressor in test suite (compressor makes the test suite run 50% slower)
Python
bsd-3-clause
mitsuhiko/sentry,JamesMura/sentry,JTCunning/sentry,imankulov/sentry,gencer/sentry,fotinakis/sentry,ewdurbin/sentry,JamesMura/sentry,Natim/sentry,beni55/sentry,jean/sentry,hongliang5623/sentry,kevinlondon/sentry,nicholasserra/sentry,zenefits/sentry,BuildingLink/sentry,argonemyth/sentry,drcapulet/sentry,boneyao/sentry,SilentCircle/sentry,ewdurbin/sentry,gg7/sentry,Kryz/sentry,daevaorn/sentry,looker/sentry,gencer/sentry,llonchj/sentry,camilonova/sentry,jean/sentry,ifduyue/sentry,1tush/sentry,vperron/sentry,zenefits/sentry,vperron/sentry,JamesMura/sentry,rdio/sentry,wujuguang/sentry,NickPresta/sentry,gg7/sentry,Natim/sentry,gencer/sentry,pauloschilling/sentry,llonchj/sentry,BuildingLink/sentry,ngonzalvez/sentry,JTCunning/sentry,argonemyth/sentry,SilentCircle/sentry,SilentCircle/sentry,BuildingLink/sentry,rdio/sentry,hongliang5623/sentry,daevaorn/sentry,NickPresta/sentry,JackDanger/sentry,gencer/sentry,drcapulet/sentry,jean/sentry,korealerts1/sentry,mvaled/sentry,1tush/sentry,wong2/sentry,jean/sentry,zenefits/sentry,ifduyue/sentry,looker/sentry,kevinastone/sentry,fotinakis/sentry,fuziontech/sentry,wujuguang/sentry,mitsuhiko/sentry,korealerts1/sentry,BuildingLink/sentry,songyi199111/sentry,JamesMura/sentry,NickPresta/sentry,JTCunning/sentry,TedaLIEz/sentry,JackDanger/sentry,beni55/sentry,daevaorn/sentry,looker/sentry,felixbuenemann/sentry,ifduyue/sentry,zenefits/sentry,songyi199111/sentry,kevinlondon/sentry,alexm92/sentry,jokey2k/sentry,pauloschilling/sentry,ngonzalvez/sentry,kevinlondon/sentry,beeftornado/sentry,fotinakis/sentry,mvaled/sentry,imankulov/sentry,mvaled/sentry,mvaled/sentry,felixbuenemann/sentry,rdio/sentry,wong2/sentry,boneyao/sentry,ewdurbin/sentry,BayanGroup/sentry,nicholasserra/sentry,looker/sentry,wong2/sentry,beni55/sentry,camilonova/sentry,Kryz/sentry,mvaled/sentry,boneyao/sentry,imankulov/sentry,gg7/sentry,fuziontech/sentry,BuildingLink/sentry,argonemyth/sentry,kevinastone/sentry,BayanGroup/sentry,daevaorn/sentry,alexm92/sentry,nicholasserra/sentry,felixbuenemann/sentry,JamesMura/sentry,beeftornado/sentry,wujuguang/sentry,JackDanger/sentry,songyi199111/sentry,camilonova/sentry,zenefits/sentry,ngonzalvez/sentry,hongliang5623/sentry,jokey2k/sentry,ifduyue/sentry,llonchj/sentry,jean/sentry,gencer/sentry,rdio/sentry,drcapulet/sentry,1tush/sentry,NickPresta/sentry,TedaLIEz/sentry,ifduyue/sentry,kevinastone/sentry,korealerts1/sentry,mvaled/sentry,jokey2k/sentry,beeftornado/sentry,pauloschilling/sentry,BayanGroup/sentry,alexm92/sentry,vperron/sentry,Kryz/sentry,fotinakis/sentry,fuziontech/sentry,SilentCircle/sentry,looker/sentry,TedaLIEz/sentry,Natim/sentry
from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) + # Compressors is not fast, disable it in tests. + settings.COMPRESS_ENABLED = False + # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False
Disable compressor in test suite (compressor makes the test suite run 50% slower)
## Code Before: from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False ## Instruction: Disable compressor in test suite (compressor makes the test suite run 50% slower) ## Code After: from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) # Compressors is not fast, disable it in tests. settings.COMPRESS_ENABLED = False # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False
from django.conf import settings import base64 import os import os.path def pytest_configure(config): if not settings.configured: os.environ['DJANGO_SETTINGS_MODULE'] = 'sentry.conf.server' test_db = os.environ.get('DB', 'sqlite') if test_db == 'mysql': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sentry', 'USER': 'root', }) elif test_db == 'postgres': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'sentry', 'OPTIONS': { 'autocommit': True, } }) elif test_db == 'sqlite': settings.DATABASES['default'].update({ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }) + # Compressors is not fast, disable it in tests. + settings.COMPRESS_ENABLED = False + # override a few things with our test specifics settings.INSTALLED_APPS = tuple(settings.INSTALLED_APPS) + ( 'tests', ) settings.SENTRY_KEY = base64.b64encode(os.urandom(40)) settings.SENTRY_PUBLIC = False
497116839db95bf734ed66e5cf87e986141ad50d
txircd/modules/rfc/cmd_info.py
txircd/modules/rfc/cmd_info.py
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd import version from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class InfoCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "InfoCommand" core = True def hookIRCd(self, ircd): self.ircd = ircd def userCommands(self): return [ ("INFO", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): user.sendMessage(irc.RPL_INFO, ":{} is running txircd-{}".format(self.ircd.name, version)) user.sendMessage(irc.RPL_INFO, ":Originally developed for the Desert Bus for Hope charity fundraiser (http://desertbus.org)") user.sendMessage(irc.RPL_INFO, ":") user.sendMessage(irc.RPL_INFO, ":Developed by ElementalAlchemist <ElementAlchemist7@gmail.com>") user.sendMessage(irc.RPL_INFO, ":Contributors:") user.sendMessage(irc.RPL_INFO, ": Heufneutje") user.sendMessage(irc.RPL_ENDOFINFO, ":End of /INFO list") return True infoCmd = InfoCommand()
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd import version from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class InfoCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "InfoCommand" core = True def hookIRCd(self, ircd): self.ircd = ircd def userCommands(self): return [ ("INFO", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): user.sendMessage(irc.RPL_INFO, ":{} is running txircd-{}".format(self.ircd.name, version)) user.sendMessage(irc.RPL_INFO, ":Originally developed for the Desert Bus for Hope charity fundraiser (http://desertbus.org)") user.sendMessage(irc.RPL_INFO, ":") user.sendMessage(irc.RPL_INFO, ":Developed by ElementalAlchemist <ElementAlchemist7@gmail.com>") user.sendMessage(irc.RPL_INFO, ":Contributors:") user.sendMessage(irc.RPL_INFO, ": Heufneutje") user.sendMessage(irc.RPL_INFO, ": ekimekim") user.sendMessage(irc.RPL_ENDOFINFO, ":End of /INFO list") return True infoCmd = InfoCommand()
Add self to contributors list
Add self to contributors list
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd import version from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class InfoCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "InfoCommand" core = True def hookIRCd(self, ircd): self.ircd = ircd def userCommands(self): return [ ("INFO", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): user.sendMessage(irc.RPL_INFO, ":{} is running txircd-{}".format(self.ircd.name, version)) user.sendMessage(irc.RPL_INFO, ":Originally developed for the Desert Bus for Hope charity fundraiser (http://desertbus.org)") user.sendMessage(irc.RPL_INFO, ":") user.sendMessage(irc.RPL_INFO, ":Developed by ElementalAlchemist <ElementAlchemist7@gmail.com>") user.sendMessage(irc.RPL_INFO, ":Contributors:") user.sendMessage(irc.RPL_INFO, ": Heufneutje") + user.sendMessage(irc.RPL_INFO, ": ekimekim") user.sendMessage(irc.RPL_ENDOFINFO, ":End of /INFO list") return True infoCmd = InfoCommand()
Add self to contributors list
## Code Before: from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd import version from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class InfoCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "InfoCommand" core = True def hookIRCd(self, ircd): self.ircd = ircd def userCommands(self): return [ ("INFO", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): user.sendMessage(irc.RPL_INFO, ":{} is running txircd-{}".format(self.ircd.name, version)) user.sendMessage(irc.RPL_INFO, ":Originally developed for the Desert Bus for Hope charity fundraiser (http://desertbus.org)") user.sendMessage(irc.RPL_INFO, ":") user.sendMessage(irc.RPL_INFO, ":Developed by ElementalAlchemist <ElementAlchemist7@gmail.com>") user.sendMessage(irc.RPL_INFO, ":Contributors:") user.sendMessage(irc.RPL_INFO, ": Heufneutje") user.sendMessage(irc.RPL_ENDOFINFO, ":End of /INFO list") return True infoCmd = InfoCommand() ## Instruction: Add self to contributors list ## Code After: from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd import version from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class InfoCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "InfoCommand" core = True def hookIRCd(self, ircd): self.ircd = ircd def userCommands(self): return [ ("INFO", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): user.sendMessage(irc.RPL_INFO, ":{} is running txircd-{}".format(self.ircd.name, version)) user.sendMessage(irc.RPL_INFO, ":Originally developed for the Desert Bus for Hope charity fundraiser (http://desertbus.org)") user.sendMessage(irc.RPL_INFO, ":") user.sendMessage(irc.RPL_INFO, ":Developed by ElementalAlchemist <ElementAlchemist7@gmail.com>") user.sendMessage(irc.RPL_INFO, ":Contributors:") user.sendMessage(irc.RPL_INFO, ": Heufneutje") user.sendMessage(irc.RPL_INFO, ": ekimekim") user.sendMessage(irc.RPL_ENDOFINFO, ":End of /INFO list") return True infoCmd = InfoCommand()
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd import version from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from zope.interface import implements class InfoCommand(ModuleData, Command): implements(IPlugin, IModuleData, ICommand) name = "InfoCommand" core = True def hookIRCd(self, ircd): self.ircd = ircd def userCommands(self): return [ ("INFO", 1, self) ] def parseParams(self, user, params, prefix, tags): return {} def execute(self, user, data): user.sendMessage(irc.RPL_INFO, ":{} is running txircd-{}".format(self.ircd.name, version)) user.sendMessage(irc.RPL_INFO, ":Originally developed for the Desert Bus for Hope charity fundraiser (http://desertbus.org)") user.sendMessage(irc.RPL_INFO, ":") user.sendMessage(irc.RPL_INFO, ":Developed by ElementalAlchemist <ElementAlchemist7@gmail.com>") user.sendMessage(irc.RPL_INFO, ":Contributors:") user.sendMessage(irc.RPL_INFO, ": Heufneutje") + user.sendMessage(irc.RPL_INFO, ": ekimekim") user.sendMessage(irc.RPL_ENDOFINFO, ":End of /INFO list") return True infoCmd = InfoCommand()