commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
52
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
fuzzy_diff
stringlengths
16
3.18k
da91f170c106c46a0d858e887220bc691066cdaa
tests/dtypes_test.py
tests/dtypes_test.py
from common import * def test_dtype(ds_local): ds = ds_local for name in ds.column_names: assert ds[name].values.dtype == ds.dtype(ds[name]) def test_dtypes(ds_local): ds = ds_local all_dtypes = [np.float64, np.float64, np.float64, np.float64, np.int64, np.int64, 'S25', np.object] np.testing.assert_array_equal(ds.dtypes(columns=None), all_dtypes) some_dtypes = [np.float64, np.int64, 'S25', np.object] np.testing.assert_array_equal(ds.dtypes(columns=['x', 'mi', 'name', 'obj']), some_dtypes)
from common import * def test_dtype(ds_local): ds = ds_local for name in ds.column_names: assert ds[name].values.dtype == ds.dtype(ds[name]) def test_dtypes(ds_local): ds = ds_local assert (ds.dtypes.values == [ds[name].dtype for name in ds.column_names]).all()
Update of the dtypes unit-test.
Update of the dtypes unit-test.
Python
mit
maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex
from common import * def test_dtype(ds_local): ds = ds_local for name in ds.column_names: - assert ds[name].values.dtype == ds.dtype(ds[name]) + assert ds[name].values.dtype == ds.dtype(ds[name]) def test_dtypes(ds_local): ds = ds_local + assert (ds.dtypes.values == [ds[name].dtype for name in ds.column_names]).all() - all_dtypes = [np.float64, np.float64, np.float64, np.float64, np.int64, np.int64, 'S25', np.object] - np.testing.assert_array_equal(ds.dtypes(columns=None), all_dtypes) - some_dtypes = [np.float64, np.int64, 'S25', np.object] - np.testing.assert_array_equal(ds.dtypes(columns=['x', 'mi', 'name', 'obj']), some_dtypes)
Update of the dtypes unit-test.
## Code Before: from common import * def test_dtype(ds_local): ds = ds_local for name in ds.column_names: assert ds[name].values.dtype == ds.dtype(ds[name]) def test_dtypes(ds_local): ds = ds_local all_dtypes = [np.float64, np.float64, np.float64, np.float64, np.int64, np.int64, 'S25', np.object] np.testing.assert_array_equal(ds.dtypes(columns=None), all_dtypes) some_dtypes = [np.float64, np.int64, 'S25', np.object] np.testing.assert_array_equal(ds.dtypes(columns=['x', 'mi', 'name', 'obj']), some_dtypes) ## Instruction: Update of the dtypes unit-test. ## Code After: from common import * def test_dtype(ds_local): ds = ds_local for name in ds.column_names: assert ds[name].values.dtype == ds.dtype(ds[name]) def test_dtypes(ds_local): ds = ds_local assert (ds.dtypes.values == [ds[name].dtype for name in ds.column_names]).all()
... for name in ds.column_names: assert ds[name].values.dtype == ds.dtype(ds[name]) ... ds = ds_local assert (ds.dtypes.values == [ds[name].dtype for name in ds.column_names]).all() ...
c8918e5ee06c3f7ec84124ebfccddb738dca2bfb
test/python_api/default-constructor/sb_communication.py
test/python_api/default-constructor/sb_communication.py
import sys import lldb def fuzz_obj(obj): broadcaster = obj.GetBroadcaster() # Do fuzz testing on the broadcaster obj, it should not crash lldb. import sb_broadcaster sb_broadcaster.fuzz_obj(broadcaster) obj.AdoptFileDesriptor(0, False) obj.AdoptFileDesriptor(1, False) obj.AdoptFileDesriptor(2, False) obj.Connect("file:/tmp/myfile") obj.Disconnect() obj.IsConnected() obj.GetCloseOnEOF() obj.SetCloseOnEOF(True) obj.SetCloseOnEOF(False) #obj.Write(None, sys.maxint, None) #obj.Read(None, sys.maxint, 0xffffffff, None) obj.ReadThreadStart() obj.ReadThreadStop() obj.ReadThreadIsRunning() obj.SetReadThreadBytesReceivedCallback(None, None)
import sys import lldb def fuzz_obj(obj): broadcaster = obj.GetBroadcaster() # Do fuzz testing on the broadcaster obj, it should not crash lldb. import sb_broadcaster sb_broadcaster.fuzz_obj(broadcaster) obj.AdoptFileDesriptor(0, False) obj.AdoptFileDesriptor(1, False) obj.AdoptFileDesriptor(2, False) obj.Connect("file:/tmp/myfile") obj.Connect(None) obj.Disconnect() obj.IsConnected() obj.GetCloseOnEOF() obj.SetCloseOnEOF(True) obj.SetCloseOnEOF(False) #obj.Write(None, sys.maxint, None) #obj.Read(None, sys.maxint, 0xffffffff, None) obj.ReadThreadStart() obj.ReadThreadStop() obj.ReadThreadIsRunning() obj.SetReadThreadBytesReceivedCallback(None, None)
Add a fuzz call for SBCommunication: obj.connect(None).
Add a fuzz call for SBCommunication: obj.connect(None). git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@146912 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb
import sys import lldb def fuzz_obj(obj): broadcaster = obj.GetBroadcaster() # Do fuzz testing on the broadcaster obj, it should not crash lldb. import sb_broadcaster sb_broadcaster.fuzz_obj(broadcaster) obj.AdoptFileDesriptor(0, False) obj.AdoptFileDesriptor(1, False) obj.AdoptFileDesriptor(2, False) obj.Connect("file:/tmp/myfile") + obj.Connect(None) obj.Disconnect() obj.IsConnected() obj.GetCloseOnEOF() obj.SetCloseOnEOF(True) obj.SetCloseOnEOF(False) #obj.Write(None, sys.maxint, None) #obj.Read(None, sys.maxint, 0xffffffff, None) obj.ReadThreadStart() obj.ReadThreadStop() obj.ReadThreadIsRunning() obj.SetReadThreadBytesReceivedCallback(None, None)
Add a fuzz call for SBCommunication: obj.connect(None).
## Code Before: import sys import lldb def fuzz_obj(obj): broadcaster = obj.GetBroadcaster() # Do fuzz testing on the broadcaster obj, it should not crash lldb. import sb_broadcaster sb_broadcaster.fuzz_obj(broadcaster) obj.AdoptFileDesriptor(0, False) obj.AdoptFileDesriptor(1, False) obj.AdoptFileDesriptor(2, False) obj.Connect("file:/tmp/myfile") obj.Disconnect() obj.IsConnected() obj.GetCloseOnEOF() obj.SetCloseOnEOF(True) obj.SetCloseOnEOF(False) #obj.Write(None, sys.maxint, None) #obj.Read(None, sys.maxint, 0xffffffff, None) obj.ReadThreadStart() obj.ReadThreadStop() obj.ReadThreadIsRunning() obj.SetReadThreadBytesReceivedCallback(None, None) ## Instruction: Add a fuzz call for SBCommunication: obj.connect(None). ## Code After: import sys import lldb def fuzz_obj(obj): broadcaster = obj.GetBroadcaster() # Do fuzz testing on the broadcaster obj, it should not crash lldb. import sb_broadcaster sb_broadcaster.fuzz_obj(broadcaster) obj.AdoptFileDesriptor(0, False) obj.AdoptFileDesriptor(1, False) obj.AdoptFileDesriptor(2, False) obj.Connect("file:/tmp/myfile") obj.Connect(None) obj.Disconnect() obj.IsConnected() obj.GetCloseOnEOF() obj.SetCloseOnEOF(True) obj.SetCloseOnEOF(False) #obj.Write(None, sys.maxint, None) #obj.Read(None, sys.maxint, 0xffffffff, None) obj.ReadThreadStart() obj.ReadThreadStop() obj.ReadThreadIsRunning() obj.SetReadThreadBytesReceivedCallback(None, None)
... obj.Connect("file:/tmp/myfile") obj.Connect(None) obj.Disconnect() ...
a8c8b136f081e3a2c7f1fd1f833a85288a358e42
vumi_http_retry/workers/api/validate.py
vumi_http_retry/workers/api/validate.py
import json from functools import wraps from twisted.web import http from jsonschema import Draft4Validator from vumi_http_retry.workers.api.utils import response def validate(*validators): def validator(fn): @wraps(fn) def wrapper(api, req, *a, **kw): errors = [] for v in validators: errors.extend(v(req, *a, **kw) or []) if not errors: return fn(api, req, *a, **kw) else: return response(req, {'errors': errors}, code=http.BAD_REQUEST) return wrapper return validator def has_header(name): def validator(req): if not req.requestHeaders.hasHeader(name): return [{ 'type': 'header_missing', 'message': "Header '%s' is missing" % (name,) }] else: return [] return validator def body_schema(schema): json_validator = Draft4Validator(schema) def validator(req, body): return [{ 'type': 'invalid_body', 'message': e.message } for e in json_validator.iter_errors(body)] return validator
import json from functools import wraps from twisted.web import http from jsonschema import Draft4Validator from vumi_http_retry.workers.api.utils import response def validate(*validators): def validator(fn): @wraps(fn) def wrapper(api, req, *a, **kw): errors = [] for v in validators: errors.extend(v(req, *a, **kw) or []) if not errors: return fn(api, req, *a, **kw) else: return response(req, {'errors': errors}, code=http.BAD_REQUEST) return wrapper return validator def has_header(name): def validator(req, *a, **kw): if not req.requestHeaders.hasHeader(name): return [{ 'type': 'header_missing', 'message': "Header '%s' is missing" % (name,) }] else: return [] return validator def body_schema(schema): json_validator = Draft4Validator(schema) def validator(req, body, *a, **kw): return [{ 'type': 'invalid_body', 'message': e.message } for e in json_validator.iter_errors(body)] return validator
Change validators to allow additional arguments to be given to the functions they are wrapping
Change validators to allow additional arguments to be given to the functions they are wrapping
Python
bsd-3-clause
praekelt/vumi-http-retry-api,praekelt/vumi-http-retry-api
import json from functools import wraps from twisted.web import http from jsonschema import Draft4Validator from vumi_http_retry.workers.api.utils import response def validate(*validators): def validator(fn): @wraps(fn) def wrapper(api, req, *a, **kw): errors = [] for v in validators: errors.extend(v(req, *a, **kw) or []) if not errors: return fn(api, req, *a, **kw) else: return response(req, {'errors': errors}, code=http.BAD_REQUEST) return wrapper return validator def has_header(name): - def validator(req): + def validator(req, *a, **kw): if not req.requestHeaders.hasHeader(name): return [{ 'type': 'header_missing', 'message': "Header '%s' is missing" % (name,) }] else: return [] return validator def body_schema(schema): json_validator = Draft4Validator(schema) - def validator(req, body): + def validator(req, body, *a, **kw): return [{ 'type': 'invalid_body', 'message': e.message } for e in json_validator.iter_errors(body)] return validator
Change validators to allow additional arguments to be given to the functions they are wrapping
## Code Before: import json from functools import wraps from twisted.web import http from jsonschema import Draft4Validator from vumi_http_retry.workers.api.utils import response def validate(*validators): def validator(fn): @wraps(fn) def wrapper(api, req, *a, **kw): errors = [] for v in validators: errors.extend(v(req, *a, **kw) or []) if not errors: return fn(api, req, *a, **kw) else: return response(req, {'errors': errors}, code=http.BAD_REQUEST) return wrapper return validator def has_header(name): def validator(req): if not req.requestHeaders.hasHeader(name): return [{ 'type': 'header_missing', 'message': "Header '%s' is missing" % (name,) }] else: return [] return validator def body_schema(schema): json_validator = Draft4Validator(schema) def validator(req, body): return [{ 'type': 'invalid_body', 'message': e.message } for e in json_validator.iter_errors(body)] return validator ## Instruction: Change validators to allow additional arguments to be given to the functions they are wrapping ## Code After: import json from functools import wraps from twisted.web import http from jsonschema import Draft4Validator from vumi_http_retry.workers.api.utils import response def validate(*validators): def validator(fn): @wraps(fn) def wrapper(api, req, *a, **kw): errors = [] for v in validators: errors.extend(v(req, *a, **kw) or []) if not errors: return fn(api, req, *a, **kw) else: return response(req, {'errors': errors}, code=http.BAD_REQUEST) return wrapper return validator def has_header(name): def validator(req, *a, **kw): if not req.requestHeaders.hasHeader(name): return [{ 'type': 'header_missing', 'message': "Header '%s' is missing" % (name,) }] else: return [] return validator def body_schema(schema): json_validator = Draft4Validator(schema) def validator(req, body, *a, **kw): return [{ 'type': 'invalid_body', 'message': e.message } for e in json_validator.iter_errors(body)] return validator
// ... existing code ... def has_header(name): def validator(req, *a, **kw): if not req.requestHeaders.hasHeader(name): // ... modified code ... def validator(req, body, *a, **kw): return [{ // ... rest of the code ...
e1fc818b8d563c00c77060cd74d2781b287c0b5d
xnuplot/__init__.py
xnuplot/__init__.py
from .plot import Plot, SPlot __all__ = ["gnuplot", "numplot"]
from .plot import Plot, SPlot __all__ = ["Plot", "SPlot", "gnuplot", "numplot"]
Include Plot, SPlot in xnuplot.__all__.
Include Plot, SPlot in xnuplot.__all__.
Python
mit
marktsuchida/Xnuplot
from .plot import Plot, SPlot - __all__ = ["gnuplot", "numplot"] + __all__ = ["Plot", "SPlot", "gnuplot", "numplot"]
Include Plot, SPlot in xnuplot.__all__.
## Code Before: from .plot import Plot, SPlot __all__ = ["gnuplot", "numplot"] ## Instruction: Include Plot, SPlot in xnuplot.__all__. ## Code After: from .plot import Plot, SPlot __all__ = ["Plot", "SPlot", "gnuplot", "numplot"]
// ... existing code ... from .plot import Plot, SPlot __all__ = ["Plot", "SPlot", "gnuplot", "numplot"] // ... rest of the code ...
78154a63e86774fb8952f42883f7788e94d0c8d2
lib/spack/spack/operating_systems/linux_distro.py
lib/spack/spack/operating_systems/linux_distro.py
import re from external.distro import linux_distribution from spack.architecture import OperatingSystem class LinuxDistro(OperatingSystem): """ This class will represent the autodetected operating system for a Linux System. Since there are many different flavors of Linux, this class will attempt to encompass them all through autodetection using the python module platform and the method platform.dist() """ def __init__(self): distname, version, _ = linux_distribution( full_distribution_name=False) distname, version = str(distname), str(version) # Grabs major version from tuple on redhat; on other platforms # grab the first legal identifier in the version field. On # debian you get things like 'wheezy/sid'; sid means unstable. # We just record 'wheezy' and don't get quite so detailed. version = re.split(r'[^\w-]', version)[0] super(LinuxDistro, self).__init__(distname, version)
import re from spack.architecture import OperatingSystem class LinuxDistro(OperatingSystem): """ This class will represent the autodetected operating system for a Linux System. Since there are many different flavors of Linux, this class will attempt to encompass them all through autodetection using the python module platform and the method platform.dist() """ def __init__(self): try: # This will throw an error if imported on a non-Linux platform. from external.distro import linux_distribution distname, version, _ = linux_distribution( full_distribution_name=False) distname, version = str(distname), str(version) except ImportError as e: distname, version = 'unknown', '' # Grabs major version from tuple on redhat; on other platforms # grab the first legal identifier in the version field. On # debian you get things like 'wheezy/sid'; sid means unstable. # We just record 'wheezy' and don't get quite so detailed. version = re.split(r'[^\w-]', version)[0] super(LinuxDistro, self).__init__(distname, version)
Fix bug in distribution detection on unsupported platforms.
Fix bug in distribution detection on unsupported platforms.
Python
lgpl-2.1
EmreAtes/spack,TheTimmy/spack,mfherbst/spack,tmerrick1/spack,iulian787/spack,skosukhin/spack,matthiasdiener/spack,mfherbst/spack,lgarren/spack,EmreAtes/spack,iulian787/spack,EmreAtes/spack,matthiasdiener/spack,mfherbst/spack,LLNL/spack,TheTimmy/spack,skosukhin/spack,skosukhin/spack,LLNL/spack,krafczyk/spack,krafczyk/spack,mfherbst/spack,matthiasdiener/spack,LLNL/spack,tmerrick1/spack,krafczyk/spack,TheTimmy/spack,iulian787/spack,krafczyk/spack,TheTimmy/spack,matthiasdiener/spack,lgarren/spack,iulian787/spack,tmerrick1/spack,EmreAtes/spack,mfherbst/spack,matthiasdiener/spack,lgarren/spack,tmerrick1/spack,iulian787/spack,lgarren/spack,lgarren/spack,krafczyk/spack,skosukhin/spack,LLNL/spack,EmreAtes/spack,skosukhin/spack,TheTimmy/spack,tmerrick1/spack,LLNL/spack
import re - from external.distro import linux_distribution from spack.architecture import OperatingSystem class LinuxDistro(OperatingSystem): """ This class will represent the autodetected operating system for a Linux System. Since there are many different flavors of Linux, this class will attempt to encompass them all through autodetection using the python module platform and the method platform.dist() """ def __init__(self): + try: + # This will throw an error if imported on a non-Linux platform. + from external.distro import linux_distribution - distname, version, _ = linux_distribution( + distname, version, _ = linux_distribution( - full_distribution_name=False) + full_distribution_name=False) - distname, version = str(distname), str(version) + distname, version = str(distname), str(version) + except ImportError as e: + distname, version = 'unknown', '' # Grabs major version from tuple on redhat; on other platforms # grab the first legal identifier in the version field. On # debian you get things like 'wheezy/sid'; sid means unstable. # We just record 'wheezy' and don't get quite so detailed. version = re.split(r'[^\w-]', version)[0] super(LinuxDistro, self).__init__(distname, version)
Fix bug in distribution detection on unsupported platforms.
## Code Before: import re from external.distro import linux_distribution from spack.architecture import OperatingSystem class LinuxDistro(OperatingSystem): """ This class will represent the autodetected operating system for a Linux System. Since there are many different flavors of Linux, this class will attempt to encompass them all through autodetection using the python module platform and the method platform.dist() """ def __init__(self): distname, version, _ = linux_distribution( full_distribution_name=False) distname, version = str(distname), str(version) # Grabs major version from tuple on redhat; on other platforms # grab the first legal identifier in the version field. On # debian you get things like 'wheezy/sid'; sid means unstable. # We just record 'wheezy' and don't get quite so detailed. version = re.split(r'[^\w-]', version)[0] super(LinuxDistro, self).__init__(distname, version) ## Instruction: Fix bug in distribution detection on unsupported platforms. ## Code After: import re from spack.architecture import OperatingSystem class LinuxDistro(OperatingSystem): """ This class will represent the autodetected operating system for a Linux System. Since there are many different flavors of Linux, this class will attempt to encompass them all through autodetection using the python module platform and the method platform.dist() """ def __init__(self): try: # This will throw an error if imported on a non-Linux platform. from external.distro import linux_distribution distname, version, _ = linux_distribution( full_distribution_name=False) distname, version = str(distname), str(version) except ImportError as e: distname, version = 'unknown', '' # Grabs major version from tuple on redhat; on other platforms # grab the first legal identifier in the version field. On # debian you get things like 'wheezy/sid'; sid means unstable. # We just record 'wheezy' and don't get quite so detailed. version = re.split(r'[^\w-]', version)[0] super(LinuxDistro, self).__init__(distname, version)
... import re from spack.architecture import OperatingSystem ... def __init__(self): try: # This will throw an error if imported on a non-Linux platform. from external.distro import linux_distribution distname, version, _ = linux_distribution( full_distribution_name=False) distname, version = str(distname), str(version) except ImportError as e: distname, version = 'unknown', '' ...
17fbd2f3fa24da128cb5cabef4a8c94b59b50b0c
sqrl/client/crypt.py
sqrl/client/crypt.py
import ed25519 import hmac from sqrl.utils import baseconv class Crypt: """ Crypt - Creating site specific key pair - Signing SRQL response - Providing public key """ def __init__(self, masterkey): self.masterkey = masterkey def _site_key_pair(self, domain): seed = self._site_seed(domain) sk = ed25519.SigningKey(seed) vk = sk.get_verifying_key() return sk, vk def _site_seed(self, domain): """ Generates a seed to based on the masterkey and the current site you authenicating with The seed is used to generate the key pair used for signing the request body """ key = self.masterkey local_hmac = hmac.new(key) local_hmac.update(domain) return local_hmac.hexdigest() def sign(self, value): signed = self.sk.sign(value) return baseconv.encode(signed) def getPublicKey(self, domain): self.sk, self.vk = self._site_key_pair(domain) key = self.vk.to_bytes() return baseconv.encode(key)
import ed25519 import hmac import baseconv class Crypt: """ Crypt - Creating site specific key pair - Signing SRQL response - Providing public key """ def __init__(self, masterkey): self.masterkey = masterkey def _site_key_pair(self, domain): seed = self._site_seed(domain) sk = ed25519.SigningKey(seed) vk = sk.get_verifying_key() return sk, vk def _site_seed(self, domain): """ Generates a seed to based on the masterkey and the current site you authenicating with The seed is used to generate the key pair used for signing the request body """ key = self.masterkey local_hmac = hmac.new(key) local_hmac.update(domain) return local_hmac.hexdigest() def sign(self, value): signed = self.sk.sign(value) return baseconv.encode(signed) def getPublicKey(self, domain): self.sk, self.vk = self._site_key_pair(domain) key = self.vk.to_bytes() return baseconv.encode(key)
Fix up imports after module has moved
Fix up imports after module has moved
Python
mit
vegarwe/sqrl,vegarwe/sqrl,vegarwe/sqrl,vegarwe/sqrl
import ed25519 import hmac - from sqrl.utils import baseconv + import baseconv class Crypt: """ Crypt - Creating site specific key pair - Signing SRQL response - Providing public key """ def __init__(self, masterkey): self.masterkey = masterkey def _site_key_pair(self, domain): seed = self._site_seed(domain) sk = ed25519.SigningKey(seed) vk = sk.get_verifying_key() return sk, vk def _site_seed(self, domain): """ Generates a seed to based on the masterkey and the current site you authenicating with The seed is used to generate the key pair used for signing the request body """ key = self.masterkey local_hmac = hmac.new(key) local_hmac.update(domain) return local_hmac.hexdigest() def sign(self, value): signed = self.sk.sign(value) return baseconv.encode(signed) def getPublicKey(self, domain): self.sk, self.vk = self._site_key_pair(domain) key = self.vk.to_bytes() return baseconv.encode(key)
Fix up imports after module has moved
## Code Before: import ed25519 import hmac from sqrl.utils import baseconv class Crypt: """ Crypt - Creating site specific key pair - Signing SRQL response - Providing public key """ def __init__(self, masterkey): self.masterkey = masterkey def _site_key_pair(self, domain): seed = self._site_seed(domain) sk = ed25519.SigningKey(seed) vk = sk.get_verifying_key() return sk, vk def _site_seed(self, domain): """ Generates a seed to based on the masterkey and the current site you authenicating with The seed is used to generate the key pair used for signing the request body """ key = self.masterkey local_hmac = hmac.new(key) local_hmac.update(domain) return local_hmac.hexdigest() def sign(self, value): signed = self.sk.sign(value) return baseconv.encode(signed) def getPublicKey(self, domain): self.sk, self.vk = self._site_key_pair(domain) key = self.vk.to_bytes() return baseconv.encode(key) ## Instruction: Fix up imports after module has moved ## Code After: import ed25519 import hmac import baseconv class Crypt: """ Crypt - Creating site specific key pair - Signing SRQL response - Providing public key """ def __init__(self, masterkey): self.masterkey = masterkey def _site_key_pair(self, domain): seed = self._site_seed(domain) sk = ed25519.SigningKey(seed) vk = sk.get_verifying_key() return sk, vk def _site_seed(self, domain): """ Generates a seed to based on the masterkey and the current site you authenicating with The seed is used to generate the key pair used for signing the request body """ key = self.masterkey local_hmac = hmac.new(key) local_hmac.update(domain) return local_hmac.hexdigest() def sign(self, value): signed = self.sk.sign(value) return baseconv.encode(signed) def getPublicKey(self, domain): self.sk, self.vk = self._site_key_pair(domain) key = self.vk.to_bytes() return baseconv.encode(key)
... import hmac import baseconv ...
f0ede3d2c32d4d3adce98cd3b762b672f7af91a9
relay_api/__main__.py
relay_api/__main__.py
from relay_api.api.server import server from relay_api.core.relay import relay from relay_api.conf.config import relays import relay_api.api.server as api for r in relays: relays[r]["instance"] = relay(relays[r]["gpio"], relays[r]["NC"]) @server.route("/relay-api/relays", methods=["GET"]) def get_relays(): return api.get_relays(relays) @server.route("/relay-api/relays/<relay_name>", methods=["GET"]) def get_relay(relay_name): return api.get_relay(relays, relay_name)
from relay_api.api.server import server from relay_api.core.relay import relay from relay_api.conf.config import relays import relay_api.api.server as api relays_dict = {} for r in relays: relays_dict[r] = relay(relays[r]["gpio"], relays[r]["NC"]) @server.route("/relay-api/relays", methods=["GET"]) def get_relays(): return api.get_relays(relays_dict) @server.route("/relay-api/relays/<relay_name>", methods=["GET"]) def get_relay(relay_name): return api.get_relay(relays_dict.get(relay_name, "None"))
Update to generate a dict with the relay instances
Update to generate a dict with the relay instances
Python
mit
pahumadad/raspi-relay-api
from relay_api.api.server import server from relay_api.core.relay import relay from relay_api.conf.config import relays import relay_api.api.server as api + relays_dict = {} for r in relays: + relays_dict[r] = relay(relays[r]["gpio"], relays[r]["NC"]) - relays[r]["instance"] = relay(relays[r]["gpio"], - relays[r]["NC"]) @server.route("/relay-api/relays", methods=["GET"]) def get_relays(): - return api.get_relays(relays) + return api.get_relays(relays_dict) @server.route("/relay-api/relays/<relay_name>", methods=["GET"]) def get_relay(relay_name): - return api.get_relay(relays, relay_name) + return api.get_relay(relays_dict.get(relay_name, "None"))
Update to generate a dict with the relay instances
## Code Before: from relay_api.api.server import server from relay_api.core.relay import relay from relay_api.conf.config import relays import relay_api.api.server as api for r in relays: relays[r]["instance"] = relay(relays[r]["gpio"], relays[r]["NC"]) @server.route("/relay-api/relays", methods=["GET"]) def get_relays(): return api.get_relays(relays) @server.route("/relay-api/relays/<relay_name>", methods=["GET"]) def get_relay(relay_name): return api.get_relay(relays, relay_name) ## Instruction: Update to generate a dict with the relay instances ## Code After: from relay_api.api.server import server from relay_api.core.relay import relay from relay_api.conf.config import relays import relay_api.api.server as api relays_dict = {} for r in relays: relays_dict[r] = relay(relays[r]["gpio"], relays[r]["NC"]) @server.route("/relay-api/relays", methods=["GET"]) def get_relays(): return api.get_relays(relays_dict) @server.route("/relay-api/relays/<relay_name>", methods=["GET"]) def get_relay(relay_name): return api.get_relay(relays_dict.get(relay_name, "None"))
// ... existing code ... relays_dict = {} for r in relays: relays_dict[r] = relay(relays[r]["gpio"], relays[r]["NC"]) // ... modified code ... def get_relays(): return api.get_relays(relays_dict) ... def get_relay(relay_name): return api.get_relay(relays_dict.get(relay_name, "None")) // ... rest of the code ...
acdb2445a5ead7d6ae116f839b1710c65ff08137
nimp/utilities/paths.py
nimp/utilities/paths.py
import os import os.path import shutil import sys import fnmatch import glob from nimp.utilities.logging import * #------------------------------------------------------------------------------- def split_path(path): splitted_path = [] while True: (path, folder) = os.path.split(path) if folder != "": splitted_path.insert(0, folder) else: if path != "": splitted_path.insert(0, path) break return splitted_path #------------------------------------------------------------------------------- # This function is necessary because Python’s makedirs cannot create a # directory such as "d:\data\foo/bar" because it’ll split it as "d:\data" # and "foo/bar" then try to create a directory named "foo/bar". def safe_makedirs(path): if os.sep is '\\': path = path.replace('/', '\\') elif os.sep is '/': path = path.replace('\\', '/') if not os.path.exists(path): os.makedirs(path)
import os import os.path import shutil import sys import fnmatch import glob from nimp.utilities.logging import * #------------------------------------------------------------------------------- def split_path(path): splitted_path = [] while True: (path, folder) = os.path.split(path) if folder != "": splitted_path.insert(0, folder) else: if path != "": splitted_path.insert(0, path) break return splitted_path #------------------------------------------------------------------------------- # This function is necessary because Python’s makedirs cannot create a # directory such as "d:\data\foo/bar" because it’ll split it as "d:\data" # and "foo/bar" then try to create a directory named "foo/bar". def safe_makedirs(path): if os.sep is '\\': path = path.replace('/', '\\') elif os.sep is '/': path = path.replace('\\', '/') try: os.makedirs(path) except FileExistsError: # Maybe someone else created the directory for us; if so, ignore error if os.path.exists(path): return raise
Make safe_makedirs resilient to race conditions.
Make safe_makedirs resilient to race conditions.
Python
mit
dontnod/nimp
import os import os.path import shutil import sys import fnmatch import glob from nimp.utilities.logging import * #------------------------------------------------------------------------------- def split_path(path): splitted_path = [] while True: (path, folder) = os.path.split(path) if folder != "": splitted_path.insert(0, folder) else: if path != "": splitted_path.insert(0, path) break return splitted_path #------------------------------------------------------------------------------- # This function is necessary because Python’s makedirs cannot create a # directory such as "d:\data\foo/bar" because it’ll split it as "d:\data" # and "foo/bar" then try to create a directory named "foo/bar". def safe_makedirs(path): if os.sep is '\\': path = path.replace('/', '\\') elif os.sep is '/': path = path.replace('\\', '/') - if not os.path.exists(path): + + try: os.makedirs(path) + except FileExistsError: + # Maybe someone else created the directory for us; if so, ignore error + if os.path.exists(path): + return + raise
Make safe_makedirs resilient to race conditions.
## Code Before: import os import os.path import shutil import sys import fnmatch import glob from nimp.utilities.logging import * #------------------------------------------------------------------------------- def split_path(path): splitted_path = [] while True: (path, folder) = os.path.split(path) if folder != "": splitted_path.insert(0, folder) else: if path != "": splitted_path.insert(0, path) break return splitted_path #------------------------------------------------------------------------------- # This function is necessary because Python’s makedirs cannot create a # directory such as "d:\data\foo/bar" because it’ll split it as "d:\data" # and "foo/bar" then try to create a directory named "foo/bar". def safe_makedirs(path): if os.sep is '\\': path = path.replace('/', '\\') elif os.sep is '/': path = path.replace('\\', '/') if not os.path.exists(path): os.makedirs(path) ## Instruction: Make safe_makedirs resilient to race conditions. ## Code After: import os import os.path import shutil import sys import fnmatch import glob from nimp.utilities.logging import * #------------------------------------------------------------------------------- def split_path(path): splitted_path = [] while True: (path, folder) = os.path.split(path) if folder != "": splitted_path.insert(0, folder) else: if path != "": splitted_path.insert(0, path) break return splitted_path #------------------------------------------------------------------------------- # This function is necessary because Python’s makedirs cannot create a # directory such as "d:\data\foo/bar" because it’ll split it as "d:\data" # and "foo/bar" then try to create a directory named "foo/bar". def safe_makedirs(path): if os.sep is '\\': path = path.replace('/', '\\') elif os.sep is '/': path = path.replace('\\', '/') try: os.makedirs(path) except FileExistsError: # Maybe someone else created the directory for us; if so, ignore error if os.path.exists(path): return raise
# ... existing code ... path = path.replace('\\', '/') try: os.makedirs(path) except FileExistsError: # Maybe someone else created the directory for us; if so, ignore error if os.path.exists(path): return raise # ... rest of the code ...
97418e6815faacbaa46a3a29bef0c4c0454bede1
urls.py
urls.py
from django.conf import settings from django.conf.urls import url, include urlpatterns = [ url(r'^auth/', include('helios_auth.urls')), url(r'^helios/', include('helios.urls')), # SHOULD BE REPLACED BY APACHE STATIC PATH url(r'booth/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/heliosbooth'}), url(r'verifier/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/heliosverifier'}), url(r'static/auth/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/helios_auth/media'}), url(r'static/helios/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/helios/media'}), url(r'static/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/server_ui/media'}), url(r'^', include('server_ui.urls')), ]
from django.conf import settings from django.conf.urls import url, include from django.views.static import serve urlpatterns = [ url(r'^auth/', include('helios_auth.urls')), url(r'^helios/', include('helios.urls')), # SHOULD BE REPLACED BY APACHE STATIC PATH url(r'booth/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/heliosbooth'}), url(r'verifier/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/heliosverifier'}), url(r'static/auth/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/helios_auth/media'}), url(r'static/helios/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/helios/media'}), url(r'static/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/server_ui/media'}), url(r'^', include('server_ui.urls')), ]
Support for string view arguments to url() will be removed
[DJ1.10] Support for string view arguments to url() will be removed
Python
apache-2.0
benadida/helios-server,shirlei/helios-server,shirlei/helios-server,benadida/helios-server,benadida/helios-server,shirlei/helios-server,benadida/helios-server,shirlei/helios-server,shirlei/helios-server,benadida/helios-server
from django.conf import settings from django.conf.urls import url, include + from django.views.static import serve urlpatterns = [ url(r'^auth/', include('helios_auth.urls')), url(r'^helios/', include('helios.urls')), # SHOULD BE REPLACED BY APACHE STATIC PATH - url(r'booth/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/heliosbooth'}), + url(r'booth/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/heliosbooth'}), - url(r'verifier/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/heliosverifier'}), + url(r'verifier/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/heliosverifier'}), - url(r'static/auth/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/helios_auth/media'}), + url(r'static/auth/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/helios_auth/media'}), - url(r'static/helios/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/helios/media'}), + url(r'static/helios/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/helios/media'}), - url(r'static/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/server_ui/media'}), + url(r'static/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/server_ui/media'}), url(r'^', include('server_ui.urls')), ]
Support for string view arguments to url() will be removed
## Code Before: from django.conf import settings from django.conf.urls import url, include urlpatterns = [ url(r'^auth/', include('helios_auth.urls')), url(r'^helios/', include('helios.urls')), # SHOULD BE REPLACED BY APACHE STATIC PATH url(r'booth/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/heliosbooth'}), url(r'verifier/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/heliosverifier'}), url(r'static/auth/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/helios_auth/media'}), url(r'static/helios/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/helios/media'}), url(r'static/(?P<path>.*)$', 'django.views.static.serve', {'document_root' : settings.ROOT_PATH + '/server_ui/media'}), url(r'^', include('server_ui.urls')), ] ## Instruction: Support for string view arguments to url() will be removed ## Code After: from django.conf import settings from django.conf.urls import url, include from django.views.static import serve urlpatterns = [ url(r'^auth/', include('helios_auth.urls')), url(r'^helios/', include('helios.urls')), # SHOULD BE REPLACED BY APACHE STATIC PATH url(r'booth/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/heliosbooth'}), url(r'verifier/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/heliosverifier'}), url(r'static/auth/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/helios_auth/media'}), url(r'static/helios/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/helios/media'}), url(r'static/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/server_ui/media'}), url(r'^', include('server_ui.urls')), ]
... from django.conf.urls import url, include from django.views.static import serve ... # SHOULD BE REPLACED BY APACHE STATIC PATH url(r'booth/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/heliosbooth'}), url(r'verifier/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/heliosverifier'}), url(r'static/auth/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/helios_auth/media'}), url(r'static/helios/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/helios/media'}), url(r'static/(?P<path>.*)$', serve, {'document_root' : settings.ROOT_PATH + '/server_ui/media'}), ...
7c5061e4fbf0737ce07f13cb9102cdbbacf73115
pyethapp/tests/test_genesis.py
pyethapp/tests/test_genesis.py
import pytest from ethereum import blocks from ethereum.db import DB from ethereum.config import Env from pyethapp.utils import merge_dict from pyethapp.utils import update_config_from_genesis_json import pyethapp.config as konfig from pyethapp.profiles import PROFILES def check_genesis(profile): config = dict(eth=dict()) # Set config values based on profile selection merge_dict(config, PROFILES[profile]) # Load genesis config update_config_from_genesis_json(config, config['eth']['genesis']) konfig.update_config_with_defaults(config, {'eth': {'block': blocks.default_config}}) print config['eth'].keys() bc = config['eth']['block'] print bc.keys() env = Env(DB(), bc) genesis = blocks.genesis(env) print 'genesis.hash', genesis.hash.encode('hex') print 'expected', config['eth']['genesis_hash'] assert genesis.hash == config['eth']['genesis_hash'].decode('hex') @pytest.mark.xfail # FIXME def test_olympic(): check_genesis('olympic') def test_frontier(): check_genesis('frontier') if __name__ == '__main__': test_genesis()
from pprint import pprint import pytest from ethereum import blocks from ethereum.db import DB from ethereum.config import Env from pyethapp.utils import merge_dict from pyethapp.utils import update_config_from_genesis_json import pyethapp.config as konfig from pyethapp.profiles import PROFILES @pytest.mark.parametrize('profile', PROFILES.keys()) def test_profile(profile): config = dict(eth=dict()) konfig.update_config_with_defaults(config, {'eth': {'block': blocks.default_config}}) # Set config values based on profile selection merge_dict(config, PROFILES[profile]) # Load genesis config update_config_from_genesis_json(config, config['eth']['genesis']) bc = config['eth']['block'] pprint(bc) env = Env(DB(), bc) genesis = blocks.genesis(env) assert genesis.hash.encode('hex') == config['eth']['genesis_hash']
Fix & cleanup profile genesis tests
Fix & cleanup profile genesis tests
Python
mit
ethereum/pyethapp,gsalgado/pyethapp,gsalgado/pyethapp,changwu-tw/pyethapp,RomanZacharia/pyethapp,changwu-tw/pyethapp,RomanZacharia/pyethapp,ethereum/pyethapp
+ from pprint import pprint import pytest from ethereum import blocks from ethereum.db import DB from ethereum.config import Env from pyethapp.utils import merge_dict from pyethapp.utils import update_config_from_genesis_json import pyethapp.config as konfig from pyethapp.profiles import PROFILES - def check_genesis(profile): + @pytest.mark.parametrize('profile', PROFILES.keys()) + def test_profile(profile): config = dict(eth=dict()) + + konfig.update_config_with_defaults(config, {'eth': {'block': blocks.default_config}}) # Set config values based on profile selection merge_dict(config, PROFILES[profile]) # Load genesis config update_config_from_genesis_json(config, config['eth']['genesis']) - konfig.update_config_with_defaults(config, {'eth': {'block': blocks.default_config}}) - - print config['eth'].keys() bc = config['eth']['block'] - print bc.keys() + pprint(bc) env = Env(DB(), bc) genesis = blocks.genesis(env) - print 'genesis.hash', genesis.hash.encode('hex') - print 'expected', config['eth']['genesis_hash'] - assert genesis.hash == config['eth']['genesis_hash'].decode('hex') + assert genesis.hash.encode('hex') == config['eth']['genesis_hash'] - - @pytest.mark.xfail # FIXME - def test_olympic(): - check_genesis('olympic') - - - def test_frontier(): - check_genesis('frontier') - - - if __name__ == '__main__': - test_genesis() -
Fix & cleanup profile genesis tests
## Code Before: import pytest from ethereum import blocks from ethereum.db import DB from ethereum.config import Env from pyethapp.utils import merge_dict from pyethapp.utils import update_config_from_genesis_json import pyethapp.config as konfig from pyethapp.profiles import PROFILES def check_genesis(profile): config = dict(eth=dict()) # Set config values based on profile selection merge_dict(config, PROFILES[profile]) # Load genesis config update_config_from_genesis_json(config, config['eth']['genesis']) konfig.update_config_with_defaults(config, {'eth': {'block': blocks.default_config}}) print config['eth'].keys() bc = config['eth']['block'] print bc.keys() env = Env(DB(), bc) genesis = blocks.genesis(env) print 'genesis.hash', genesis.hash.encode('hex') print 'expected', config['eth']['genesis_hash'] assert genesis.hash == config['eth']['genesis_hash'].decode('hex') @pytest.mark.xfail # FIXME def test_olympic(): check_genesis('olympic') def test_frontier(): check_genesis('frontier') if __name__ == '__main__': test_genesis() ## Instruction: Fix & cleanup profile genesis tests ## Code After: from pprint import pprint import pytest from ethereum import blocks from ethereum.db import DB from ethereum.config import Env from pyethapp.utils import merge_dict from pyethapp.utils import update_config_from_genesis_json import pyethapp.config as konfig from pyethapp.profiles import PROFILES @pytest.mark.parametrize('profile', PROFILES.keys()) def test_profile(profile): config = dict(eth=dict()) konfig.update_config_with_defaults(config, {'eth': {'block': blocks.default_config}}) # Set config values based on profile selection merge_dict(config, PROFILES[profile]) # Load genesis config update_config_from_genesis_json(config, config['eth']['genesis']) bc = config['eth']['block'] pprint(bc) env = Env(DB(), bc) genesis = blocks.genesis(env) assert genesis.hash.encode('hex') == config['eth']['genesis_hash']
... from pprint import pprint import pytest ... @pytest.mark.parametrize('profile', PROFILES.keys()) def test_profile(profile): config = dict(eth=dict()) konfig.update_config_with_defaults(config, {'eth': {'block': blocks.default_config}}) ... bc = config['eth']['block'] pprint(bc) env = Env(DB(), bc) ... genesis = blocks.genesis(env) assert genesis.hash.encode('hex') == config['eth']['genesis_hash'] ...
bb4bff73a1eefad6188f1d1544f3b4106b606d36
driller/LibcSimProc.py
driller/LibcSimProc.py
import simuvex from simuvex.s_type import SimTypeFd, SimTypeChar, SimTypeArray, SimTypeLength class DrillerRead(simuvex.SimProcedure): ''' A custom version of read which has a symbolic return value. ''' def run(self, fd, dst, length): self.argument_types = {0: SimTypeFd(), 1: self.ty_ptr(SimTypeArray(SimTypeChar(), length)), 2: SimTypeLength(self.state.arch)} self.return_type = SimTypeLength(self.state.arch) if self.state.se.max_int(length) == 0: return self.state.se.BVV(0, self.state.arch.bits) sym_length = self.state.se.BV("sym_length", self.state.arch.bits) self.state.add_constraints(sym_length <= length) self.state.add_constraints(sym_length >= 0) _ = self.state.posix.pos(fd) data = self.state.posix.read(fd, length) self.state.store_mem(dst, data) return sym_length simprocedures = [("read", DrillerRead)]
import simuvex from simuvex.s_type import SimTypeFd, SimTypeChar, SimTypeArray, SimTypeLength class DrillerRead(simuvex.SimProcedure): ''' A custom version of read which has a symbolic return value. ''' def run(self, fd, dst, length): self.argument_types = {0: SimTypeFd(), 1: self.ty_ptr(SimTypeArray(SimTypeChar(), length)), 2: SimTypeLength(self.state.arch)} self.return_type = SimTypeLength(self.state.arch) if self.state.se.max_int(length) == 0: return self.state.se.BVV(0, self.state.arch.bits) sym_length = self.state.se.BV("sym_length", self.state.arch.bits) self.state.add_constraints(sym_length <= length) self.state.add_constraints(sym_length >= 0) data = self.state.posix.read(fd, length, dst_addr=dst) return sym_length simprocedures = [("read", DrillerRead)]
Update libc's DrillerRead to use the new posix read calling convention to support variable read
Update libc's DrillerRead to use the new posix read calling convention to support variable read
Python
bsd-2-clause
shellphish/driller
import simuvex from simuvex.s_type import SimTypeFd, SimTypeChar, SimTypeArray, SimTypeLength class DrillerRead(simuvex.SimProcedure): ''' A custom version of read which has a symbolic return value. ''' def run(self, fd, dst, length): self.argument_types = {0: SimTypeFd(), 1: self.ty_ptr(SimTypeArray(SimTypeChar(), length)), 2: SimTypeLength(self.state.arch)} self.return_type = SimTypeLength(self.state.arch) if self.state.se.max_int(length) == 0: return self.state.se.BVV(0, self.state.arch.bits) sym_length = self.state.se.BV("sym_length", self.state.arch.bits) self.state.add_constraints(sym_length <= length) self.state.add_constraints(sym_length >= 0) - _ = self.state.posix.pos(fd) - data = self.state.posix.read(fd, length) + data = self.state.posix.read(fd, length, dst_addr=dst) - self.state.store_mem(dst, data) return sym_length simprocedures = [("read", DrillerRead)]
Update libc's DrillerRead to use the new posix read calling convention to support variable read
## Code Before: import simuvex from simuvex.s_type import SimTypeFd, SimTypeChar, SimTypeArray, SimTypeLength class DrillerRead(simuvex.SimProcedure): ''' A custom version of read which has a symbolic return value. ''' def run(self, fd, dst, length): self.argument_types = {0: SimTypeFd(), 1: self.ty_ptr(SimTypeArray(SimTypeChar(), length)), 2: SimTypeLength(self.state.arch)} self.return_type = SimTypeLength(self.state.arch) if self.state.se.max_int(length) == 0: return self.state.se.BVV(0, self.state.arch.bits) sym_length = self.state.se.BV("sym_length", self.state.arch.bits) self.state.add_constraints(sym_length <= length) self.state.add_constraints(sym_length >= 0) _ = self.state.posix.pos(fd) data = self.state.posix.read(fd, length) self.state.store_mem(dst, data) return sym_length simprocedures = [("read", DrillerRead)] ## Instruction: Update libc's DrillerRead to use the new posix read calling convention to support variable read ## Code After: import simuvex from simuvex.s_type import SimTypeFd, SimTypeChar, SimTypeArray, SimTypeLength class DrillerRead(simuvex.SimProcedure): ''' A custom version of read which has a symbolic return value. ''' def run(self, fd, dst, length): self.argument_types = {0: SimTypeFd(), 1: self.ty_ptr(SimTypeArray(SimTypeChar(), length)), 2: SimTypeLength(self.state.arch)} self.return_type = SimTypeLength(self.state.arch) if self.state.se.max_int(length) == 0: return self.state.se.BVV(0, self.state.arch.bits) sym_length = self.state.se.BV("sym_length", self.state.arch.bits) self.state.add_constraints(sym_length <= length) self.state.add_constraints(sym_length >= 0) data = self.state.posix.read(fd, length, dst_addr=dst) return sym_length simprocedures = [("read", DrillerRead)]
... data = self.state.posix.read(fd, length, dst_addr=dst) return sym_length ...
df25af8c12f824ee46a7bbf676f9adfcef5b1624
grazer/run.py
grazer/run.py
import click from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") def main(env, config): load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main()
import click import logging from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") @click.option("--log_level", default="INFO") def main(env, config, log_level): logging.basicConfig(level=getattr(logging, log_level)) load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main()
Allow to config log level
Allow to config log level
Python
mit
CodersOfTheNight/verata
import click + import logging from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") + @click.option("--log_level", default="INFO") - def main(env, config): + def main(env, config, log_level): + logging.basicConfig(level=getattr(logging, log_level)) load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main()
Allow to config log level
## Code Before: import click from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") def main(env, config): load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main() ## Instruction: Allow to config log level ## Code After: import click import logging from dotenv import load_dotenv, find_dotenv from grazer.config import Config from grazer.core import crawler @click.command() @click.option("--env", default=find_dotenv()) @click.option("--config") @click.option("--log_level", default="INFO") def main(env, config, log_level): logging.basicConfig(level=getattr(logging, log_level)) load_dotenv(env) cfg = Config(config) for record, link in crawler.create(cfg): print(record) if __name__ == "__main__": main()
... import click import logging ... @click.option("--config") @click.option("--log_level", default="INFO") def main(env, config, log_level): logging.basicConfig(level=getattr(logging, log_level)) load_dotenv(env) ...
3d97a2ca6c4c285d59e3c823fbee94a494e85ba0
app/tests/tests.py
app/tests/tests.py
import unittest from app import serve class PageCase(unittest.TestCase): def setUp(self): serve.app.config['TESTING'] = True self.app = serve.app.test_client() def test_index_load(self): self.page_test('/', b'') def test_robots_load(self): self.page_test('/robots.txt', b'') def test_sitemap_load(self): self.page_test('/sitemap.xml', b'') def test_not_found(self): response = self.app.get('/asdf') self.assertEqual(response.status_code, 404) self.assertIn(b'Not Found', response.get_data()) def page_test(self, path, string): response = self.app.get(path) self.assertEqual(response.status_code, 200) self.assertIn(string, response.get_data())
import unittest from varsnap import TestVarSnap # noqa: F401 from app import serve class PageCase(unittest.TestCase): def setUp(self): serve.app.config['TESTING'] = True self.app = serve.app.test_client() def test_index_load(self): self.page_test('/', b'') def test_robots_load(self): self.page_test('/robots.txt', b'') def test_sitemap_load(self): self.page_test('/sitemap.xml', b'') def test_not_found(self): response = self.app.get('/asdf') self.assertEqual(response.status_code, 404) self.assertIn(b'Not Found', response.get_data()) def page_test(self, path, string): response = self.app.get(path) self.assertEqual(response.status_code, 200) self.assertIn(string, response.get_data())
Add TestVarSnap as a TestCase
Add TestVarSnap as a TestCase
Python
mit
albertyw/base-flask,albertyw/base-flask,albertyw/base-flask,albertyw/base-flask
import unittest + + from varsnap import TestVarSnap # noqa: F401 from app import serve class PageCase(unittest.TestCase): def setUp(self): serve.app.config['TESTING'] = True self.app = serve.app.test_client() def test_index_load(self): self.page_test('/', b'') def test_robots_load(self): self.page_test('/robots.txt', b'') def test_sitemap_load(self): self.page_test('/sitemap.xml', b'') def test_not_found(self): response = self.app.get('/asdf') self.assertEqual(response.status_code, 404) self.assertIn(b'Not Found', response.get_data()) def page_test(self, path, string): response = self.app.get(path) self.assertEqual(response.status_code, 200) self.assertIn(string, response.get_data())
Add TestVarSnap as a TestCase
## Code Before: import unittest from app import serve class PageCase(unittest.TestCase): def setUp(self): serve.app.config['TESTING'] = True self.app = serve.app.test_client() def test_index_load(self): self.page_test('/', b'') def test_robots_load(self): self.page_test('/robots.txt', b'') def test_sitemap_load(self): self.page_test('/sitemap.xml', b'') def test_not_found(self): response = self.app.get('/asdf') self.assertEqual(response.status_code, 404) self.assertIn(b'Not Found', response.get_data()) def page_test(self, path, string): response = self.app.get(path) self.assertEqual(response.status_code, 200) self.assertIn(string, response.get_data()) ## Instruction: Add TestVarSnap as a TestCase ## Code After: import unittest from varsnap import TestVarSnap # noqa: F401 from app import serve class PageCase(unittest.TestCase): def setUp(self): serve.app.config['TESTING'] = True self.app = serve.app.test_client() def test_index_load(self): self.page_test('/', b'') def test_robots_load(self): self.page_test('/robots.txt', b'') def test_sitemap_load(self): self.page_test('/sitemap.xml', b'') def test_not_found(self): response = self.app.get('/asdf') self.assertEqual(response.status_code, 404) self.assertIn(b'Not Found', response.get_data()) def page_test(self, path, string): response = self.app.get(path) self.assertEqual(response.status_code, 200) self.assertIn(string, response.get_data())
// ... existing code ... import unittest from varsnap import TestVarSnap # noqa: F401 // ... rest of the code ...
5ad869909e95fa8e5e0b6a489d361c42006023a5
openstack/__init__.py
openstack/__init__.py
import pbr.version __version__ = pbr.version.VersionInfo( 'openstack').version_string()
import pbr.version __version__ = pbr.version.VersionInfo( 'python-openstacksdk').version_string()
Use project name to retrieve version info
Use project name to retrieve version info Change-Id: Iaef93bde5183263f900166b8ec90eefb7bfdc99b
Python
apache-2.0
openstack/python-openstacksdk,dudymas/python-openstacksdk,dudymas/python-openstacksdk,mtougeron/python-openstacksdk,mtougeron/python-openstacksdk,openstack/python-openstacksdk,briancurtin/python-openstacksdk,dtroyer/python-openstacksdk,stackforge/python-openstacksdk,briancurtin/python-openstacksdk,stackforge/python-openstacksdk,dtroyer/python-openstacksdk
import pbr.version __version__ = pbr.version.VersionInfo( - 'openstack').version_string() + 'python-openstacksdk').version_string()
Use project name to retrieve version info
## Code Before: import pbr.version __version__ = pbr.version.VersionInfo( 'openstack').version_string() ## Instruction: Use project name to retrieve version info ## Code After: import pbr.version __version__ = pbr.version.VersionInfo( 'python-openstacksdk').version_string()
# ... existing code ... __version__ = pbr.version.VersionInfo( 'python-openstacksdk').version_string() # ... rest of the code ...
d0bf235af3742a17c722488fe3679d5b73a0d945
thinc/neural/_classes/softmax.py
thinc/neural/_classes/softmax.py
from .affine import Affine from ... import describe from ...describe import Dimension, Synapses, Biases from ...check import has_shape from ... import check @describe.attributes( W=Synapses("Weights matrix", lambda obj: (obj.nO, obj.nI), lambda W, ops: None) ) class Softmax(Affine): name = 'softmax' @check.arg(1, has_shape(('nB', 'nI'))) def predict(self, input__BI): output__BO = self.ops.affine(self.W, self.b, input__BI) output__BO = self.ops.softmax(output__BO, inplace=False) return output__BO @check.arg(1, has_shape(('nB', 'nI'))) def begin_update(self, input__BI, drop=0.): output__BO = self.predict(input__BI) @check.arg(0, has_shape(('nB', 'nO'))) def finish_update(grad__BO, sgd=None): self.d_W += self.ops.batch_outer(grad__BO, input__BI) self.d_b += grad__BO.sum(axis=0) grad__BI = self.ops.dot(grad__BO, self.W) if sgd is not None: sgd(self._mem.weights, self._mem.gradient, key=self.id) return grad__BI return output__BO, finish_update
from .affine import Affine from ... import describe from ...describe import Dimension, Synapses, Biases from ...check import has_shape from ... import check @describe.attributes( W=Synapses("Weights matrix", lambda obj: (obj.nO, obj.nI), lambda W, ops: None) ) class Softmax(Affine): name = 'softmax' @check.arg(1, has_shape(('nB', 'nI'))) def predict(self, input__BI): output__BO = self.ops.affine(self.W, self.b, input__BI) output__BO = self.ops.softmax(output__BO, inplace=False) return output__BO @check.arg(1, has_shape(('nB', 'nI'))) def begin_update(self, input__BI, drop=0.): output__BO = self.predict(input__BI) @check.arg(0, has_shape(('nB', 'nO'))) def finish_update(grad__BO, sgd=None): self.d_W += self.ops.gemm(grad__BO, input__BI, trans1=True) self.d_b += grad__BO.sum(axis=0) grad__BI = self.ops.gemm(grad__BO, self.W) if sgd is not None: sgd(self._mem.weights, self._mem.gradient, key=self.id) return grad__BI return output__BO, finish_update
Fix gemm calls in Softmax
Fix gemm calls in Softmax
Python
mit
spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc
from .affine import Affine from ... import describe from ...describe import Dimension, Synapses, Biases from ...check import has_shape from ... import check @describe.attributes( W=Synapses("Weights matrix", lambda obj: (obj.nO, obj.nI), lambda W, ops: None) ) class Softmax(Affine): name = 'softmax' @check.arg(1, has_shape(('nB', 'nI'))) def predict(self, input__BI): output__BO = self.ops.affine(self.W, self.b, input__BI) output__BO = self.ops.softmax(output__BO, inplace=False) return output__BO @check.arg(1, has_shape(('nB', 'nI'))) def begin_update(self, input__BI, drop=0.): output__BO = self.predict(input__BI) @check.arg(0, has_shape(('nB', 'nO'))) def finish_update(grad__BO, sgd=None): - self.d_W += self.ops.batch_outer(grad__BO, input__BI) + self.d_W += self.ops.gemm(grad__BO, input__BI, trans1=True) self.d_b += grad__BO.sum(axis=0) - grad__BI = self.ops.dot(grad__BO, self.W) + grad__BI = self.ops.gemm(grad__BO, self.W) if sgd is not None: sgd(self._mem.weights, self._mem.gradient, key=self.id) return grad__BI return output__BO, finish_update
Fix gemm calls in Softmax
## Code Before: from .affine import Affine from ... import describe from ...describe import Dimension, Synapses, Biases from ...check import has_shape from ... import check @describe.attributes( W=Synapses("Weights matrix", lambda obj: (obj.nO, obj.nI), lambda W, ops: None) ) class Softmax(Affine): name = 'softmax' @check.arg(1, has_shape(('nB', 'nI'))) def predict(self, input__BI): output__BO = self.ops.affine(self.W, self.b, input__BI) output__BO = self.ops.softmax(output__BO, inplace=False) return output__BO @check.arg(1, has_shape(('nB', 'nI'))) def begin_update(self, input__BI, drop=0.): output__BO = self.predict(input__BI) @check.arg(0, has_shape(('nB', 'nO'))) def finish_update(grad__BO, sgd=None): self.d_W += self.ops.batch_outer(grad__BO, input__BI) self.d_b += grad__BO.sum(axis=0) grad__BI = self.ops.dot(grad__BO, self.W) if sgd is not None: sgd(self._mem.weights, self._mem.gradient, key=self.id) return grad__BI return output__BO, finish_update ## Instruction: Fix gemm calls in Softmax ## Code After: from .affine import Affine from ... import describe from ...describe import Dimension, Synapses, Biases from ...check import has_shape from ... import check @describe.attributes( W=Synapses("Weights matrix", lambda obj: (obj.nO, obj.nI), lambda W, ops: None) ) class Softmax(Affine): name = 'softmax' @check.arg(1, has_shape(('nB', 'nI'))) def predict(self, input__BI): output__BO = self.ops.affine(self.W, self.b, input__BI) output__BO = self.ops.softmax(output__BO, inplace=False) return output__BO @check.arg(1, has_shape(('nB', 'nI'))) def begin_update(self, input__BI, drop=0.): output__BO = self.predict(input__BI) @check.arg(0, has_shape(('nB', 'nO'))) def finish_update(grad__BO, sgd=None): self.d_W += self.ops.gemm(grad__BO, input__BI, trans1=True) self.d_b += grad__BO.sum(axis=0) grad__BI = self.ops.gemm(grad__BO, self.W) if sgd is not None: sgd(self._mem.weights, self._mem.gradient, key=self.id) return grad__BI return output__BO, finish_update
... def finish_update(grad__BO, sgd=None): self.d_W += self.ops.gemm(grad__BO, input__BI, trans1=True) self.d_b += grad__BO.sum(axis=0) grad__BI = self.ops.gemm(grad__BO, self.W) if sgd is not None: ...
624276b80b6d69b788b2f48691941cd89847237b
software/Pi/ui.py
software/Pi/ui.py
import RPi.GPIO as gpio import time ledPin = 16 #GPIO23 #Set up RPi GPIO def setup(): gpio.setmode(gpio.BOARD) gpio.setup(ledPin, gpio.OUT) def blink(n): for i in range(0, n): gpio.output(ledPin, True) time.sleep(0.5) gpio.output(ledPin, False) time.sleep(0.5)
import RPi.GPIO as gpio import time ledPin = 16 #GPIO23 #Set up RPi GPIO def setup(): gpio.setmode(gpio.BOARD) gpio.setwarnings(False) gpio.setup(ledPin, gpio.OUT) def blink(n): for i in range(0, n): gpio.output(ledPin, True) time.sleep(0.5) gpio.output(ledPin, False) time.sleep(0.5)
Disable warnings for GPIO channels...
Disable warnings for GPIO channels...
Python
mit
AdlerFarHorizons/eclipse-tracking,AdlerFarHorizons/eclipse-tracking,AdlerFarHorizons/eclipse-tracking,AdlerFarHorizons/eclipse-tracking
import RPi.GPIO as gpio import time ledPin = 16 #GPIO23 #Set up RPi GPIO def setup(): gpio.setmode(gpio.BOARD) + gpio.setwarnings(False) gpio.setup(ledPin, gpio.OUT) def blink(n): for i in range(0, n): gpio.output(ledPin, True) time.sleep(0.5) gpio.output(ledPin, False) time.sleep(0.5)
Disable warnings for GPIO channels...
## Code Before: import RPi.GPIO as gpio import time ledPin = 16 #GPIO23 #Set up RPi GPIO def setup(): gpio.setmode(gpio.BOARD) gpio.setup(ledPin, gpio.OUT) def blink(n): for i in range(0, n): gpio.output(ledPin, True) time.sleep(0.5) gpio.output(ledPin, False) time.sleep(0.5) ## Instruction: Disable warnings for GPIO channels... ## Code After: import RPi.GPIO as gpio import time ledPin = 16 #GPIO23 #Set up RPi GPIO def setup(): gpio.setmode(gpio.BOARD) gpio.setwarnings(False) gpio.setup(ledPin, gpio.OUT) def blink(n): for i in range(0, n): gpio.output(ledPin, True) time.sleep(0.5) gpio.output(ledPin, False) time.sleep(0.5)
# ... existing code ... gpio.setmode(gpio.BOARD) gpio.setwarnings(False) gpio.setup(ledPin, gpio.OUT) # ... rest of the code ...
faac7b98d3270267b731c97aa0318d532f75610c
dash_table/__init__.py
dash_table/__init__.py
from dash.dash_table import * # noqa: F401, F403, E402 import warnings warnings.warn( """ The dash_table package is deprecated. Please replace `import dash_table` with `from dash import dash_table`""", stacklevel=2, )
from dash.dash_table import * # noqa: F401, F403, E402 import warnings warnings.warn( """ The dash_table package is deprecated. Please replace `import dash_table` with `from dash import dash_table` Also, if you're using any of the table format helpers (e.g. Group), replace `from dash_table.Format import Group` with `from dash.dash_table.Format import Group`""", stacklevel=2, )
Add info on table format helpers to warning message
Add info on table format helpers to warning message
Python
mit
plotly/dash-table,plotly/dash-table,plotly/dash-table
from dash.dash_table import * # noqa: F401, F403, E402 import warnings warnings.warn( """ The dash_table package is deprecated. Please replace - `import dash_table` with `from dash import dash_table`""", + `import dash_table` with `from dash import dash_table` + + Also, if you're using any of the table format helpers (e.g. Group), replace + `from dash_table.Format import Group` with + `from dash.dash_table.Format import Group`""", stacklevel=2, )
Add info on table format helpers to warning message
## Code Before: from dash.dash_table import * # noqa: F401, F403, E402 import warnings warnings.warn( """ The dash_table package is deprecated. Please replace `import dash_table` with `from dash import dash_table`""", stacklevel=2, ) ## Instruction: Add info on table format helpers to warning message ## Code After: from dash.dash_table import * # noqa: F401, F403, E402 import warnings warnings.warn( """ The dash_table package is deprecated. Please replace `import dash_table` with `from dash import dash_table` Also, if you're using any of the table format helpers (e.g. Group), replace `from dash_table.Format import Group` with `from dash.dash_table.Format import Group`""", stacklevel=2, )
... The dash_table package is deprecated. Please replace `import dash_table` with `from dash import dash_table` Also, if you're using any of the table format helpers (e.g. Group), replace `from dash_table.Format import Group` with `from dash.dash_table.Format import Group`""", stacklevel=2, ...
ce25be4609f6206343cdcb34b5342843f09f557b
server.py
server.py
from flask import Flask from SPARQLWrapper import SPARQLWrapper, JSON from flask import request, jsonify from flask.ext.cors import CORS app = Flask(__name__) CORS(app) @app.route('/') def hello_world(): auth = request.authorization query = request.args.get('query') if not auth is None and not query is None: sparql = SPARQLWrapper('https://knowledgestore2.fbk.eu/nwr/dutchhouse/sparql') sparql.setQuery(query) sparql.setCredentials(auth.username, auth.password) sparql.setReturnFormat(JSON) results = sparql.query().convert() return jsonify(**results) else: msg = [] if auth is None: msg.append('authorization error') if query is None: msg.append('no query') response = jsonify({'status': 404, 'statusText': ' '.join(msg)}) response.status_code = 404 return response if __name__ == '__main__': app.run()
from flask import Flask from SPARQLWrapper import SPARQLWrapper, JSON from flask import request, jsonify from flask.ext.cors import CORS app = Flask(__name__) CORS(app) @app.route('/') def hello_world(): return 'hello world' @app.route('/sparql') def do_sparql(): auth = request.authorization query = request.args.get('query') if not auth is None and not query is None: sparql = SPARQLWrapper('https://knowledgestore2.fbk.eu/nwr/dutchhouse/sparql') sparql.setQuery(query) sparql.setCredentials(auth.username, auth.password) sparql.setReturnFormat(JSON) results = sparql.query().convert() return jsonify(**results) else: msg = [] if auth is None: msg.append('authorization error') if query is None: msg.append('no query') response = jsonify({'status': 404, 'statusText': ' '.join(msg)}) response.status_code = 404 return response if __name__ == '__main__': app.run()
Add test route for heroku
Add test route for heroku
Python
apache-2.0
jvdzwaan/visun-flask
from flask import Flask from SPARQLWrapper import SPARQLWrapper, JSON from flask import request, jsonify from flask.ext.cors import CORS app = Flask(__name__) CORS(app) @app.route('/') def hello_world(): + return 'hello world' + + @app.route('/sparql') + def do_sparql(): auth = request.authorization query = request.args.get('query') if not auth is None and not query is None: sparql = SPARQLWrapper('https://knowledgestore2.fbk.eu/nwr/dutchhouse/sparql') sparql.setQuery(query) sparql.setCredentials(auth.username, auth.password) sparql.setReturnFormat(JSON) results = sparql.query().convert() return jsonify(**results) else: msg = [] if auth is None: msg.append('authorization error') if query is None: msg.append('no query') response = jsonify({'status': 404, 'statusText': ' '.join(msg)}) response.status_code = 404 return response if __name__ == '__main__': app.run()
Add test route for heroku
## Code Before: from flask import Flask from SPARQLWrapper import SPARQLWrapper, JSON from flask import request, jsonify from flask.ext.cors import CORS app = Flask(__name__) CORS(app) @app.route('/') def hello_world(): auth = request.authorization query = request.args.get('query') if not auth is None and not query is None: sparql = SPARQLWrapper('https://knowledgestore2.fbk.eu/nwr/dutchhouse/sparql') sparql.setQuery(query) sparql.setCredentials(auth.username, auth.password) sparql.setReturnFormat(JSON) results = sparql.query().convert() return jsonify(**results) else: msg = [] if auth is None: msg.append('authorization error') if query is None: msg.append('no query') response = jsonify({'status': 404, 'statusText': ' '.join(msg)}) response.status_code = 404 return response if __name__ == '__main__': app.run() ## Instruction: Add test route for heroku ## Code After: from flask import Flask from SPARQLWrapper import SPARQLWrapper, JSON from flask import request, jsonify from flask.ext.cors import CORS app = Flask(__name__) CORS(app) @app.route('/') def hello_world(): return 'hello world' @app.route('/sparql') def do_sparql(): auth = request.authorization query = request.args.get('query') if not auth is None and not query is None: sparql = SPARQLWrapper('https://knowledgestore2.fbk.eu/nwr/dutchhouse/sparql') sparql.setQuery(query) sparql.setCredentials(auth.username, auth.password) sparql.setReturnFormat(JSON) results = sparql.query().convert() return jsonify(**results) else: msg = [] if auth is None: msg.append('authorization error') if query is None: msg.append('no query') response = jsonify({'status': 404, 'statusText': ' '.join(msg)}) response.status_code = 404 return response if __name__ == '__main__': app.run()
# ... existing code ... def hello_world(): return 'hello world' @app.route('/sparql') def do_sparql(): auth = request.authorization # ... rest of the code ...
ca917fa28c5bf8fe3c431868951f429c48b58e0a
buysafe/urls.py
buysafe/urls.py
from django.conf.urls import patterns, url urlpatterns = patterns( 'buysafe.views', url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'), (r'^start/$', 'start'), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') )
from django.conf.urls import patterns, url urlpatterns = patterns( 'buysafe.views', url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'), url(r'^start/$', 'start', name="buysafe_start"), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') )
Add view label to buysafe_start
Add view label to buysafe_start
Python
bsd-3-clause
uranusjr/django-buysafe
from django.conf.urls import patterns, url urlpatterns = patterns( 'buysafe.views', url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'), - (r'^start/$', 'start'), + url(r'^start/$', 'start', name="buysafe_start"), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') )
Add view label to buysafe_start
## Code Before: from django.conf.urls import patterns, url urlpatterns = patterns( 'buysafe.views', url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'), (r'^start/$', 'start'), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') ) ## Instruction: Add view label to buysafe_start ## Code After: from django.conf.urls import patterns, url urlpatterns = patterns( 'buysafe.views', url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'), url(r'^start/$', 'start', name="buysafe_start"), (r'^success/(?P<payment_type>[01])/$', 'success'), (r'^fail/(?P<payment_type>[01])/$', 'fail'), (r'^check/(?P<payment_type>[01])/$', 'check') )
... url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'), url(r'^start/$', 'start', name="buysafe_start"), (r'^success/(?P<payment_type>[01])/$', 'success'), ...
213b889a580f58f5dea13fa63c999ca7dac04450
src/extras/__init__.py
src/extras/__init__.py
__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis
__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis from stemmed_kucera_francis import StemmedKuceraFrancis
Add Stemmed Kucera Francis to extras package
Add Stemmed Kucera Francis to extras package
Python
mit
Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify
__author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis + from stemmed_kucera_francis import StemmedKuceraFrancis
Add Stemmed Kucera Francis to extras package
## Code Before: __author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis ## Instruction: Add Stemmed Kucera Francis to extras package ## Code After: __author__ = 's7a' # All imports from logger import Logger from sanitizer import Sanitizer from kucera_francis import KuceraFrancis from stemmed_kucera_francis import StemmedKuceraFrancis
... from kucera_francis import KuceraFrancis from stemmed_kucera_francis import StemmedKuceraFrancis ...
b8e9a572098a5eaccf5aadde1b46bfc51da2face
tests/test_check_step_UDFs.py
tests/test_check_step_UDFs.py
from scripts.check_step_UDFs import CheckStepUDFs from tests.test_common import TestEPP from unittest.mock import Mock, patch, PropertyMock class TestCheckStepUDFs(TestEPP): def setUp(self): self.patched_process = patch.object( CheckStepUDFs, 'process', new_callable=PropertyMock(return_value=Mock(udf={ 'udfname1': 'a', 'udfname2': 'a' })) ) self.epp = CheckStepUDFs( 'http://server:8080/a_step_uri', 'a_user', 'a_password', ['udfname1', 'udfname2'], self.log_file ) def test_check_step_UDFs(self): with self.patched_process: self.epp._run()
from scripts.check_step_UDFs import CheckStepUDFs from tests.test_common import TestEPP from unittest.mock import Mock, patch, PropertyMock class TestCheckStepUDFs(TestEPP): def setUp(self): self.patched_process = patch.object( CheckStepUDFs, 'process', new_callable=PropertyMock(return_value=Mock(udf={ 'udfname1': 'a', 'udfname2': 'a' })) ) self.epp = CheckStepUDFs( 'http://server:8080/a_step_uri', 'a_user', 'a_password', ['udfname1', 'udfname2'], self.log_file ) self.epp2 = CheckStepUDFs( 'http://server:8080/a_step_uri', 'a_user', 'a_password', ['udfname1', 'udfname2', 'udfname3'], self.log_file ) def test_check_step_UDFs(self): with self.patched_process: # Both UDFs are present so run does not execute sys.exit assert self.epp._run() is None def test_check_step_UDFs(self): with self.patched_process, patch('scripts.check_step_UDFs.exit') as mexit: # One UDF is missing so run will execute sys.exit self.epp2._run() mexit.assert_called_once_with(1)
Add test to check sys.exit was called with the expected exit status
Add test to check sys.exit was called with the expected exit status
Python
mit
EdinburghGenomics/clarity_scripts,EdinburghGenomics/clarity_scripts
from scripts.check_step_UDFs import CheckStepUDFs from tests.test_common import TestEPP from unittest.mock import Mock, patch, PropertyMock class TestCheckStepUDFs(TestEPP): def setUp(self): self.patched_process = patch.object( CheckStepUDFs, 'process', new_callable=PropertyMock(return_value=Mock(udf={ - 'udfname1': 'a', 'udfname2': 'a' })) ) self.epp = CheckStepUDFs( 'http://server:8080/a_step_uri', 'a_user', 'a_password', ['udfname1', 'udfname2'], self.log_file ) + self.epp2 = CheckStepUDFs( + 'http://server:8080/a_step_uri', + 'a_user', + 'a_password', + ['udfname1', 'udfname2', 'udfname3'], + self.log_file + ) + def test_check_step_UDFs(self): with self.patched_process: + # Both UDFs are present so run does not execute sys.exit - self.epp._run() + assert self.epp._run() is None + def test_check_step_UDFs(self): + with self.patched_process, patch('scripts.check_step_UDFs.exit') as mexit: + # One UDF is missing so run will execute sys.exit + self.epp2._run() + mexit.assert_called_once_with(1)
Add test to check sys.exit was called with the expected exit status
## Code Before: from scripts.check_step_UDFs import CheckStepUDFs from tests.test_common import TestEPP from unittest.mock import Mock, patch, PropertyMock class TestCheckStepUDFs(TestEPP): def setUp(self): self.patched_process = patch.object( CheckStepUDFs, 'process', new_callable=PropertyMock(return_value=Mock(udf={ 'udfname1': 'a', 'udfname2': 'a' })) ) self.epp = CheckStepUDFs( 'http://server:8080/a_step_uri', 'a_user', 'a_password', ['udfname1', 'udfname2'], self.log_file ) def test_check_step_UDFs(self): with self.patched_process: self.epp._run() ## Instruction: Add test to check sys.exit was called with the expected exit status ## Code After: from scripts.check_step_UDFs import CheckStepUDFs from tests.test_common import TestEPP from unittest.mock import Mock, patch, PropertyMock class TestCheckStepUDFs(TestEPP): def setUp(self): self.patched_process = patch.object( CheckStepUDFs, 'process', new_callable=PropertyMock(return_value=Mock(udf={ 'udfname1': 'a', 'udfname2': 'a' })) ) self.epp = CheckStepUDFs( 'http://server:8080/a_step_uri', 'a_user', 'a_password', ['udfname1', 'udfname2'], self.log_file ) self.epp2 = CheckStepUDFs( 'http://server:8080/a_step_uri', 'a_user', 'a_password', ['udfname1', 'udfname2', 'udfname3'], self.log_file ) def test_check_step_UDFs(self): with self.patched_process: # Both UDFs are present so run does not execute sys.exit assert self.epp._run() is None def test_check_step_UDFs(self): with self.patched_process, patch('scripts.check_step_UDFs.exit') as mexit: # One UDF is missing so run will execute sys.exit self.epp2._run() mexit.assert_called_once_with(1)
... new_callable=PropertyMock(return_value=Mock(udf={ 'udfname1': 'a', ... self.epp2 = CheckStepUDFs( 'http://server:8080/a_step_uri', 'a_user', 'a_password', ['udfname1', 'udfname2', 'udfname3'], self.log_file ) def test_check_step_UDFs(self): ... with self.patched_process: # Both UDFs are present so run does not execute sys.exit assert self.epp._run() is None def test_check_step_UDFs(self): with self.patched_process, patch('scripts.check_step_UDFs.exit') as mexit: # One UDF is missing so run will execute sys.exit self.epp2._run() mexit.assert_called_once_with(1) ...
9f994fdcc29e290b98c0938ce9e8c32dc5f8adee
neuroimaging/algorithms/statistics/__init__.py
neuroimaging/algorithms/statistics/__init__.py
__docformat__ = 'restructuredtext' import intrinsic_volumes, rft def test(level=1, verbosity=1, flags=[]): from neuroimaging.utils.testutils import set_flags set_flags(flags) from neuroimaging.testing import * return NumpyTest().test(level, verbosity)
__docformat__ = 'restructuredtext' import intrinsic_volumes, rft from neuroimaging.testing import Tester test = Tester().test bench = Tester().bench
Fix test funcs in algorithms packaging.
Fix test funcs in algorithms packaging.
Python
bsd-3-clause
musically-ut/statsmodels,bsipocz/statsmodels,hlin117/statsmodels,waynenilsen/statsmodels,statsmodels/statsmodels,bzero/statsmodels,pprett/statsmodels,yl565/statsmodels,ChadFulton/statsmodels,musically-ut/statsmodels,pprett/statsmodels,adammenges/statsmodels,kiyoto/statsmodels,bashtage/statsmodels,alekz112/statsmodels,statsmodels/statsmodels,cbmoore/statsmodels,edhuckle/statsmodels,saketkc/statsmodels,bashtage/statsmodels,gef756/statsmodels,josef-pkt/statsmodels,alekz112/statsmodels,adammenges/statsmodels,nvoron23/statsmodels,YihaoLu/statsmodels,kiyoto/statsmodels,kiyoto/statsmodels,DonBeo/statsmodels,jstoxrocky/statsmodels,saketkc/statsmodels,wesm/statsmodels,bzero/statsmodels,yl565/statsmodels,hlin117/statsmodels,waynenilsen/statsmodels,DonBeo/statsmodels,DonBeo/statsmodels,wdurhamh/statsmodels,jstoxrocky/statsmodels,waynenilsen/statsmodels,jseabold/statsmodels,bashtage/statsmodels,pprett/statsmodels,yarikoptic/pystatsmodels,nguyentu1602/statsmodels,statsmodels/statsmodels,adammenges/statsmodels,saketkc/statsmodels,detrout/debian-statsmodels,josef-pkt/statsmodels,wdurhamh/statsmodels,phobson/statsmodels,alekz112/statsmodels,edhuckle/statsmodels,cbmoore/statsmodels,bzero/statsmodels,wwf5067/statsmodels,bert9bert/statsmodels,alekz112/statsmodels,cbmoore/statsmodels,wdurhamh/statsmodels,rgommers/statsmodels,wwf5067/statsmodels,nguyentu1602/statsmodels,rgommers/statsmodels,hainm/statsmodels,bashtage/statsmodels,wzbozon/statsmodels,nvoron23/statsmodels,wkfwkf/statsmodels,wzbozon/statsmodels,phobson/statsmodels,wkfwkf/statsmodels,yarikoptic/pystatsmodels,huongttlan/statsmodels,detrout/debian-statsmodels,cbmoore/statsmodels,DonBeo/statsmodels,wzbozon/statsmodels,yarikoptic/pystatsmodels,adammenges/statsmodels,hlin117/statsmodels,josef-pkt/statsmodels,phobson/statsmodels,bzero/statsmodels,YihaoLu/statsmodels,ChadFulton/statsmodels,astocko/statsmodels,saketkc/statsmodels,huongttlan/statsmodels,rgommers/statsmodels,hainm/statsmodels,bert9bert/statsmodels,jseabold/statsmodels,pprett/statsmodels,Averroes/statsmodels,nguyentu1602/statsmodels,gef756/statsmodels,bsipocz/statsmodels,musically-ut/statsmodels,statsmodels/statsmodels,DonBeo/statsmodels,astocko/statsmodels,ChadFulton/statsmodels,musically-ut/statsmodels,nguyentu1602/statsmodels,saketkc/statsmodels,wzbozon/statsmodels,bashtage/statsmodels,nvoron23/statsmodels,rgommers/statsmodels,YihaoLu/statsmodels,bert9bert/statsmodels,jstoxrocky/statsmodels,bavardage/statsmodels,bsipocz/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,bavardage/statsmodels,ChadFulton/statsmodels,bzero/statsmodels,bert9bert/statsmodels,nvoron23/statsmodels,statsmodels/statsmodels,wdurhamh/statsmodels,jstoxrocky/statsmodels,wwf5067/statsmodels,astocko/statsmodels,edhuckle/statsmodels,bavardage/statsmodels,kiyoto/statsmodels,hainm/statsmodels,waynenilsen/statsmodels,YihaoLu/statsmodels,bavardage/statsmodels,wzbozon/statsmodels,phobson/statsmodels,jseabold/statsmodels,gef756/statsmodels,jseabold/statsmodels,yl565/statsmodels,edhuckle/statsmodels,detrout/debian-statsmodels,jseabold/statsmodels,nvoron23/statsmodels,cbmoore/statsmodels,phobson/statsmodels,detrout/debian-statsmodels,ChadFulton/statsmodels,yl565/statsmodels,bavardage/statsmodels,bert9bert/statsmodels,wesm/statsmodels,wkfwkf/statsmodels,hainm/statsmodels,wdurhamh/statsmodels,kiyoto/statsmodels,edhuckle/statsmodels,wwf5067/statsmodels,Averroes/statsmodels,gef756/statsmodels,YihaoLu/statsmodels,ChadFulton/statsmodels,yl565/statsmodels,bsipocz/statsmodels,wkfwkf/statsmodels,Averroes/statsmodels,astocko/statsmodels,wkfwkf/statsmodels,huongttlan/statsmodels,rgommers/statsmodels,josef-pkt/statsmodels,gef756/statsmodels,josef-pkt/statsmodels,huongttlan/statsmodels,Averroes/statsmodels,wesm/statsmodels,hlin117/statsmodels,bashtage/statsmodels
__docformat__ = 'restructuredtext' import intrinsic_volumes, rft - def test(level=1, verbosity=1, flags=[]): - from neuroimaging.utils.testutils import set_flags - set_flags(flags) - from neuroimaging.testing import * + from neuroimaging.testing import Tester - return NumpyTest().test(level, verbosity) + test = Tester().test + bench = Tester().bench
Fix test funcs in algorithms packaging.
## Code Before: __docformat__ = 'restructuredtext' import intrinsic_volumes, rft def test(level=1, verbosity=1, flags=[]): from neuroimaging.utils.testutils import set_flags set_flags(flags) from neuroimaging.testing import * return NumpyTest().test(level, verbosity) ## Instruction: Fix test funcs in algorithms packaging. ## Code After: __docformat__ = 'restructuredtext' import intrinsic_volumes, rft from neuroimaging.testing import Tester test = Tester().test bench = Tester().bench
# ... existing code ... from neuroimaging.testing import Tester test = Tester().test bench = Tester().bench # ... rest of the code ...
4640b75fdb794e29cb6e7bdc03a6697d8f9f3483
emu/processes/wps_ultimate_question.py
emu/processes/wps_ultimate_question.py
from pywps import Process, LiteralOutput from pywps.app.Common import Metadata class UltimateQuestion(Process): def __init__(self): inputs = [] outputs = [LiteralOutput('answer', 'Answer to Ultimate Question', data_type='string')] super(UltimateQuestion, self).__init__( self._handler, identifier='ultimate_question', version='2.0', title='Answer to the ultimate question', abstract='This process gives the answer to the ultimate question of "What is the meaning of life?"', profile='', metadata=[Metadata('Ultimate Question'), Metadata('What is the meaning of life')], inputs=inputs, outputs=outputs, store_supported=True, status_supported=True ) @staticmethod def _handler(request, response): import time response.update_status('PyWPS Process started.', 0) sleep_delay = .1 time.sleep(sleep_delay) response.update_status('Thinking...', 20) time.sleep(sleep_delay) response.update_status('Thinking...', 40) time.sleep(sleep_delay) response.update_status('Thinking...', 60) time.sleep(sleep_delay) response.update_status('Thinking...', 80) response.outputs['answer'].data = '42' response.update_status('PyWPS Process completed.', 100) return response
from pywps import Process, LiteralOutput from pywps.app.Common import Metadata class UltimateQuestion(Process): def __init__(self): inputs = [] outputs = [LiteralOutput('answer', 'Answer to Ultimate Question', data_type='string')] super(UltimateQuestion, self).__init__( self._handler, identifier='ultimate_question', version='2.0', title='Answer to the ultimate question', abstract='This process gives the answer to the ultimate question of life, the universe, and everything.', profile='', metadata=[Metadata('Ultimate Question'), Metadata('What is the meaning of life')], inputs=inputs, outputs=outputs, store_supported=True, status_supported=True ) @staticmethod def _handler(request, response): import time sleep_delay = .1 response.update_status('PyWPS Process started.', 0) time.sleep(sleep_delay) response.update_status("Contacting the Deep Thought supercomputer.", 10) time.sleep(sleep_delay) response.update_status('Thinking...', 20) time.sleep(sleep_delay) response.update_status('Thinking...', 40) time.sleep(sleep_delay) response.update_status('Thinking...', 60) time.sleep(sleep_delay) response.update_status('Thinking...', 80) response.outputs['answer'].data = '42' response.update_status('PyWPS Process completed.', 100) return response
Make ultimate question ever more ultimate
Make ultimate question ever more ultimate
Python
apache-2.0
bird-house/emu
from pywps import Process, LiteralOutput from pywps.app.Common import Metadata class UltimateQuestion(Process): def __init__(self): inputs = [] outputs = [LiteralOutput('answer', 'Answer to Ultimate Question', data_type='string')] super(UltimateQuestion, self).__init__( self._handler, identifier='ultimate_question', version='2.0', title='Answer to the ultimate question', - abstract='This process gives the answer to the ultimate question of "What is the meaning of life?"', + abstract='This process gives the answer to the ultimate question of life, the universe, and everything.', profile='', metadata=[Metadata('Ultimate Question'), Metadata('What is the meaning of life')], inputs=inputs, outputs=outputs, store_supported=True, status_supported=True ) @staticmethod def _handler(request, response): import time + sleep_delay = .1 response.update_status('PyWPS Process started.', 0) + time.sleep(sleep_delay) - sleep_delay = .1 + response.update_status("Contacting the Deep Thought supercomputer.", 10) time.sleep(sleep_delay) response.update_status('Thinking...', 20) time.sleep(sleep_delay) response.update_status('Thinking...', 40) time.sleep(sleep_delay) response.update_status('Thinking...', 60) time.sleep(sleep_delay) response.update_status('Thinking...', 80) response.outputs['answer'].data = '42' response.update_status('PyWPS Process completed.', 100) return response
Make ultimate question ever more ultimate
## Code Before: from pywps import Process, LiteralOutput from pywps.app.Common import Metadata class UltimateQuestion(Process): def __init__(self): inputs = [] outputs = [LiteralOutput('answer', 'Answer to Ultimate Question', data_type='string')] super(UltimateQuestion, self).__init__( self._handler, identifier='ultimate_question', version='2.0', title='Answer to the ultimate question', abstract='This process gives the answer to the ultimate question of "What is the meaning of life?"', profile='', metadata=[Metadata('Ultimate Question'), Metadata('What is the meaning of life')], inputs=inputs, outputs=outputs, store_supported=True, status_supported=True ) @staticmethod def _handler(request, response): import time response.update_status('PyWPS Process started.', 0) sleep_delay = .1 time.sleep(sleep_delay) response.update_status('Thinking...', 20) time.sleep(sleep_delay) response.update_status('Thinking...', 40) time.sleep(sleep_delay) response.update_status('Thinking...', 60) time.sleep(sleep_delay) response.update_status('Thinking...', 80) response.outputs['answer'].data = '42' response.update_status('PyWPS Process completed.', 100) return response ## Instruction: Make ultimate question ever more ultimate ## Code After: from pywps import Process, LiteralOutput from pywps.app.Common import Metadata class UltimateQuestion(Process): def __init__(self): inputs = [] outputs = [LiteralOutput('answer', 'Answer to Ultimate Question', data_type='string')] super(UltimateQuestion, self).__init__( self._handler, identifier='ultimate_question', version='2.0', title='Answer to the ultimate question', abstract='This process gives the answer to the ultimate question of life, the universe, and everything.', profile='', metadata=[Metadata('Ultimate Question'), Metadata('What is the meaning of life')], inputs=inputs, outputs=outputs, store_supported=True, status_supported=True ) @staticmethod def _handler(request, response): import time sleep_delay = .1 response.update_status('PyWPS Process started.', 0) time.sleep(sleep_delay) response.update_status("Contacting the Deep Thought supercomputer.", 10) time.sleep(sleep_delay) response.update_status('Thinking...', 20) time.sleep(sleep_delay) response.update_status('Thinking...', 40) time.sleep(sleep_delay) response.update_status('Thinking...', 60) time.sleep(sleep_delay) response.update_status('Thinking...', 80) response.outputs['answer'].data = '42' response.update_status('PyWPS Process completed.', 100) return response
# ... existing code ... title='Answer to the ultimate question', abstract='This process gives the answer to the ultimate question of life, the universe, and everything.', profile='', # ... modified code ... import time sleep_delay = .1 response.update_status('PyWPS Process started.', 0) time.sleep(sleep_delay) response.update_status("Contacting the Deep Thought supercomputer.", 10) time.sleep(sleep_delay) # ... rest of the code ...
ee0a0b492b5536e0cc8c8e561875254698416eb4
lib/ansible/utils/string_functions.py
lib/ansible/utils/string_functions.py
def isprintable(instring): #http://stackoverflow.com/a/3637294 import string printset = set(string.printable) isprintable = set(instring).issubset(printset) return isprintable def count_newlines_from_end(str): i = len(str) while i > 0: if str[i-1] != '\n': break i -= 1 return len(str) - i
def isprintable(instring): if isinstance(instring, str): #http://stackoverflow.com/a/3637294 import string printset = set(string.printable) isprintable = set(instring).issubset(printset) return isprintable else: return True def count_newlines_from_end(str): i = len(str) while i > 0: if str[i-1] != '\n': break i -= 1 return len(str) - i
Allow isprintable() util function to work with unicode
Allow isprintable() util function to work with unicode Fixes #6842
Python
mit
thaim/ansible,thaim/ansible
def isprintable(instring): + if isinstance(instring, str): - #http://stackoverflow.com/a/3637294 + #http://stackoverflow.com/a/3637294 - import string + import string - printset = set(string.printable) + printset = set(string.printable) - isprintable = set(instring).issubset(printset) + isprintable = set(instring).issubset(printset) - return isprintable + return isprintable + else: + return True def count_newlines_from_end(str): i = len(str) while i > 0: if str[i-1] != '\n': break i -= 1 return len(str) - i
Allow isprintable() util function to work with unicode
## Code Before: def isprintable(instring): #http://stackoverflow.com/a/3637294 import string printset = set(string.printable) isprintable = set(instring).issubset(printset) return isprintable def count_newlines_from_end(str): i = len(str) while i > 0: if str[i-1] != '\n': break i -= 1 return len(str) - i ## Instruction: Allow isprintable() util function to work with unicode ## Code After: def isprintable(instring): if isinstance(instring, str): #http://stackoverflow.com/a/3637294 import string printset = set(string.printable) isprintable = set(instring).issubset(printset) return isprintable else: return True def count_newlines_from_end(str): i = len(str) while i > 0: if str[i-1] != '\n': break i -= 1 return len(str) - i
... def isprintable(instring): if isinstance(instring, str): #http://stackoverflow.com/a/3637294 import string printset = set(string.printable) isprintable = set(instring).issubset(printset) return isprintable else: return True ...
f188f2eb81c1310b9862b435a492b4ce6d0fac2d
python3/aniso8601/resolution.py
python3/aniso8601/resolution.py
from enum import Enum class DateResolution(Enum): Year, Month, Week, Weekday, Day, Ordinal = range(6) class TimeResolution(Enum): Seconds, Minutes, Hours = range(3)
class DateResolution(object): Year, Month, Week, Weekday, Day, Ordinal = list(range(6)) class TimeResolution(object): Seconds, Minutes, Hours = list(range(3))
Remove use of enum in Python3
Remove use of enum in Python3
Python
bsd-3-clause
3stack-software/python-aniso8601-relativedelta
- from enum import Enum + class DateResolution(object): + Year, Month, Week, Weekday, Day, Ordinal = list(range(6)) - class DateResolution(Enum): - Year, Month, Week, Weekday, Day, Ordinal = range(6) + class TimeResolution(object): + Seconds, Minutes, Hours = list(range(3)) - class TimeResolution(Enum): - Seconds, Minutes, Hours = range(3) -
Remove use of enum in Python3
## Code Before: from enum import Enum class DateResolution(Enum): Year, Month, Week, Weekday, Day, Ordinal = range(6) class TimeResolution(Enum): Seconds, Minutes, Hours = range(3) ## Instruction: Remove use of enum in Python3 ## Code After: class DateResolution(object): Year, Month, Week, Weekday, Day, Ordinal = list(range(6)) class TimeResolution(object): Seconds, Minutes, Hours = list(range(3))
... class DateResolution(object): Year, Month, Week, Weekday, Day, Ordinal = list(range(6)) class TimeResolution(object): Seconds, Minutes, Hours = list(range(3)) ...
24045cd16a862ebd31f4a88a733a05bf2aff03a5
easygeoip/urls_api.py
easygeoip/urls_api.py
from django.conf.urls import patterns, url # API URLs from .views import LocationFromIpView urlpatterns = patterns('', url(r'^location/(?P<ip_address>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))/$', LocationFromIpView.as_view(), name='geoip-explicit-ip-view'), url(r'^location/$', LocationFromIpView.as_view(), name='geoip-implicit-ip-view') # Take IP addr from request )
from django.conf.urls import url # API URLs from .views import LocationFromIpView urlpatterns = [ url(r'^location/(?P<ip_address>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))/$', LocationFromIpView.as_view(), name='geoip-explicit-ip-view'), url(r'^location/$', LocationFromIpView.as_view(), name='geoip-implicit-ip-view') # Take IP addr from request ]
Upgrade to new urlpatterns format
Upgrade to new urlpatterns format
Python
mit
lambdacomplete/django-easygeoip
- from django.conf.urls import patterns, url + from django.conf.urls import url # API URLs from .views import LocationFromIpView - urlpatterns = patterns('', + urlpatterns = [ url(r'^location/(?P<ip_address>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))/$', LocationFromIpView.as_view(), name='geoip-explicit-ip-view'), url(r'^location/$', LocationFromIpView.as_view(), name='geoip-implicit-ip-view') # Take IP addr from request - ) + ]
Upgrade to new urlpatterns format
## Code Before: from django.conf.urls import patterns, url # API URLs from .views import LocationFromIpView urlpatterns = patterns('', url(r'^location/(?P<ip_address>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))/$', LocationFromIpView.as_view(), name='geoip-explicit-ip-view'), url(r'^location/$', LocationFromIpView.as_view(), name='geoip-implicit-ip-view') # Take IP addr from request ) ## Instruction: Upgrade to new urlpatterns format ## Code After: from django.conf.urls import url # API URLs from .views import LocationFromIpView urlpatterns = [ url(r'^location/(?P<ip_address>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))/$', LocationFromIpView.as_view(), name='geoip-explicit-ip-view'), url(r'^location/$', LocationFromIpView.as_view(), name='geoip-implicit-ip-view') # Take IP addr from request ]
... from django.conf.urls import url ... urlpatterns = [ url(r'^location/(?P<ip_address>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))/$', LocationFromIpView.as_view(), ... url(r'^location/$', LocationFromIpView.as_view(), name='geoip-implicit-ip-view') # Take IP addr from request ] ...
8a8d4905c169b9a1060f1283d0286c433af24f43
word2gauss/words.py
word2gauss/words.py
from itertools import islice from .embeddings import text_to_pairs def iter_pairs(fin, vocab, batch_size=10, nsamples=2, window=5): ''' Convert a document stream to batches of pairs used for training embeddings. iter_pairs is a generator that yields batches of pairs that can be passed to GaussianEmbedding.train fin = an iterator of documents / sentences (e.g. a file like object) Each element is a string of raw text vocab = something implementing the Vocabulary interface batch_size = size of batches window = Number of words to the left and right of center word to include as positive pairs nsamples = number of negative samples to drawn for each center word ''' documents = iter(fin) batch = list(islice(documents, batch_size)) while len(batch) > 0: text = [ vocab.tokenize(doc, remove_oov=False, return_ids=True) for doc in batch ] pairs = text_to_pairs(text, vocab.random_ids, nsamples_per_word=nsamples, half_window_size=window) yield pairs batch = list(islice(documents, batch_size))
from itertools import islice from .embeddings import text_to_pairs def iter_pairs(fin, vocab, batch_size=10, nsamples=2, window=5): ''' Convert a document stream to batches of pairs used for training embeddings. iter_pairs is a generator that yields batches of pairs that can be passed to GaussianEmbedding.train fin = an iterator of documents / sentences (e.g. a file like object) Each element is a string of raw text vocab = something implementing the Vocabulary interface batch_size = size of batches window = Number of words to the left and right of center word to include as positive pairs nsamples = number of negative samples to drawn for each center word ''' documents = iter(fin) batch = list(islice(documents, batch_size)) while len(batch) > 0: text = [ vocab.tokenize_ids(doc, remove_oov=False) for doc in batch ] pairs = text_to_pairs(text, vocab.random_ids, nsamples_per_word=nsamples, half_window_size=window) yield pairs batch = list(islice(documents, batch_size))
Change the interface on tokenize in vocabulary
Change the interface on tokenize in vocabulary
Python
mit
seomoz/word2gauss,seomoz/word2gauss
from itertools import islice from .embeddings import text_to_pairs def iter_pairs(fin, vocab, batch_size=10, nsamples=2, window=5): ''' Convert a document stream to batches of pairs used for training embeddings. iter_pairs is a generator that yields batches of pairs that can be passed to GaussianEmbedding.train fin = an iterator of documents / sentences (e.g. a file like object) Each element is a string of raw text vocab = something implementing the Vocabulary interface batch_size = size of batches window = Number of words to the left and right of center word to include as positive pairs nsamples = number of negative samples to drawn for each center word ''' documents = iter(fin) batch = list(islice(documents, batch_size)) while len(batch) > 0: text = [ - vocab.tokenize(doc, remove_oov=False, return_ids=True) + vocab.tokenize_ids(doc, remove_oov=False) for doc in batch ] pairs = text_to_pairs(text, vocab.random_ids, nsamples_per_word=nsamples, half_window_size=window) yield pairs batch = list(islice(documents, batch_size))
Change the interface on tokenize in vocabulary
## Code Before: from itertools import islice from .embeddings import text_to_pairs def iter_pairs(fin, vocab, batch_size=10, nsamples=2, window=5): ''' Convert a document stream to batches of pairs used for training embeddings. iter_pairs is a generator that yields batches of pairs that can be passed to GaussianEmbedding.train fin = an iterator of documents / sentences (e.g. a file like object) Each element is a string of raw text vocab = something implementing the Vocabulary interface batch_size = size of batches window = Number of words to the left and right of center word to include as positive pairs nsamples = number of negative samples to drawn for each center word ''' documents = iter(fin) batch = list(islice(documents, batch_size)) while len(batch) > 0: text = [ vocab.tokenize(doc, remove_oov=False, return_ids=True) for doc in batch ] pairs = text_to_pairs(text, vocab.random_ids, nsamples_per_word=nsamples, half_window_size=window) yield pairs batch = list(islice(documents, batch_size)) ## Instruction: Change the interface on tokenize in vocabulary ## Code After: from itertools import islice from .embeddings import text_to_pairs def iter_pairs(fin, vocab, batch_size=10, nsamples=2, window=5): ''' Convert a document stream to batches of pairs used for training embeddings. iter_pairs is a generator that yields batches of pairs that can be passed to GaussianEmbedding.train fin = an iterator of documents / sentences (e.g. a file like object) Each element is a string of raw text vocab = something implementing the Vocabulary interface batch_size = size of batches window = Number of words to the left and right of center word to include as positive pairs nsamples = number of negative samples to drawn for each center word ''' documents = iter(fin) batch = list(islice(documents, batch_size)) while len(batch) > 0: text = [ vocab.tokenize_ids(doc, remove_oov=False) for doc in batch ] pairs = text_to_pairs(text, vocab.random_ids, nsamples_per_word=nsamples, half_window_size=window) yield pairs batch = list(islice(documents, batch_size))
// ... existing code ... text = [ vocab.tokenize_ids(doc, remove_oov=False) for doc in batch // ... rest of the code ...
7fb284ad29098a4397c7ac953e2d9acb89cf089e
notification/backends/email.py
notification/backends/email.py
from django.conf import settings from django.core.mail import EmailMessage from notification.backends.base import NotificationBackend class EmailBackend(NotificationBackend): slug = u'email' display_name = u'E-mail' formats = ['short.txt', 'full.txt'] def email_for_user(self, recipient): return recipient.email def should_send(self, sender, recipient, notice_type, *args, **kwargs): send = super(EmailBackend, self).should_send(sender, recipient, notice_type) return send and self.email_for_user(recipient) != '' def render_subject(self, label, context): # Strip newlines from subject return ''.join(self.render_message(label, 'notification/email_subject.txt', 'short.txt', context ).splitlines()) def send(self, sender, recipient, notice_type, context, *args, **kwargs): if not self.should_send(sender, recipient, notice_type): return False headers = kwargs.get('headers', {}) headers.setdefault('Reply-To', settings.DEFAULT_FROM_EMAIL) EmailMessage(self.render_subject(notice_type.label, context), self.render_message(notice_type.label, 'notification/email_body.txt', 'full.txt', context), kwargs.get('from_email') or settings.DEFAULT_FROM_EMAIL, [self.email_for_user(recipient)], headers=headers).send() return True
from django.conf import settings from django.core.mail import EmailMessage from notification.backends.base import NotificationBackend class EmailBackend(NotificationBackend): sensitivity = 2 slug = u'email' display_name = u'E-mail' formats = ['short.txt', 'full.txt'] def email_for_user(self, recipient): return recipient.email def should_send(self, sender, recipient, notice_type, *args, **kwargs): send = super(EmailBackend, self).should_send(sender, recipient, notice_type) return send and self.email_for_user(recipient) != '' def render_subject(self, label, context): # Strip newlines from subject return ''.join(self.render_message(label, 'notification/email_subject.txt', 'short.txt', context ).splitlines()) def send(self, sender, recipient, notice_type, context, *args, **kwargs): if not self.should_send(sender, recipient, notice_type): return False headers = kwargs.get('headers', {}) headers.setdefault('Reply-To', settings.DEFAULT_FROM_EMAIL) EmailMessage(self.render_subject(notice_type.label, context), self.render_message(notice_type.label, 'notification/email_body.txt', 'full.txt', context), kwargs.get('from_email') or settings.DEFAULT_FROM_EMAIL, [self.email_for_user(recipient)], headers=headers).send() return True
Set sensitivity of e-mail backend to 2, so notifications with 1 aren't mailed.
Set sensitivity of e-mail backend to 2, so notifications with 1 aren't mailed.
Python
mit
theatlantic/django-notification,theatlantic/django-notification
from django.conf import settings from django.core.mail import EmailMessage from notification.backends.base import NotificationBackend class EmailBackend(NotificationBackend): + sensitivity = 2 slug = u'email' display_name = u'E-mail' formats = ['short.txt', 'full.txt'] def email_for_user(self, recipient): return recipient.email def should_send(self, sender, recipient, notice_type, *args, **kwargs): send = super(EmailBackend, self).should_send(sender, recipient, notice_type) return send and self.email_for_user(recipient) != '' def render_subject(self, label, context): # Strip newlines from subject return ''.join(self.render_message(label, 'notification/email_subject.txt', 'short.txt', context ).splitlines()) def send(self, sender, recipient, notice_type, context, *args, **kwargs): if not self.should_send(sender, recipient, notice_type): return False headers = kwargs.get('headers', {}) headers.setdefault('Reply-To', settings.DEFAULT_FROM_EMAIL) EmailMessage(self.render_subject(notice_type.label, context), self.render_message(notice_type.label, 'notification/email_body.txt', 'full.txt', context), kwargs.get('from_email') or settings.DEFAULT_FROM_EMAIL, [self.email_for_user(recipient)], headers=headers).send() return True
Set sensitivity of e-mail backend to 2, so notifications with 1 aren't mailed.
## Code Before: from django.conf import settings from django.core.mail import EmailMessage from notification.backends.base import NotificationBackend class EmailBackend(NotificationBackend): slug = u'email' display_name = u'E-mail' formats = ['short.txt', 'full.txt'] def email_for_user(self, recipient): return recipient.email def should_send(self, sender, recipient, notice_type, *args, **kwargs): send = super(EmailBackend, self).should_send(sender, recipient, notice_type) return send and self.email_for_user(recipient) != '' def render_subject(self, label, context): # Strip newlines from subject return ''.join(self.render_message(label, 'notification/email_subject.txt', 'short.txt', context ).splitlines()) def send(self, sender, recipient, notice_type, context, *args, **kwargs): if not self.should_send(sender, recipient, notice_type): return False headers = kwargs.get('headers', {}) headers.setdefault('Reply-To', settings.DEFAULT_FROM_EMAIL) EmailMessage(self.render_subject(notice_type.label, context), self.render_message(notice_type.label, 'notification/email_body.txt', 'full.txt', context), kwargs.get('from_email') or settings.DEFAULT_FROM_EMAIL, [self.email_for_user(recipient)], headers=headers).send() return True ## Instruction: Set sensitivity of e-mail backend to 2, so notifications with 1 aren't mailed. ## Code After: from django.conf import settings from django.core.mail import EmailMessage from notification.backends.base import NotificationBackend class EmailBackend(NotificationBackend): sensitivity = 2 slug = u'email' display_name = u'E-mail' formats = ['short.txt', 'full.txt'] def email_for_user(self, recipient): return recipient.email def should_send(self, sender, recipient, notice_type, *args, **kwargs): send = super(EmailBackend, self).should_send(sender, recipient, notice_type) return send and self.email_for_user(recipient) != '' def render_subject(self, label, context): # Strip newlines from subject return ''.join(self.render_message(label, 'notification/email_subject.txt', 'short.txt', context ).splitlines()) def send(self, sender, recipient, notice_type, context, *args, **kwargs): if not self.should_send(sender, recipient, notice_type): return False headers = kwargs.get('headers', {}) headers.setdefault('Reply-To', settings.DEFAULT_FROM_EMAIL) EmailMessage(self.render_subject(notice_type.label, context), self.render_message(notice_type.label, 'notification/email_body.txt', 'full.txt', context), kwargs.get('from_email') or settings.DEFAULT_FROM_EMAIL, [self.email_for_user(recipient)], headers=headers).send() return True
// ... existing code ... class EmailBackend(NotificationBackend): sensitivity = 2 slug = u'email' // ... rest of the code ...
5864b503bced36d51ab911d5b306284dbc0cdb13
rest_framework_simplejwt/settings.py
rest_framework_simplejwt/settings.py
from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from rest_framework.settings import APISettings USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None) DEFAULTS = { 'AUTH_HEADER_TYPE': 'Bearer', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'TOKEN_TYPE_CLAIM': 'token_type', 'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(days=1), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=3), 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'SECRET_KEY': settings.SECRET_KEY, # Undocumented settings. Changing these may lead to unexpected behavior. # Make sure you know what you're doing. These might become part of the # public API eventually but that would require some adjustments. 'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.AccessToken', 'TOKEN_BACKEND_CLASS': 'rest_framework_simplejwt.backends.PythonJOSEBackend', 'ALGORITHM': 'HS256', } IMPORT_STRING_SETTINGS = ( 'AUTH_TOKEN_CLASS', 'TOKEN_BACKEND_CLASS', ) api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRING_SETTINGS)
from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from rest_framework.settings import APISettings USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None) DEFAULTS = { 'AUTH_HEADER_TYPE': 'Bearer', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'TOKEN_TYPE_CLAIM': 'token_type', 'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'SECRET_KEY': settings.SECRET_KEY, # Undocumented settings. Changing these may lead to unexpected behavior. # Make sure you know what you're doing. These might become part of the # public API eventually but that would require some adjustments. 'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.AccessToken', 'TOKEN_BACKEND_CLASS': 'rest_framework_simplejwt.backends.PythonJOSEBackend', 'ALGORITHM': 'HS256', } IMPORT_STRING_SETTINGS = ( 'AUTH_TOKEN_CLASS', 'TOKEN_BACKEND_CLASS', ) api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRING_SETTINGS)
Make sliding token lifetime defaults a bit more conservative
Make sliding token lifetime defaults a bit more conservative
Python
mit
davesque/django-rest-framework-simplejwt,davesque/django-rest-framework-simplejwt
from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from rest_framework.settings import APISettings USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None) DEFAULTS = { 'AUTH_HEADER_TYPE': 'Bearer', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'TOKEN_TYPE_CLAIM': 'token_type', + 'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp', - 'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp', - 'SLIDING_TOKEN_LIFETIME': timedelta(days=1), + 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), - 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=3), + 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'SECRET_KEY': settings.SECRET_KEY, # Undocumented settings. Changing these may lead to unexpected behavior. # Make sure you know what you're doing. These might become part of the # public API eventually but that would require some adjustments. 'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.AccessToken', 'TOKEN_BACKEND_CLASS': 'rest_framework_simplejwt.backends.PythonJOSEBackend', 'ALGORITHM': 'HS256', } IMPORT_STRING_SETTINGS = ( 'AUTH_TOKEN_CLASS', 'TOKEN_BACKEND_CLASS', ) api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRING_SETTINGS)
Make sliding token lifetime defaults a bit more conservative
## Code Before: from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from rest_framework.settings import APISettings USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None) DEFAULTS = { 'AUTH_HEADER_TYPE': 'Bearer', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'TOKEN_TYPE_CLAIM': 'token_type', 'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(days=1), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=3), 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'SECRET_KEY': settings.SECRET_KEY, # Undocumented settings. Changing these may lead to unexpected behavior. # Make sure you know what you're doing. These might become part of the # public API eventually but that would require some adjustments. 'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.AccessToken', 'TOKEN_BACKEND_CLASS': 'rest_framework_simplejwt.backends.PythonJOSEBackend', 'ALGORITHM': 'HS256', } IMPORT_STRING_SETTINGS = ( 'AUTH_TOKEN_CLASS', 'TOKEN_BACKEND_CLASS', ) api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRING_SETTINGS) ## Instruction: Make sliding token lifetime defaults a bit more conservative ## Code After: from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from rest_framework.settings import APISettings USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None) DEFAULTS = { 'AUTH_HEADER_TYPE': 'Bearer', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'TOKEN_TYPE_CLAIM': 'token_type', 'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'SECRET_KEY': settings.SECRET_KEY, # Undocumented settings. Changing these may lead to unexpected behavior. # Make sure you know what you're doing. These might become part of the # public API eventually but that would require some adjustments. 'AUTH_TOKEN_CLASS': 'rest_framework_simplejwt.tokens.AccessToken', 'TOKEN_BACKEND_CLASS': 'rest_framework_simplejwt.backends.PythonJOSEBackend', 'ALGORITHM': 'HS256', } IMPORT_STRING_SETTINGS = ( 'AUTH_TOKEN_CLASS', 'TOKEN_BACKEND_CLASS', ) api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRING_SETTINGS)
# ... existing code ... 'TOKEN_TYPE_CLAIM': 'token_type', 'SLIDING_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), # ... rest of the code ...
6054f2a103639dc1da51ddd4d63777a9d728a9ba
hr/admin.py
hr/admin.py
from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from hr.models import Application, Recommendation, Audit, Blacklist, BlacklistSource class ApplicationAdmin(admin.ModelAdmin): list_display = ('user', 'character', 'corporation', 'status', 'recommendations') search_fields = ['user', 'character', 'status'] list_filter = ('status',) def recommendations(self, obj): return len(obj.recommendation_set.all()) recommendations.short_description = '# of Recommendations' def save_model(self, request, obj, form, change): obj.save(user=request.user) admin.site.register(Application, ApplicationAdmin) class RecommendationAdmin(admin.ModelAdmin): list_display = ('user', 'user_character', 'application') search_fields = ['user_character'] admin.site.register(Recommendation, RecommendationAdmin) class AuditAdmin(admin.ModelAdmin): list_display = ('application', 'event', 'date') list_filter = ('event',) admin.site.register(Audit, AuditAdmin) class BlacklistAdmin(admin.ModelAdmin): list_display = ('type', 'value', 'source', 'created_date', 'created_by') list_filter = ('source', 'type') admin.site.register(Blacklist, BlacklistAdmin) class BlacklistSourceAdmin(admin.ModelAdmin): list_display = ('id', 'name') admin.site.register(BlacklistSource, BlacklistSourceAdmin)
from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from hr.models import Application, Recommendation, Audit, Blacklist, BlacklistSource class ApplicationAdmin(admin.ModelAdmin): list_display = ('user', 'character', 'corporation', 'status', 'recommendations') search_fields = ['user', 'character', 'status'] list_filter = ('status',) def recommendations(self, obj): return obj.recommendation_set.all().count() recommendations.short_description = '# of Recommendations' def save_model(self, request, obj, form, change): obj.save(user=request.user) admin.site.register(Application, ApplicationAdmin) class RecommendationAdmin(admin.ModelAdmin): list_display = ('user', 'user_character', 'application') search_fields = ['user_character'] admin.site.register(Recommendation, RecommendationAdmin) class AuditAdmin(admin.ModelAdmin): list_display = ('application', 'event', 'date') list_filter = ('event',) admin.site.register(Audit, AuditAdmin) class BlacklistAdmin(admin.ModelAdmin): list_display = ('type', 'value', 'source', 'created_date', 'created_by') list_filter = ('source', 'type') search_fields = ('value') admin.site.register(Blacklist, BlacklistAdmin) class BlacklistSourceAdmin(admin.ModelAdmin): list_display = ('id', 'name') admin.site.register(BlacklistSource, BlacklistSourceAdmin)
Add searchfield Blacklists, and use count() for recommendation count
Add searchfield Blacklists, and use count() for recommendation count
Python
bsd-3-clause
nikdoof/test-auth
from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from hr.models import Application, Recommendation, Audit, Blacklist, BlacklistSource class ApplicationAdmin(admin.ModelAdmin): list_display = ('user', 'character', 'corporation', 'status', 'recommendations') search_fields = ['user', 'character', 'status'] list_filter = ('status',) def recommendations(self, obj): - return len(obj.recommendation_set.all()) + return obj.recommendation_set.all().count() recommendations.short_description = '# of Recommendations' def save_model(self, request, obj, form, change): obj.save(user=request.user) admin.site.register(Application, ApplicationAdmin) class RecommendationAdmin(admin.ModelAdmin): list_display = ('user', 'user_character', 'application') search_fields = ['user_character'] admin.site.register(Recommendation, RecommendationAdmin) class AuditAdmin(admin.ModelAdmin): list_display = ('application', 'event', 'date') list_filter = ('event',) admin.site.register(Audit, AuditAdmin) class BlacklistAdmin(admin.ModelAdmin): list_display = ('type', 'value', 'source', 'created_date', 'created_by') list_filter = ('source', 'type') + search_fields = ('value') admin.site.register(Blacklist, BlacklistAdmin) class BlacklistSourceAdmin(admin.ModelAdmin): list_display = ('id', 'name') admin.site.register(BlacklistSource, BlacklistSourceAdmin)
Add searchfield Blacklists, and use count() for recommendation count
## Code Before: from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from hr.models import Application, Recommendation, Audit, Blacklist, BlacklistSource class ApplicationAdmin(admin.ModelAdmin): list_display = ('user', 'character', 'corporation', 'status', 'recommendations') search_fields = ['user', 'character', 'status'] list_filter = ('status',) def recommendations(self, obj): return len(obj.recommendation_set.all()) recommendations.short_description = '# of Recommendations' def save_model(self, request, obj, form, change): obj.save(user=request.user) admin.site.register(Application, ApplicationAdmin) class RecommendationAdmin(admin.ModelAdmin): list_display = ('user', 'user_character', 'application') search_fields = ['user_character'] admin.site.register(Recommendation, RecommendationAdmin) class AuditAdmin(admin.ModelAdmin): list_display = ('application', 'event', 'date') list_filter = ('event',) admin.site.register(Audit, AuditAdmin) class BlacklistAdmin(admin.ModelAdmin): list_display = ('type', 'value', 'source', 'created_date', 'created_by') list_filter = ('source', 'type') admin.site.register(Blacklist, BlacklistAdmin) class BlacklistSourceAdmin(admin.ModelAdmin): list_display = ('id', 'name') admin.site.register(BlacklistSource, BlacklistSourceAdmin) ## Instruction: Add searchfield Blacklists, and use count() for recommendation count ## Code After: from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from hr.models import Application, Recommendation, Audit, Blacklist, BlacklistSource class ApplicationAdmin(admin.ModelAdmin): list_display = ('user', 'character', 'corporation', 'status', 'recommendations') search_fields = ['user', 'character', 'status'] list_filter = ('status',) def recommendations(self, obj): return obj.recommendation_set.all().count() recommendations.short_description = '# of Recommendations' def save_model(self, request, obj, form, change): obj.save(user=request.user) admin.site.register(Application, ApplicationAdmin) class RecommendationAdmin(admin.ModelAdmin): list_display = ('user', 'user_character', 'application') search_fields = ['user_character'] admin.site.register(Recommendation, RecommendationAdmin) class AuditAdmin(admin.ModelAdmin): list_display = ('application', 'event', 'date') list_filter = ('event',) admin.site.register(Audit, AuditAdmin) class BlacklistAdmin(admin.ModelAdmin): list_display = ('type', 'value', 'source', 'created_date', 'created_by') list_filter = ('source', 'type') search_fields = ('value') admin.site.register(Blacklist, BlacklistAdmin) class BlacklistSourceAdmin(admin.ModelAdmin): list_display = ('id', 'name') admin.site.register(BlacklistSource, BlacklistSourceAdmin)
# ... existing code ... def recommendations(self, obj): return obj.recommendation_set.all().count() # ... modified code ... list_filter = ('source', 'type') search_fields = ('value') # ... rest of the code ...
c08e6a22e589880d97b92048cfaec994c41a23d4
pylama/lint/pylama_pydocstyle.py
pylama/lint/pylama_pydocstyle.py
"""pydocstyle support.""" from pydocstyle import PEP257Checker from pylama.lint import Linter as Abstract class Linter(Abstract): """Check pydocstyle errors.""" @staticmethod def run(path, code=None, **meta): """pydocstyle code checking. :return list: List of errors. """ return [{ 'lnum': e.line, # Remove colon after error code ("D403: ..." => "D403 ..."). 'text': (e.message[0:4] + e.message[5:] if e.message[4] == ':' else e.message), 'type': 'D', 'number': e.code } for e in PEP257Checker().check_source(code, path)]
"""pydocstyle support.""" THIRD_ARG = True try: #: Import for pydocstyle 2.0.0 and newer from pydocstyle import ConventionChecker as PyDocChecker except ImportError: #: Backward compatibility for pydocstyle prior to 2.0.0 from pydocstyle import PEP257Checker as PyDocChecker THIRD_ARG = False from pylama.lint import Linter as Abstract class Linter(Abstract): """Check pydocstyle errors.""" @staticmethod def run(path, code=None, **meta): """pydocstyle code checking. :return list: List of errors. """ check_source_args = (code, path, None) if THIRD_ARG else (code, path) return [{ 'lnum': e.line, # Remove colon after error code ("D403: ..." => "D403 ..."). 'text': (e.message[0:4] + e.message[5:] if e.message[4] == ':' else e.message), 'type': 'D', 'number': e.code } for e in PyDocChecker().check_source(*check_source_args)]
Update for pydocstyle 2.0.0 compatibility
Update for pydocstyle 2.0.0 compatibility Fix klen/pylama#96 Adding the newer ignore_decorators argument. Thanks to @not-raspberry for the tip!
Python
mit
klen/pylama
"""pydocstyle support.""" + THIRD_ARG = True + try: + #: Import for pydocstyle 2.0.0 and newer + from pydocstyle import ConventionChecker as PyDocChecker + except ImportError: + #: Backward compatibility for pydocstyle prior to 2.0.0 - from pydocstyle import PEP257Checker + from pydocstyle import PEP257Checker as PyDocChecker + THIRD_ARG = False from pylama.lint import Linter as Abstract class Linter(Abstract): """Check pydocstyle errors.""" @staticmethod def run(path, code=None, **meta): """pydocstyle code checking. :return list: List of errors. """ + check_source_args = (code, path, None) if THIRD_ARG else (code, path) return [{ 'lnum': e.line, # Remove colon after error code ("D403: ..." => "D403 ..."). 'text': (e.message[0:4] + e.message[5:] if e.message[4] == ':' else e.message), 'type': 'D', 'number': e.code - } for e in PEP257Checker().check_source(code, path)] + } for e in PyDocChecker().check_source(*check_source_args)]
Update for pydocstyle 2.0.0 compatibility
## Code Before: """pydocstyle support.""" from pydocstyle import PEP257Checker from pylama.lint import Linter as Abstract class Linter(Abstract): """Check pydocstyle errors.""" @staticmethod def run(path, code=None, **meta): """pydocstyle code checking. :return list: List of errors. """ return [{ 'lnum': e.line, # Remove colon after error code ("D403: ..." => "D403 ..."). 'text': (e.message[0:4] + e.message[5:] if e.message[4] == ':' else e.message), 'type': 'D', 'number': e.code } for e in PEP257Checker().check_source(code, path)] ## Instruction: Update for pydocstyle 2.0.0 compatibility ## Code After: """pydocstyle support.""" THIRD_ARG = True try: #: Import for pydocstyle 2.0.0 and newer from pydocstyle import ConventionChecker as PyDocChecker except ImportError: #: Backward compatibility for pydocstyle prior to 2.0.0 from pydocstyle import PEP257Checker as PyDocChecker THIRD_ARG = False from pylama.lint import Linter as Abstract class Linter(Abstract): """Check pydocstyle errors.""" @staticmethod def run(path, code=None, **meta): """pydocstyle code checking. :return list: List of errors. """ check_source_args = (code, path, None) if THIRD_ARG else (code, path) return [{ 'lnum': e.line, # Remove colon after error code ("D403: ..." => "D403 ..."). 'text': (e.message[0:4] + e.message[5:] if e.message[4] == ':' else e.message), 'type': 'D', 'number': e.code } for e in PyDocChecker().check_source(*check_source_args)]
... THIRD_ARG = True try: #: Import for pydocstyle 2.0.0 and newer from pydocstyle import ConventionChecker as PyDocChecker except ImportError: #: Backward compatibility for pydocstyle prior to 2.0.0 from pydocstyle import PEP257Checker as PyDocChecker THIRD_ARG = False ... """ check_source_args = (code, path, None) if THIRD_ARG else (code, path) return [{ ... 'number': e.code } for e in PyDocChecker().check_source(*check_source_args)] ...
20dbd80d0262869f3378597d7152dab7a6104de8
routes/__init__.py
routes/__init__.py
import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to
import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to __all__=['Mapper', 'url_for', 'redirect_to', 'request_config']
Tweak for exporting the symbols
[svn] Tweak for exporting the symbols --HG-- branch : trunk
Python
mit
alex/routes,bbangert/routes,mikepk/routes,webknjaz/routes,mikepk/pybald-routes
import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to - + __all__=['Mapper', 'url_for', 'redirect_to', 'request_config']
Tweak for exporting the symbols
## Code Before: import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to ## Instruction: Tweak for exporting the symbols ## Code After: import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) else: class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattribute__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, value) def request_config(): return _RequestConfig() from base import Mapper from util import url_for, redirect_to __all__=['Mapper', 'url_for', 'redirect_to', 'request_config']
# ... existing code ... from util import url_for, redirect_to __all__=['Mapper', 'url_for', 'redirect_to', 'request_config'] # ... rest of the code ...
435ac02a320582fb8ede698da579d5c4fdd2d600
summary_footnotes.py
summary_footnotes.py
from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def summary_footnotes(instance): if "SUMMARY_FOOTNOTES_MODE" in instance.settings: mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] else: mode = 'link' if type(instance) == Article: summary = BeautifulSoup(instance.summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (instance.settings["SITEURL"], instance.url, link['href']) else: raise Exception("Unknown summary footnote mode: %s" % mode) instance._summary = text_type(summary) def register(): signals.content_object_init.connect(summary_footnotes)
from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def initialized(pelican): from pelican.settings import DEFAULT_CONFIG DEFAULT_CONFIG.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') if pelican: pelican.settings.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') def transform_summary(summary, article_url, site_url, mode): summary = BeautifulSoup(summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (site_url, article_url, link['href']) else: raise Exception("Unknown summary_footnote mode: %s" % mode) return text_type(summary) return None def summary_footnotes(instance): mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] if type(instance) == Article: # Monkeypatch in the rewrite on the summary because when this is run # the content might not be ready yet if it depends on other files # being loaded. instance._orig_get_summary = instance._get_summary def _get_summary(self): summary = self._orig_get_summary() new_summary = transform_summary(summary, self.url, self.settings['SITEURL'], mode) if new_summary is not None: return new_summary else: return summary funcType = type(instance._get_summary) instance._get_summary = funcType(_get_summary, instance, Article) def register(): signals.initialized.connect(initialized) signals.content_object_init.connect(summary_footnotes)
Rewrite summary as late as possible.
Rewrite summary as late as possible. Fixes issue where {filename} links would sometimes not work.
Python
agpl-3.0
dperelman/summary_footnotes
from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type + def initialized(pelican): + from pelican.settings import DEFAULT_CONFIG + DEFAULT_CONFIG.setdefault('SUMMARY_FOOTNOTES_MODE', + 'link') + if pelican: + pelican.settings.setdefault('SUMMARY_FOOTNOTES_MODE', + 'link') + + def transform_summary(summary, article_url, site_url, mode): + summary = BeautifulSoup(summary) + footnote_links = summary.findAll('a', {'rel':'footnote'}) + if footnote_links: + for link in footnote_links: + if mode == 'remove': + link.extract() + elif mode == 'link': + link['href'] = "%s/%s%s" % (site_url, + article_url, + link['href']) + else: + raise Exception("Unknown summary_footnote mode: %s" % mode) + return text_type(summary) + return None + def summary_footnotes(instance): - if "SUMMARY_FOOTNOTES_MODE" in instance.settings: - mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] + mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] - else: - mode = 'link' if type(instance) == Article: - summary = BeautifulSoup(instance.summary) - footnote_links = summary.findAll('a', {'rel':'footnote'}) - if footnote_links: - for link in footnote_links: - if mode == 'remove': - link.extract() - elif mode == 'link': - link['href'] = "%s/%s%s" % (instance.settings["SITEURL"], + # Monkeypatch in the rewrite on the summary because when this is run + # the content might not be ready yet if it depends on other files + # being loaded. + instance._orig_get_summary = instance._get_summary + + def _get_summary(self): + summary = self._orig_get_summary() + new_summary = transform_summary(summary, - instance.url, + self.url, + self.settings['SITEURL'], - link['href']) + mode) + if new_summary is not None: + return new_summary - else: + else: - raise Exception("Unknown summary footnote mode: %s" % mode) - instance._summary = text_type(summary) + return summary + + funcType = type(instance._get_summary) + instance._get_summary = funcType(_get_summary, instance, Article) def register(): + signals.initialized.connect(initialized) signals.content_object_init.connect(summary_footnotes)
Rewrite summary as late as possible.
## Code Before: from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def summary_footnotes(instance): if "SUMMARY_FOOTNOTES_MODE" in instance.settings: mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] else: mode = 'link' if type(instance) == Article: summary = BeautifulSoup(instance.summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (instance.settings["SITEURL"], instance.url, link['href']) else: raise Exception("Unknown summary footnote mode: %s" % mode) instance._summary = text_type(summary) def register(): signals.content_object_init.connect(summary_footnotes) ## Instruction: Rewrite summary as late as possible. ## Code After: from pelican import signals from pelican.contents import Content, Article from BeautifulSoup import BeautifulSoup from six import text_type def initialized(pelican): from pelican.settings import DEFAULT_CONFIG DEFAULT_CONFIG.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') if pelican: pelican.settings.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') def transform_summary(summary, article_url, site_url, mode): summary = BeautifulSoup(summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (site_url, article_url, link['href']) else: raise Exception("Unknown summary_footnote mode: %s" % mode) return text_type(summary) return None def summary_footnotes(instance): mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] if type(instance) == Article: # Monkeypatch in the rewrite on the summary because when this is run # the content might not be ready yet if it depends on other files # being loaded. instance._orig_get_summary = instance._get_summary def _get_summary(self): summary = self._orig_get_summary() new_summary = transform_summary(summary, self.url, self.settings['SITEURL'], mode) if new_summary is not None: return new_summary else: return summary funcType = type(instance._get_summary) instance._get_summary = funcType(_get_summary, instance, Article) def register(): signals.initialized.connect(initialized) signals.content_object_init.connect(summary_footnotes)
// ... existing code ... def initialized(pelican): from pelican.settings import DEFAULT_CONFIG DEFAULT_CONFIG.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') if pelican: pelican.settings.setdefault('SUMMARY_FOOTNOTES_MODE', 'link') def transform_summary(summary, article_url, site_url, mode): summary = BeautifulSoup(summary) footnote_links = summary.findAll('a', {'rel':'footnote'}) if footnote_links: for link in footnote_links: if mode == 'remove': link.extract() elif mode == 'link': link['href'] = "%s/%s%s" % (site_url, article_url, link['href']) else: raise Exception("Unknown summary_footnote mode: %s" % mode) return text_type(summary) return None def summary_footnotes(instance): mode = instance.settings["SUMMARY_FOOTNOTES_MODE"] // ... modified code ... if type(instance) == Article: # Monkeypatch in the rewrite on the summary because when this is run # the content might not be ready yet if it depends on other files # being loaded. instance._orig_get_summary = instance._get_summary def _get_summary(self): summary = self._orig_get_summary() new_summary = transform_summary(summary, self.url, self.settings['SITEURL'], mode) if new_summary is not None: return new_summary else: return summary funcType = type(instance._get_summary) instance._get_summary = funcType(_get_summary, instance, Article) ... def register(): signals.initialized.connect(initialized) signals.content_object_init.connect(summary_footnotes) // ... rest of the code ...
3ede075c812b116629c5f514596669b16c4784df
fulltext/backends/__json.py
fulltext/backends/__json.py
import json from six import StringIO from six import string_types from six import integer_types def _to_text(text, obj): if isinstance(obj, dict): for key in sorted(obj.keys()): _to_text(text, key) _to_text(text, obj[key]) elif isinstance(obj, list): for item in obj: _to_text(text, item) elif isinstance(obj, string_types): text.write(obj) text.write(u' ') elif isinstance(obj, integer_types): text.write(str(obj)) text.write(u' ') def _get_file(f, **kwargs): text, obj = StringIO(), json.loads(f.read().decode('utf8')) _to_text(text, obj) return text.getvalue()
import json from six import StringIO from six import string_types from six import integer_types def _to_text(text, obj): if isinstance(obj, dict): for key in sorted(obj.keys()): _to_text(text, key) _to_text(text, obj[key]) elif isinstance(obj, list): for item in obj: _to_text(text, item) elif isinstance(obj, string_types + integer_types): text.write(u'%s ' % obj) else: raise ValueError('Unrecognized type: %s' % obj.__class__) def _get_file(f, **kwargs): text, data = StringIO(), f.read() obj = json.loads(data.decode('utf8')) _to_text(text, obj) return text.getvalue()
Use format string. Readability. ValueError.
Use format string. Readability. ValueError.
Python
mit
btimby/fulltext,btimby/fulltext
import json from six import StringIO from six import string_types from six import integer_types def _to_text(text, obj): if isinstance(obj, dict): for key in sorted(obj.keys()): _to_text(text, key) _to_text(text, obj[key]) elif isinstance(obj, list): for item in obj: _to_text(text, item) - elif isinstance(obj, string_types): + elif isinstance(obj, string_types + integer_types): - text.write(obj) - text.write(u' ') + text.write(u'%s ' % obj) + else: + raise ValueError('Unrecognized type: %s' % obj.__class__) - elif isinstance(obj, integer_types): - text.write(str(obj)) - text.write(u' ') def _get_file(f, **kwargs): - text, obj = StringIO(), json.loads(f.read().decode('utf8')) + text, data = StringIO(), f.read() + obj = json.loads(data.decode('utf8')) _to_text(text, obj) return text.getvalue()
Use format string. Readability. ValueError.
## Code Before: import json from six import StringIO from six import string_types from six import integer_types def _to_text(text, obj): if isinstance(obj, dict): for key in sorted(obj.keys()): _to_text(text, key) _to_text(text, obj[key]) elif isinstance(obj, list): for item in obj: _to_text(text, item) elif isinstance(obj, string_types): text.write(obj) text.write(u' ') elif isinstance(obj, integer_types): text.write(str(obj)) text.write(u' ') def _get_file(f, **kwargs): text, obj = StringIO(), json.loads(f.read().decode('utf8')) _to_text(text, obj) return text.getvalue() ## Instruction: Use format string. Readability. ValueError. ## Code After: import json from six import StringIO from six import string_types from six import integer_types def _to_text(text, obj): if isinstance(obj, dict): for key in sorted(obj.keys()): _to_text(text, key) _to_text(text, obj[key]) elif isinstance(obj, list): for item in obj: _to_text(text, item) elif isinstance(obj, string_types + integer_types): text.write(u'%s ' % obj) else: raise ValueError('Unrecognized type: %s' % obj.__class__) def _get_file(f, **kwargs): text, data = StringIO(), f.read() obj = json.loads(data.decode('utf8')) _to_text(text, obj) return text.getvalue()
# ... existing code ... elif isinstance(obj, string_types + integer_types): text.write(u'%s ' % obj) else: raise ValueError('Unrecognized type: %s' % obj.__class__) # ... modified code ... def _get_file(f, **kwargs): text, data = StringIO(), f.read() obj = json.loads(data.decode('utf8')) # ... rest of the code ...
9699d573fa459cb7ee90237d7fa64f7014c96db4
scripts/update_centroid_reports.py
scripts/update_centroid_reports.py
import mica.centroid_dashboard # Cheat. Needs entrypoint scripts mica.centroid_dashboard.update_observed_metrics()
import mica.centroid_dashboard # Cheat. Needs entrypoint scripts mica.centroid_dashboard.update_observed_metrics(save=True, make_plots=True)
Fix script default to actually save plots
Fix script default to actually save plots
Python
bsd-3-clause
sot/mica,sot/mica
import mica.centroid_dashboard # Cheat. Needs entrypoint scripts - mica.centroid_dashboard.update_observed_metrics() + mica.centroid_dashboard.update_observed_metrics(save=True, make_plots=True)
Fix script default to actually save plots
## Code Before: import mica.centroid_dashboard # Cheat. Needs entrypoint scripts mica.centroid_dashboard.update_observed_metrics() ## Instruction: Fix script default to actually save plots ## Code After: import mica.centroid_dashboard # Cheat. Needs entrypoint scripts mica.centroid_dashboard.update_observed_metrics(save=True, make_plots=True)
// ... existing code ... # Cheat. Needs entrypoint scripts mica.centroid_dashboard.update_observed_metrics(save=True, make_plots=True) // ... rest of the code ...
96fe288cbd4c4399c83b4c3d56da6e427aaad0f9
spicedham/digitdestroyer.py
spicedham/digitdestroyer.py
from spicedham.basewrapper import BaseWrapper class DigitDestroyer(BaseWrapper): def train(*args): pass def classify(self, response): if all(map(unicode.isdigit, response)): return 1 else: return 0.5
from spicedham.basewrapper import BaseWrapper class DigitDestroyer(object): def train(*args): pass def classify(self, response): if all(map(unicode.isdigit, response)): return 1 else: return None
Fix inheritence error and return value
Fix inheritence error and return value It shouldn't inherit from BaseWrapper, but merely object. It should return None instead of 0.5 so it will have no effect on the average.
Python
mpl-2.0
mozilla/spicedham,mozilla/spicedham
from spicedham.basewrapper import BaseWrapper - class DigitDestroyer(BaseWrapper): + class DigitDestroyer(object): def train(*args): pass def classify(self, response): if all(map(unicode.isdigit, response)): return 1 else: - return 0.5 + return None
Fix inheritence error and return value
## Code Before: from spicedham.basewrapper import BaseWrapper class DigitDestroyer(BaseWrapper): def train(*args): pass def classify(self, response): if all(map(unicode.isdigit, response)): return 1 else: return 0.5 ## Instruction: Fix inheritence error and return value ## Code After: from spicedham.basewrapper import BaseWrapper class DigitDestroyer(object): def train(*args): pass def classify(self, response): if all(map(unicode.isdigit, response)): return 1 else: return None
... class DigitDestroyer(object): def train(*args): ... else: return None ...
957f3e82f13dc8a9bd09d40a25c1f65847e144b8
aiohttp_json_api/decorators.py
aiohttp_json_api/decorators.py
from functools import wraps from boltons.iterutils import first from .context import RequestContext from .errors import HTTPUnsupportedMediaType from .const import JSONAPI_CONTENT_TYPE def jsonapi_content(handler): @wraps(handler) async def wrapper(*args, **kwargs): context = kwargs.get('context') if context is None: context = first(args, key=lambda v: isinstance(v, RequestContext)) assert context if context.request.content_type != JSONAPI_CONTENT_TYPE: raise HTTPUnsupportedMediaType( detail=f"Only '{JSONAPI_CONTENT_TYPE}' " f"content-type is acceptable." ) return await handler(*args, **kwargs) return wrapper
from functools import wraps from aiohttp import web from boltons.iterutils import first from .context import RequestContext from .errors import HTTPUnsupportedMediaType from .const import JSONAPI, JSONAPI_CONTENT_TYPE def jsonapi_content(handler): @wraps(handler) async def wrapper(*args, **kwargs): request = kwargs.get('request') if request is None: request = first(args, key=lambda v: isinstance(v, web.Request)) context = request[JSONAPI] assert context and isinstance(context, RequestContext) if context.request.content_type != JSONAPI_CONTENT_TYPE: raise HTTPUnsupportedMediaType( detail=f"Only '{JSONAPI_CONTENT_TYPE}' " f"content-type is acceptable." ) return await handler(*args, **kwargs) return wrapper
Fix bug with arguments handling in JSON API content decorator
Fix bug with arguments handling in JSON API content decorator
Python
mit
vovanbo/aiohttp_json_api
from functools import wraps + from aiohttp import web from boltons.iterutils import first from .context import RequestContext from .errors import HTTPUnsupportedMediaType - from .const import JSONAPI_CONTENT_TYPE + from .const import JSONAPI, JSONAPI_CONTENT_TYPE def jsonapi_content(handler): @wraps(handler) async def wrapper(*args, **kwargs): - context = kwargs.get('context') + request = kwargs.get('request') - if context is None: + if request is None: - context = first(args, key=lambda v: isinstance(v, RequestContext)) + request = first(args, key=lambda v: isinstance(v, web.Request)) - assert context + context = request[JSONAPI] + assert context and isinstance(context, RequestContext) if context.request.content_type != JSONAPI_CONTENT_TYPE: raise HTTPUnsupportedMediaType( detail=f"Only '{JSONAPI_CONTENT_TYPE}' " f"content-type is acceptable." ) return await handler(*args, **kwargs) return wrapper
Fix bug with arguments handling in JSON API content decorator
## Code Before: from functools import wraps from boltons.iterutils import first from .context import RequestContext from .errors import HTTPUnsupportedMediaType from .const import JSONAPI_CONTENT_TYPE def jsonapi_content(handler): @wraps(handler) async def wrapper(*args, **kwargs): context = kwargs.get('context') if context is None: context = first(args, key=lambda v: isinstance(v, RequestContext)) assert context if context.request.content_type != JSONAPI_CONTENT_TYPE: raise HTTPUnsupportedMediaType( detail=f"Only '{JSONAPI_CONTENT_TYPE}' " f"content-type is acceptable." ) return await handler(*args, **kwargs) return wrapper ## Instruction: Fix bug with arguments handling in JSON API content decorator ## Code After: from functools import wraps from aiohttp import web from boltons.iterutils import first from .context import RequestContext from .errors import HTTPUnsupportedMediaType from .const import JSONAPI, JSONAPI_CONTENT_TYPE def jsonapi_content(handler): @wraps(handler) async def wrapper(*args, **kwargs): request = kwargs.get('request') if request is None: request = first(args, key=lambda v: isinstance(v, web.Request)) context = request[JSONAPI] assert context and isinstance(context, RequestContext) if context.request.content_type != JSONAPI_CONTENT_TYPE: raise HTTPUnsupportedMediaType( detail=f"Only '{JSONAPI_CONTENT_TYPE}' " f"content-type is acceptable." ) return await handler(*args, **kwargs) return wrapper
// ... existing code ... from aiohttp import web from boltons.iterutils import first // ... modified code ... from .errors import HTTPUnsupportedMediaType from .const import JSONAPI, JSONAPI_CONTENT_TYPE ... async def wrapper(*args, **kwargs): request = kwargs.get('request') if request is None: request = first(args, key=lambda v: isinstance(v, web.Request)) context = request[JSONAPI] assert context and isinstance(context, RequestContext) // ... rest of the code ...
1326203c81db0973ff5e1472a2ad80499b6f2189
main.py
main.py
import csv import logging from config.config import Config from d_spider import DSpider from dev.logger import logger_setup def main(): # setup logger_setup(Config.get('APP_LOG_FILE'), ['ddd_site_parse']) # log logger = logging.getLogger('ddd_site_parse') logger.addHandler(logging.NullHandler()) logger.info(' --- ') logger.info('Start app...') # bot with open(Config.get('APP_OUTPUT_CSV'), 'w', newline='') as output: writer = csv.writer(output, delimiter=';') try: threads_counter = int(Config.get('APP_THREAD_COUNT')) bot = DSpider(thread_number=threads_counter, logger_name='ddd_site_parse', writer=writer) bot.run() except Exception as e: print(e) logger.info('End app...\n\n') if __name__ == '__main__': main()
import csv import logging import os import time from config.config import Config from d_spider import DSpider from dev.logger import logger_setup def main(): # setup logger_setup(Config.get('APP_LOG_FILE'), ['ddd_site_parse']) # log logger = logging.getLogger('ddd_site_parse') logger.addHandler(logging.NullHandler()) logger.info(' --- ') logger.info('Start app...') # bot output_file_name = time.strftime('%d_%m_%Y') + '.csv' output_path = os.path.join(Config.get('APP_OUTPUT_DIR'), output_file_name) if not os.path.exists(Config.get('APP_OUTPUT_DIR')): logger.info('Create directory, because not exist') os.makedirs(Config.get('APP_OUTPUT_DIR')) with open(output_path, 'w', newline='', encoding=Config.get('APP_OUTPUT_ENC')) as output: writer = csv.writer(output, delimiter=';') try: threads_counter = int(Config.get('APP_THREAD_COUNT')) bot = DSpider(thread_number=threads_counter, logger_name='ddd_site_parse', writer=writer) bot.run() except Exception as e: print(e) logger.info('End app...\n\n') if __name__ == '__main__': main()
Add encoding support, move output to separate directory, change output filename to DD_MM_YYYY.csv
Add encoding support, move output to separate directory, change output filename to DD_MM_YYYY.csv
Python
mit
Holovin/D_GrabDemo
import csv import logging + import os + + import time from config.config import Config from d_spider import DSpider from dev.logger import logger_setup def main(): # setup logger_setup(Config.get('APP_LOG_FILE'), ['ddd_site_parse']) # log logger = logging.getLogger('ddd_site_parse') logger.addHandler(logging.NullHandler()) logger.info(' --- ') logger.info('Start app...') # bot - with open(Config.get('APP_OUTPUT_CSV'), 'w', newline='') as output: + output_file_name = time.strftime('%d_%m_%Y') + '.csv' + output_path = os.path.join(Config.get('APP_OUTPUT_DIR'), output_file_name) + + if not os.path.exists(Config.get('APP_OUTPUT_DIR')): + logger.info('Create directory, because not exist') + os.makedirs(Config.get('APP_OUTPUT_DIR')) + + with open(output_path, 'w', newline='', encoding=Config.get('APP_OUTPUT_ENC')) as output: writer = csv.writer(output, delimiter=';') try: threads_counter = int(Config.get('APP_THREAD_COUNT')) bot = DSpider(thread_number=threads_counter, logger_name='ddd_site_parse', writer=writer) bot.run() except Exception as e: print(e) logger.info('End app...\n\n') if __name__ == '__main__': main()
Add encoding support, move output to separate directory, change output filename to DD_MM_YYYY.csv
## Code Before: import csv import logging from config.config import Config from d_spider import DSpider from dev.logger import logger_setup def main(): # setup logger_setup(Config.get('APP_LOG_FILE'), ['ddd_site_parse']) # log logger = logging.getLogger('ddd_site_parse') logger.addHandler(logging.NullHandler()) logger.info(' --- ') logger.info('Start app...') # bot with open(Config.get('APP_OUTPUT_CSV'), 'w', newline='') as output: writer = csv.writer(output, delimiter=';') try: threads_counter = int(Config.get('APP_THREAD_COUNT')) bot = DSpider(thread_number=threads_counter, logger_name='ddd_site_parse', writer=writer) bot.run() except Exception as e: print(e) logger.info('End app...\n\n') if __name__ == '__main__': main() ## Instruction: Add encoding support, move output to separate directory, change output filename to DD_MM_YYYY.csv ## Code After: import csv import logging import os import time from config.config import Config from d_spider import DSpider from dev.logger import logger_setup def main(): # setup logger_setup(Config.get('APP_LOG_FILE'), ['ddd_site_parse']) # log logger = logging.getLogger('ddd_site_parse') logger.addHandler(logging.NullHandler()) logger.info(' --- ') logger.info('Start app...') # bot output_file_name = time.strftime('%d_%m_%Y') + '.csv' output_path = os.path.join(Config.get('APP_OUTPUT_DIR'), output_file_name) if not os.path.exists(Config.get('APP_OUTPUT_DIR')): logger.info('Create directory, because not exist') os.makedirs(Config.get('APP_OUTPUT_DIR')) with open(output_path, 'w', newline='', encoding=Config.get('APP_OUTPUT_ENC')) as output: writer = csv.writer(output, delimiter=';') try: threads_counter = int(Config.get('APP_THREAD_COUNT')) bot = DSpider(thread_number=threads_counter, logger_name='ddd_site_parse', writer=writer) bot.run() except Exception as e: print(e) logger.info('End app...\n\n') if __name__ == '__main__': main()
... import logging import os import time ... # bot output_file_name = time.strftime('%d_%m_%Y') + '.csv' output_path = os.path.join(Config.get('APP_OUTPUT_DIR'), output_file_name) if not os.path.exists(Config.get('APP_OUTPUT_DIR')): logger.info('Create directory, because not exist') os.makedirs(Config.get('APP_OUTPUT_DIR')) with open(output_path, 'w', newline='', encoding=Config.get('APP_OUTPUT_ENC')) as output: writer = csv.writer(output, delimiter=';') ...
f0ac78b3bfc0f81f142e66030e1e822dacfafe14
setup.py
setup.py
from distutils.core import setup setup(name='ansi', version='0.3.0', description='ANSI cursor movement and graphics', author='Wijnand Modderman-Lenstra', author_email='[email protected]', url='https://github.com/tehmaze/ansi/', packages = ['ansi', 'ansi.colour'], long_description=''' ANSI ==== Various ANSI escape codes, used in moving the cursor in a text console or rendering coloured text. Example ------- Print something in bold yellow on a red background:: >>> from ansi.colour import fg, bg, reset >>> print map(str, [bg.red, fg.yellow, 'Hello world!', reset]) ... If you like syntactic sugar, you may also do:: >>> print bg.red(fg.yellow('Hello world!')) ... Also, 256 RGB colors are supported:: >>> from ansi.colour import rgb, reset >>> print rgb(0xff, 0x80, 0x00) + 'hello world' + reset ... If you prefer to use American English in stead:: >>> from ansi.color import ... ''')
from distutils.core import setup setup(name='ansi', version='0.3.0', description='ANSI cursor movement and graphics', author='Wijnand Modderman-Lenstra', author_email='[email protected]', url='https://github.com/tehmaze/ansi/', packages = ['ansi', 'ansi.colour'], package_data = {'ansi': ['py.typed']}, long_description=''' ANSI ==== Various ANSI escape codes, used in moving the cursor in a text console or rendering coloured text. Example ------- Print something in bold yellow on a red background:: >>> from ansi.colour import fg, bg, reset >>> print map(str, [bg.red, fg.yellow, 'Hello world!', reset]) ... If you like syntactic sugar, you may also do:: >>> print bg.red(fg.yellow('Hello world!')) ... Also, 256 RGB colors are supported:: >>> from ansi.colour import rgb, reset >>> print rgb(0xff, 0x80, 0x00) + 'hello world' + reset ... If you prefer to use American English in stead:: >>> from ansi.color import ... ''')
Include py.typed marker in package
Include py.typed marker in package
Python
mit
tehmaze/ansi
from distutils.core import setup setup(name='ansi', version='0.3.0', description='ANSI cursor movement and graphics', author='Wijnand Modderman-Lenstra', author_email='[email protected]', url='https://github.com/tehmaze/ansi/', packages = ['ansi', 'ansi.colour'], + package_data = {'ansi': ['py.typed']}, long_description=''' ANSI ==== Various ANSI escape codes, used in moving the cursor in a text console or rendering coloured text. Example ------- Print something in bold yellow on a red background:: >>> from ansi.colour import fg, bg, reset >>> print map(str, [bg.red, fg.yellow, 'Hello world!', reset]) ... If you like syntactic sugar, you may also do:: >>> print bg.red(fg.yellow('Hello world!')) ... Also, 256 RGB colors are supported:: >>> from ansi.colour import rgb, reset >>> print rgb(0xff, 0x80, 0x00) + 'hello world' + reset ... If you prefer to use American English in stead:: >>> from ansi.color import ... ''')
Include py.typed marker in package
## Code Before: from distutils.core import setup setup(name='ansi', version='0.3.0', description='ANSI cursor movement and graphics', author='Wijnand Modderman-Lenstra', author_email='[email protected]', url='https://github.com/tehmaze/ansi/', packages = ['ansi', 'ansi.colour'], long_description=''' ANSI ==== Various ANSI escape codes, used in moving the cursor in a text console or rendering coloured text. Example ------- Print something in bold yellow on a red background:: >>> from ansi.colour import fg, bg, reset >>> print map(str, [bg.red, fg.yellow, 'Hello world!', reset]) ... If you like syntactic sugar, you may also do:: >>> print bg.red(fg.yellow('Hello world!')) ... Also, 256 RGB colors are supported:: >>> from ansi.colour import rgb, reset >>> print rgb(0xff, 0x80, 0x00) + 'hello world' + reset ... If you prefer to use American English in stead:: >>> from ansi.color import ... ''') ## Instruction: Include py.typed marker in package ## Code After: from distutils.core import setup setup(name='ansi', version='0.3.0', description='ANSI cursor movement and graphics', author='Wijnand Modderman-Lenstra', author_email='[email protected]', url='https://github.com/tehmaze/ansi/', packages = ['ansi', 'ansi.colour'], package_data = {'ansi': ['py.typed']}, long_description=''' ANSI ==== Various ANSI escape codes, used in moving the cursor in a text console or rendering coloured text. Example ------- Print something in bold yellow on a red background:: >>> from ansi.colour import fg, bg, reset >>> print map(str, [bg.red, fg.yellow, 'Hello world!', reset]) ... If you like syntactic sugar, you may also do:: >>> print bg.red(fg.yellow('Hello world!')) ... Also, 256 RGB colors are supported:: >>> from ansi.colour import rgb, reset >>> print rgb(0xff, 0x80, 0x00) + 'hello world' + reset ... If you prefer to use American English in stead:: >>> from ansi.color import ... ''')
# ... existing code ... packages = ['ansi', 'ansi.colour'], package_data = {'ansi': ['py.typed']}, long_description=''' # ... rest of the code ...
f413f5bc2015843a4e74dd969d56bc54f9dbba4e
deconstrst/__init__.py
deconstrst/__init__.py
import sys from sphinxwrapper import build __author__ = 'Ash Wilson' __email__ = '[email protected]' __version__ = '0.1.0' def main(): sys.exit(build(sys.argv)) if __name__ == '__main__': main()
import sys from deconstrst import build __author__ = 'Ash Wilson' __email__ = '[email protected]' __version__ = '0.1.0' def main(): sys.exit(build(sys.argv)) if __name__ == '__main__': main()
Fix an import that missed the renaming sweep.
Fix an import that missed the renaming sweep.
Python
apache-2.0
deconst/preparer-sphinx,ktbartholomew/preparer-sphinx,smashwilson/deconst-preparer-sphinx,deconst/preparer-sphinx,ktbartholomew/preparer-sphinx
import sys - from sphinxwrapper import build + from deconstrst import build __author__ = 'Ash Wilson' __email__ = '[email protected]' __version__ = '0.1.0' def main(): sys.exit(build(sys.argv)) if __name__ == '__main__': main()
Fix an import that missed the renaming sweep.
## Code Before: import sys from sphinxwrapper import build __author__ = 'Ash Wilson' __email__ = '[email protected]' __version__ = '0.1.0' def main(): sys.exit(build(sys.argv)) if __name__ == '__main__': main() ## Instruction: Fix an import that missed the renaming sweep. ## Code After: import sys from deconstrst import build __author__ = 'Ash Wilson' __email__ = '[email protected]' __version__ = '0.1.0' def main(): sys.exit(build(sys.argv)) if __name__ == '__main__': main()
// ... existing code ... import sys from deconstrst import build // ... rest of the code ...
ebb0916a7c63c1aaf383c696c203199ca79f70ac
nereid/backend.py
nereid/backend.py
''' nereid.backend Backed - Tryton specific features :copyright: (c) 2010-2012 by Openlabs Technologies & Consulting (P) Ltd. :license: GPLv3, see LICENSE for more details ''' class TransactionManager(object): def __init__(self, database_name, user, context=None): self.database_name = database_name self.user = user self.context = context if context is not None else {} def __enter__(self): from trytond.transaction import Transaction Transaction().start(self.database_name, self.user, self.context.copy()) return Transaction() def __exit__(self, type, value, traceback): from trytond.transaction import Transaction Transaction().stop()
''' nereid.backend Backed - Tryton specific features :copyright: (c) 2010-2012 by Openlabs Technologies & Consulting (P) Ltd. :license: GPLv3, see LICENSE for more details ''' class TransactionManager(object): def __init__(self, database_name, user, context=None): self.database_name = database_name self.user = user self.context = context if context is not None else {} def __enter__(self): from trytond.transaction import Transaction Transaction().start( self.database_name, self.user, readonly=False, context=self.context.copy() ) return Transaction() def __exit__(self, type, value, traceback): from trytond.transaction import Transaction Transaction().stop()
Change the way transaction is initiated as readonly support was introduced in version 2.4
Change the way transaction is initiated as readonly support was introduced in version 2.4
Python
bsd-3-clause
riteshshrv/nereid,usudaysingh/nereid,usudaysingh/nereid,riteshshrv/nereid,fulfilio/nereid,fulfilio/nereid,prakashpp/nereid,prakashpp/nereid
''' nereid.backend Backed - Tryton specific features :copyright: (c) 2010-2012 by Openlabs Technologies & Consulting (P) Ltd. :license: GPLv3, see LICENSE for more details ''' class TransactionManager(object): def __init__(self, database_name, user, context=None): self.database_name = database_name self.user = user self.context = context if context is not None else {} def __enter__(self): from trytond.transaction import Transaction - Transaction().start(self.database_name, self.user, self.context.copy()) + Transaction().start( + self.database_name, self.user, + readonly=False, context=self.context.copy() + ) return Transaction() def __exit__(self, type, value, traceback): from trytond.transaction import Transaction Transaction().stop()
Change the way transaction is initiated as readonly support was introduced in version 2.4
## Code Before: ''' nereid.backend Backed - Tryton specific features :copyright: (c) 2010-2012 by Openlabs Technologies & Consulting (P) Ltd. :license: GPLv3, see LICENSE for more details ''' class TransactionManager(object): def __init__(self, database_name, user, context=None): self.database_name = database_name self.user = user self.context = context if context is not None else {} def __enter__(self): from trytond.transaction import Transaction Transaction().start(self.database_name, self.user, self.context.copy()) return Transaction() def __exit__(self, type, value, traceback): from trytond.transaction import Transaction Transaction().stop() ## Instruction: Change the way transaction is initiated as readonly support was introduced in version 2.4 ## Code After: ''' nereid.backend Backed - Tryton specific features :copyright: (c) 2010-2012 by Openlabs Technologies & Consulting (P) Ltd. :license: GPLv3, see LICENSE for more details ''' class TransactionManager(object): def __init__(self, database_name, user, context=None): self.database_name = database_name self.user = user self.context = context if context is not None else {} def __enter__(self): from trytond.transaction import Transaction Transaction().start( self.database_name, self.user, readonly=False, context=self.context.copy() ) return Transaction() def __exit__(self, type, value, traceback): from trytond.transaction import Transaction Transaction().stop()
# ... existing code ... from trytond.transaction import Transaction Transaction().start( self.database_name, self.user, readonly=False, context=self.context.copy() ) return Transaction() # ... rest of the code ...
b235ae762adb76fe9835d98f7e2a4fc3d92db251
src/util/sortLargeFIs.py
src/util/sortLargeFIs.py
import os, sys from operator import itemgetter def errorExit(msg): sys.stderr.write(msg) sys.exit(1) def main(): # Verify arguments if len(sys.argv) != 2: errorExit("Usage: {} FILE\n".format(os.path.basename(sys.argv[0]))) fileName = sys.argv[1] if not os.path.isfile(fileName): errorExit("{} does not exist, or is not a file\n".format(fileName)) results = [] with open(fileName) as FILE: for line in FILE: tokens = line.split("\t") frequency = float(tokens[1]) results.append((line, frequency)) results.sort(key=itemgetter(1), reverse=True) for tup in results: sys.stdout.write(tup[0]) if __name__ == "__main__": main()
import os, sys from operator import itemgetter def errorExit(msg): sys.stderr.write(msg) sys.exit(1) def main(): # Verify arguments if len(sys.argv) != 2: errorExit("Usage: {} FILE\n".format(os.path.basename(sys.argv[0]))) fileName = sys.argv[1] if not os.path.isfile(fileName): errorExit("{} does not exist, or is not a file\n".format(fileName)) results = [] with open(fileName) as FILE: for line in FILE: tokens = line.split("}") itemset = tokens[0][1:-1] frequency = float((tokens[1].split(" "))[0][2:-3]) results.append((itemset + "\t" + str(frequency)+"\n", frequency)) results.sort(key=itemgetter(1), reverse=True) for tup in results: sys.stdout.write(tup[0]) if __name__ == "__main__": main()
Modify to handle ARtool output
Modify to handle ARtool output
Python
apache-2.0
jdebrabant/parallel_arules,jdebrabant/parallel_arules,jdebrabant/parallel_arules,jdebrabant/parallel_arules
import os, sys from operator import itemgetter def errorExit(msg): sys.stderr.write(msg) sys.exit(1) def main(): # Verify arguments if len(sys.argv) != 2: errorExit("Usage: {} FILE\n".format(os.path.basename(sys.argv[0]))) fileName = sys.argv[1] if not os.path.isfile(fileName): errorExit("{} does not exist, or is not a file\n".format(fileName)) results = [] with open(fileName) as FILE: for line in FILE: - tokens = line.split("\t") + tokens = line.split("}") + itemset = tokens[0][1:-1] - frequency = float(tokens[1]) + frequency = float((tokens[1].split(" "))[0][2:-3]) - results.append((line, frequency)) + results.append((itemset + "\t" + str(frequency)+"\n", frequency)) results.sort(key=itemgetter(1), reverse=True) for tup in results: sys.stdout.write(tup[0]) if __name__ == "__main__": main()
Modify to handle ARtool output
## Code Before: import os, sys from operator import itemgetter def errorExit(msg): sys.stderr.write(msg) sys.exit(1) def main(): # Verify arguments if len(sys.argv) != 2: errorExit("Usage: {} FILE\n".format(os.path.basename(sys.argv[0]))) fileName = sys.argv[1] if not os.path.isfile(fileName): errorExit("{} does not exist, or is not a file\n".format(fileName)) results = [] with open(fileName) as FILE: for line in FILE: tokens = line.split("\t") frequency = float(tokens[1]) results.append((line, frequency)) results.sort(key=itemgetter(1), reverse=True) for tup in results: sys.stdout.write(tup[0]) if __name__ == "__main__": main() ## Instruction: Modify to handle ARtool output ## Code After: import os, sys from operator import itemgetter def errorExit(msg): sys.stderr.write(msg) sys.exit(1) def main(): # Verify arguments if len(sys.argv) != 2: errorExit("Usage: {} FILE\n".format(os.path.basename(sys.argv[0]))) fileName = sys.argv[1] if not os.path.isfile(fileName): errorExit("{} does not exist, or is not a file\n".format(fileName)) results = [] with open(fileName) as FILE: for line in FILE: tokens = line.split("}") itemset = tokens[0][1:-1] frequency = float((tokens[1].split(" "))[0][2:-3]) results.append((itemset + "\t" + str(frequency)+"\n", frequency)) results.sort(key=itemgetter(1), reverse=True) for tup in results: sys.stdout.write(tup[0]) if __name__ == "__main__": main()
... for line in FILE: tokens = line.split("}") itemset = tokens[0][1:-1] frequency = float((tokens[1].split(" "))[0][2:-3]) results.append((itemset + "\t" + str(frequency)+"\n", frequency)) ...
1fce663e37823d985d00d1700aba5e067157b789
profiles/tests.py
profiles/tests.py
from django.contrib.auth.models import User from django.test import TestCase import factory from .models import Profile class UserFactory(factory.Factory): FACTORY_FOR = User first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n)) last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)) username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower()) email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) class ProfileFactory(UserFactory): FACTORY_FOR = Profile user_ptr = factory.SubFactory(UserFactory) class ProfileUtils(object): def generate_profile(self, **kwargs): password = kwargs.pop('password', 'test') profile = ProfileFactory.build(**kwargs) profile.set_password(password) profile.save() return profile def login(self, user=None, password='test'): user = user or self.user self.client.login(username=user.username, password=password)
from django.contrib.auth.models import User import factory from .models import Profile class UserFactory(factory.Factory): FACTORY_FOR = User first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n)) last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)) username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower()) email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) @classmethod def _prepare(cls, create, **kwargs): password = kwargs.pop('password', 'password') user = super(UserFactory, cls)._prepare(create=False, **kwargs) user.set_password(password) user.raw_password = password if create: user.save() return user class ProfileFactory(UserFactory): FACTORY_FOR = Profile user_ptr = factory.SubFactory(UserFactory) class ProfileUtils(object): def generate_profile(self, **kwargs): password = kwargs.pop('password', 'test') profile = ProfileFactory.build(**kwargs) profile.set_password(password) profile.save() return profile def login(self, user=None, password='test'): user = user or self.user self.client.login(username=user.username, password=password)
Add password handling to default factory.
Add password handling to default factory.
Python
bsd-2-clause
incuna/django-extensible-profiles
from django.contrib.auth.models import User - from django.test import TestCase + import factory from .models import Profile class UserFactory(factory.Factory): FACTORY_FOR = User first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n)) last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)) username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower()) email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) + + @classmethod + def _prepare(cls, create, **kwargs): + password = kwargs.pop('password', 'password') + user = super(UserFactory, cls)._prepare(create=False, **kwargs) + user.set_password(password) + user.raw_password = password + if create: + user.save() + return user class ProfileFactory(UserFactory): FACTORY_FOR = Profile user_ptr = factory.SubFactory(UserFactory) class ProfileUtils(object): def generate_profile(self, **kwargs): password = kwargs.pop('password', 'test') profile = ProfileFactory.build(**kwargs) profile.set_password(password) profile.save() return profile def login(self, user=None, password='test'): user = user or self.user self.client.login(username=user.username, password=password)
Add password handling to default factory.
## Code Before: from django.contrib.auth.models import User from django.test import TestCase import factory from .models import Profile class UserFactory(factory.Factory): FACTORY_FOR = User first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n)) last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)) username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower()) email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) class ProfileFactory(UserFactory): FACTORY_FOR = Profile user_ptr = factory.SubFactory(UserFactory) class ProfileUtils(object): def generate_profile(self, **kwargs): password = kwargs.pop('password', 'test') profile = ProfileFactory.build(**kwargs) profile.set_password(password) profile.save() return profile def login(self, user=None, password='test'): user = user or self.user self.client.login(username=user.username, password=password) ## Instruction: Add password handling to default factory. ## Code After: from django.contrib.auth.models import User import factory from .models import Profile class UserFactory(factory.Factory): FACTORY_FOR = User first_name = factory.Sequence(lambda n: 'Firstname {0}'.format(n)) last_name = factory.Sequence(lambda n: 'Lastname {0}'.format(n)) username = factory.Sequence(lambda n: 'user-{0}'.format(n).lower()) email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) @classmethod def _prepare(cls, create, **kwargs): password = kwargs.pop('password', 'password') user = super(UserFactory, cls)._prepare(create=False, **kwargs) user.set_password(password) user.raw_password = password if create: user.save() return user class ProfileFactory(UserFactory): FACTORY_FOR = Profile user_ptr = factory.SubFactory(UserFactory) class ProfileUtils(object): def generate_profile(self, **kwargs): password = kwargs.pop('password', 'test') profile = ProfileFactory.build(**kwargs) profile.set_password(password) profile.save() return profile def login(self, user=None, password='test'): user = user or self.user self.client.login(username=user.username, password=password)
# ... existing code ... from django.contrib.auth.models import User import factory # ... modified code ... email = factory.LazyAttribute(lambda a: '{0}@example.com'.format(a.username).lower()) @classmethod def _prepare(cls, create, **kwargs): password = kwargs.pop('password', 'password') user = super(UserFactory, cls)._prepare(create=False, **kwargs) user.set_password(password) user.raw_password = password if create: user.save() return user # ... rest of the code ...
45c4c1f627f224f36c24acebbec43a17a5c59fcb
nib/plugins/lesscss.py
nib/plugins/lesscss.py
from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource
from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) print("Processing: ", filepath) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource
Print out file being processed, need to do to other modules, add -v flag
Print out file being processed, need to do to other modules, add -v flag
Python
mit
jreese/nib
from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) + print("Processing: ", filepath) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource
Print out file being processed, need to do to other modules, add -v flag
## Code Before: from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource ## Instruction: Print out file being processed, need to do to other modules, add -v flag ## Code After: from __future__ import absolute_import, division, print_function, unicode_literals from os import path import sh from nib import Processor, resource @resource('.less') class LessCSSProcessor(Processor): def resource(self, resource): filepath = path.join(self.options['resource_path'], resource.path + resource.extension) print("Processing: ", filepath) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') resource.extension = '.css' return resource
... resource.path + resource.extension) print("Processing: ", filepath) resource.content = bytearray(str(sh.lessc(filepath)), 'utf-8') ...
293b1d492cfd3c5542c78acffbbdebf4933b6d85
django_db_geventpool/backends/postgresql_psycopg2/creation.py
django_db_geventpool/backends/postgresql_psycopg2/creation.py
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation class DatabaseCreation(OriginalDatabaseCreation): def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreation, self)._destroy_test_db(test_database_name, verbosity)
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation class DatabaseCreation(OriginalDatabaseCreation): def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreation, self)._destroy_test_db(test_database_name, verbosity) def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() return super(DatabaseCreation, self)._create_test_db(verbosity, autoclobber)
Handle open connections when creating the test database
Handle open connections when creating the test database
Python
apache-2.0
jneight/django-db-geventpool,PreppyLLC-opensource/django-db-geventpool
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation class DatabaseCreation(OriginalDatabaseCreation): def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreation, self)._destroy_test_db(test_database_name, verbosity) + def _create_test_db(self, verbosity, autoclobber): + self.connection.closeall() + return super(DatabaseCreation, self)._create_test_db(verbosity, autoclobber) -
Handle open connections when creating the test database
## Code Before: from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation class DatabaseCreation(OriginalDatabaseCreation): def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreation, self)._destroy_test_db(test_database_name, verbosity) ## Instruction: Handle open connections when creating the test database ## Code After: from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation as OriginalDatabaseCreation class DatabaseCreation(OriginalDatabaseCreation): def _destroy_test_db(self, test_database_name, verbosity): self.connection.closeall() return super(DatabaseCreation, self)._destroy_test_db(test_database_name, verbosity) def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() return super(DatabaseCreation, self)._create_test_db(verbosity, autoclobber)
# ... existing code ... return super(DatabaseCreation, self)._destroy_test_db(test_database_name, verbosity) def _create_test_db(self, verbosity, autoclobber): self.connection.closeall() return super(DatabaseCreation, self)._create_test_db(verbosity, autoclobber) # ... rest of the code ...
222e2a70f9c2d4ce7cb4a26d717c6bcce1e3f344
tests/utils.py
tests/utils.py
import os import pytest from tests.consts import examples_path from valohai_yaml import parse def _load_config(filename, roundtrip): with open(os.path.join(examples_path, filename), 'r') as infp: config = parse(infp) if roundtrip: config = parse(config.serialize()) return config def config_fixture(name): @pytest.fixture(params=[False, True]) def _config_fixture(request): return _load_config(name, roundtrip=request.param) return _config_fixture
import os import pytest from tests.consts import examples_path from valohai_yaml import parse def _load_config(filename, roundtrip): with open(os.path.join(examples_path, filename), 'r') as infp: config = parse(infp) if roundtrip: config = parse(config.serialize()) return config def config_fixture(name): @pytest.fixture(params=[False, True], ids=['direct', 'roundtrip']) def _config_fixture(request): return _load_config(name, roundtrip=request.param) return _config_fixture
Add nicer ids for tests
Add nicer ids for tests
Python
mit
valohai/valohai-yaml
import os import pytest from tests.consts import examples_path from valohai_yaml import parse def _load_config(filename, roundtrip): with open(os.path.join(examples_path, filename), 'r') as infp: config = parse(infp) if roundtrip: config = parse(config.serialize()) return config def config_fixture(name): - @pytest.fixture(params=[False, True]) + @pytest.fixture(params=[False, True], ids=['direct', 'roundtrip']) def _config_fixture(request): return _load_config(name, roundtrip=request.param) return _config_fixture
Add nicer ids for tests
## Code Before: import os import pytest from tests.consts import examples_path from valohai_yaml import parse def _load_config(filename, roundtrip): with open(os.path.join(examples_path, filename), 'r') as infp: config = parse(infp) if roundtrip: config = parse(config.serialize()) return config def config_fixture(name): @pytest.fixture(params=[False, True]) def _config_fixture(request): return _load_config(name, roundtrip=request.param) return _config_fixture ## Instruction: Add nicer ids for tests ## Code After: import os import pytest from tests.consts import examples_path from valohai_yaml import parse def _load_config(filename, roundtrip): with open(os.path.join(examples_path, filename), 'r') as infp: config = parse(infp) if roundtrip: config = parse(config.serialize()) return config def config_fixture(name): @pytest.fixture(params=[False, True], ids=['direct', 'roundtrip']) def _config_fixture(request): return _load_config(name, roundtrip=request.param) return _config_fixture
// ... existing code ... def config_fixture(name): @pytest.fixture(params=[False, True], ids=['direct', 'roundtrip']) def _config_fixture(request): // ... rest of the code ...
2b479927ee33181c57081df941bfdf347cd45423
test/test_serenata_de_amor.py
test/test_serenata_de_amor.py
from unittest import TestCase class TestSerenataDeAmor(TestCase): def test_it_works(self): self.assertEqual(4, 2 + 2) self.assertNotEqual(5, 2 + 2)
import glob import subprocess from unittest import TestCase class TestSerenataDeAmor(TestCase): def setUp(self): self.notebook_files = glob.glob('develop/*.ipynb') def test_html_versions_present(self): """There is a *.html version of every Jupyter notebook.""" expected = [filename.replace('.ipynb', '.html') for filename in self.notebook_files] html_files = glob.glob('develop/*.html') self.assertEqual(expected, html_files) def test_py_versions_present(self): """There is a *.py version of every Jupyter notebook.""" expected = [filename.replace('.ipynb', '.py') for filename in self.notebook_files] py_files = glob.glob('develop/*.py') self.assertEqual(expected, py_files)
Verify existence of *.html and *.py versions for every notebook
Verify existence of *.html and *.py versions for every notebook
Python
mit
marcusrehm/serenata-de-amor,datasciencebr/serenata-de-amor,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor,datasciencebr/serenata-de-amor
+ import glob + import subprocess from unittest import TestCase class TestSerenataDeAmor(TestCase): + def setUp(self): + self.notebook_files = glob.glob('develop/*.ipynb') - def test_it_works(self): - self.assertEqual(4, 2 + 2) - self.assertNotEqual(5, 2 + 2) + def test_html_versions_present(self): + """There is a *.html version of every Jupyter notebook.""" + expected = [filename.replace('.ipynb', '.html') + for filename in self.notebook_files] + html_files = glob.glob('develop/*.html') + self.assertEqual(expected, html_files) + + def test_py_versions_present(self): + """There is a *.py version of every Jupyter notebook.""" + expected = [filename.replace('.ipynb', '.py') + for filename in self.notebook_files] + py_files = glob.glob('develop/*.py') + self.assertEqual(expected, py_files) +
Verify existence of *.html and *.py versions for every notebook
## Code Before: from unittest import TestCase class TestSerenataDeAmor(TestCase): def test_it_works(self): self.assertEqual(4, 2 + 2) self.assertNotEqual(5, 2 + 2) ## Instruction: Verify existence of *.html and *.py versions for every notebook ## Code After: import glob import subprocess from unittest import TestCase class TestSerenataDeAmor(TestCase): def setUp(self): self.notebook_files = glob.glob('develop/*.ipynb') def test_html_versions_present(self): """There is a *.html version of every Jupyter notebook.""" expected = [filename.replace('.ipynb', '.html') for filename in self.notebook_files] html_files = glob.glob('develop/*.html') self.assertEqual(expected, html_files) def test_py_versions_present(self): """There is a *.py version of every Jupyter notebook.""" expected = [filename.replace('.ipynb', '.py') for filename in self.notebook_files] py_files = glob.glob('develop/*.py') self.assertEqual(expected, py_files)
// ... existing code ... import glob import subprocess from unittest import TestCase // ... modified code ... def setUp(self): self.notebook_files = glob.glob('develop/*.ipynb') def test_html_versions_present(self): """There is a *.html version of every Jupyter notebook.""" expected = [filename.replace('.ipynb', '.html') for filename in self.notebook_files] html_files = glob.glob('develop/*.html') self.assertEqual(expected, html_files) def test_py_versions_present(self): """There is a *.py version of every Jupyter notebook.""" expected = [filename.replace('.ipynb', '.py') for filename in self.notebook_files] py_files = glob.glob('develop/*.py') self.assertEqual(expected, py_files) // ... rest of the code ...
64219411d0bcbb7dafc754bef8538fc237584031
go/vumitools/tests/test_api_worker.py
go/vumitools/tests/test_api_worker.py
"""Tests for go.vumitools.api_worker.""" from twisted.internet.defer import inlineCallbacks from vumi.application.tests.test_base import ApplicationTestCase from go.vumitools.api_worker import VumiApiWorker from go.vumitools.api import VumiApiCommand class TestVumiApiWorker(ApplicationTestCase): application_class = VumiApiWorker @inlineCallbacks def setUp(self): super(TestVumiApiWorker, self).setUp() config = { 'send_to': { 'default': { 'transport_name': 'test_transport', }, }, } self.api = yield self.get_application(config) def publish_command(self, cmd): return self.dispatch(cmd, rkey='vumi.api') @inlineCallbacks def test_send(self): yield self.publish_command(VumiApiCommand.send('batch1', 'content', 'to_addr')) [msg] = yield self.get_dispatched_messages() self.assertEqual(msg['to_addr'], 'to_addr') self.assertEqual(msg['content'], 'content')
"""Tests for go.vumitools.api_worker.""" from twisted.internet.defer import inlineCallbacks from vumi.application.tests.test_base import ApplicationTestCase from go.vumitools.api_worker import VumiApiWorker from go.vumitools.api import VumiApiCommand class TestVumiApiWorker(ApplicationTestCase): application_class = VumiApiWorker @inlineCallbacks def setUp(self): super(TestVumiApiWorker, self).setUp() self.api = yield self.get_application({}) def publish_command(self, cmd): return self.dispatch(cmd, rkey='vumi.api') @inlineCallbacks def test_send(self): yield self.publish_command(VumiApiCommand.send('batch1', 'content', 'to_addr')) [msg] = yield self.get_dispatched_messages() self.assertEqual(msg['to_addr'], 'to_addr') self.assertEqual(msg['content'], 'content')
Remove send_to config from tests since Vumi's application test class now adds this automatically.
Remove send_to config from tests since Vumi's application test class now adds this automatically.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
"""Tests for go.vumitools.api_worker.""" from twisted.internet.defer import inlineCallbacks from vumi.application.tests.test_base import ApplicationTestCase from go.vumitools.api_worker import VumiApiWorker from go.vumitools.api import VumiApiCommand class TestVumiApiWorker(ApplicationTestCase): application_class = VumiApiWorker @inlineCallbacks def setUp(self): super(TestVumiApiWorker, self).setUp() - config = { - 'send_to': { - 'default': { - 'transport_name': 'test_transport', - }, - }, - } - self.api = yield self.get_application(config) + self.api = yield self.get_application({}) def publish_command(self, cmd): return self.dispatch(cmd, rkey='vumi.api') @inlineCallbacks def test_send(self): yield self.publish_command(VumiApiCommand.send('batch1', 'content', 'to_addr')) [msg] = yield self.get_dispatched_messages() self.assertEqual(msg['to_addr'], 'to_addr') self.assertEqual(msg['content'], 'content')
Remove send_to config from tests since Vumi's application test class now adds this automatically.
## Code Before: """Tests for go.vumitools.api_worker.""" from twisted.internet.defer import inlineCallbacks from vumi.application.tests.test_base import ApplicationTestCase from go.vumitools.api_worker import VumiApiWorker from go.vumitools.api import VumiApiCommand class TestVumiApiWorker(ApplicationTestCase): application_class = VumiApiWorker @inlineCallbacks def setUp(self): super(TestVumiApiWorker, self).setUp() config = { 'send_to': { 'default': { 'transport_name': 'test_transport', }, }, } self.api = yield self.get_application(config) def publish_command(self, cmd): return self.dispatch(cmd, rkey='vumi.api') @inlineCallbacks def test_send(self): yield self.publish_command(VumiApiCommand.send('batch1', 'content', 'to_addr')) [msg] = yield self.get_dispatched_messages() self.assertEqual(msg['to_addr'], 'to_addr') self.assertEqual(msg['content'], 'content') ## Instruction: Remove send_to config from tests since Vumi's application test class now adds this automatically. ## Code After: """Tests for go.vumitools.api_worker.""" from twisted.internet.defer import inlineCallbacks from vumi.application.tests.test_base import ApplicationTestCase from go.vumitools.api_worker import VumiApiWorker from go.vumitools.api import VumiApiCommand class TestVumiApiWorker(ApplicationTestCase): application_class = VumiApiWorker @inlineCallbacks def setUp(self): super(TestVumiApiWorker, self).setUp() self.api = yield self.get_application({}) def publish_command(self, cmd): return self.dispatch(cmd, rkey='vumi.api') @inlineCallbacks def test_send(self): yield self.publish_command(VumiApiCommand.send('batch1', 'content', 'to_addr')) [msg] = yield self.get_dispatched_messages() self.assertEqual(msg['to_addr'], 'to_addr') self.assertEqual(msg['content'], 'content')
// ... existing code ... super(TestVumiApiWorker, self).setUp() self.api = yield self.get_application({}) // ... rest of the code ...
1b179405245bc7d7d6157528bd64e2b399491090
quantecon/optimize/__init__.py
quantecon/optimize/__init__.py
from .scalar_maximization import brent_max from .root_finding import *
from .scalar_maximization import brent_max from .root_finding import newton, newton_halley, newton_secant, bisect, brentq
Fix import to list items
Fix import to list items
Python
bsd-3-clause
oyamad/QuantEcon.py,QuantEcon/QuantEcon.py,oyamad/QuantEcon.py,QuantEcon/QuantEcon.py
from .scalar_maximization import brent_max - from .root_finding import * + from .root_finding import newton, newton_halley, newton_secant, bisect, brentq
Fix import to list items
## Code Before: from .scalar_maximization import brent_max from .root_finding import * ## Instruction: Fix import to list items ## Code After: from .scalar_maximization import brent_max from .root_finding import newton, newton_halley, newton_secant, bisect, brentq
... from .scalar_maximization import brent_max from .root_finding import newton, newton_halley, newton_secant, bisect, brentq ...
69853e5ef1ef297c776fd23a48b0ac0b2356f06f
examples/fantasy/tasks.py
examples/fantasy/tasks.py
import json from pathlib import Path import sys import sqlalchemy as sa from invoke import task FANTASY_DB_SQL = Path.cwd() / 'fantasy-database' / 'schema.sql' FANTASY_DB_DATA = Path.cwd() / 'fantasy-database' / 'data.json' @task def populate_db(ctx, data_file=FANTASY_DB_DATA): from examples.fantasy import tables if not Path(data_file).exists(): sys.exit(f'Invalid data file: {data_file}') with data_file.open() as f: data = json.load(f) create_sql = FANTASY_DB_SQL.read_text() engine = \ sa.create_engine('postgresql://example:somepassword@localhost/example', echo=True) conn = engine.connect() trans = conn.begin() conn.execute(sa.text(create_sql)) tables_in_order = ('photos', 'stores', 'authors', 'series', 'books', 'chapters', 'books_stores') try: for table_name in tables_in_order: table = getattr(tables, table_name) values = data[table_name] for value in values: query = table.insert().values(value) conn.execute(query) trans.commit() except Exception as exc: trans.rollback() raise print('\nDatabase is successfully populated!')
import json from pathlib import Path import sys import sqlalchemy as sa from invoke import task FANTASY_DATA_FOLDER = Path(__file__).parent / 'fantasy-database' @task def populate_db(ctx, data_folder=FANTASY_DATA_FOLDER, dsn=None): from examples.fantasy import tables data_file = data_folder / 'data.json' if not Path(data_file).exists(): sys.exit(f'Invalid data file: {data_file}') with data_file.open() as f: data = json.load(f) create_sql = (data_folder / 'schema.sql').read_text() if dsn is None: dsn = 'postgresql://example:somepassword@localhost/example' engine = sa.create_engine(dsn, echo=True) conn = engine.connect() trans = conn.begin() conn.execute(sa.text(create_sql)) tables_in_order = ('photos', 'stores', 'authors', 'series', 'books', 'chapters', 'books_stores') try: for table_name in tables_in_order: table = getattr(tables, table_name) values = data[table_name] for value in values: query = table.insert().values(value) conn.execute(query) trans.commit() except Exception as exc: trans.rollback() raise print('\nDatabase is successfully populated!')
Refactor populate_db pyinvoke task to use it in tests
Refactor populate_db pyinvoke task to use it in tests
Python
mit
vovanbo/aiohttp_json_api
import json from pathlib import Path import sys import sqlalchemy as sa from invoke import task + FANTASY_DATA_FOLDER = Path(__file__).parent / 'fantasy-database' - FANTASY_DB_SQL = Path.cwd() / 'fantasy-database' / 'schema.sql' - FANTASY_DB_DATA = Path.cwd() / 'fantasy-database' / 'data.json' @task - def populate_db(ctx, data_file=FANTASY_DB_DATA): + def populate_db(ctx, data_folder=FANTASY_DATA_FOLDER, dsn=None): from examples.fantasy import tables + data_file = data_folder / 'data.json' if not Path(data_file).exists(): sys.exit(f'Invalid data file: {data_file}') with data_file.open() as f: data = json.load(f) - create_sql = FANTASY_DB_SQL.read_text() + create_sql = (data_folder / 'schema.sql').read_text() - engine = \ + if dsn is None: - sa.create_engine('postgresql://example:somepassword@localhost/example', + dsn = 'postgresql://example:somepassword@localhost/example' - echo=True) + + engine = sa.create_engine(dsn, echo=True) conn = engine.connect() trans = conn.begin() conn.execute(sa.text(create_sql)) tables_in_order = ('photos', 'stores', 'authors', 'series', 'books', 'chapters', 'books_stores') try: for table_name in tables_in_order: table = getattr(tables, table_name) values = data[table_name] for value in values: query = table.insert().values(value) conn.execute(query) trans.commit() except Exception as exc: trans.rollback() raise print('\nDatabase is successfully populated!')
Refactor populate_db pyinvoke task to use it in tests
## Code Before: import json from pathlib import Path import sys import sqlalchemy as sa from invoke import task FANTASY_DB_SQL = Path.cwd() / 'fantasy-database' / 'schema.sql' FANTASY_DB_DATA = Path.cwd() / 'fantasy-database' / 'data.json' @task def populate_db(ctx, data_file=FANTASY_DB_DATA): from examples.fantasy import tables if not Path(data_file).exists(): sys.exit(f'Invalid data file: {data_file}') with data_file.open() as f: data = json.load(f) create_sql = FANTASY_DB_SQL.read_text() engine = \ sa.create_engine('postgresql://example:somepassword@localhost/example', echo=True) conn = engine.connect() trans = conn.begin() conn.execute(sa.text(create_sql)) tables_in_order = ('photos', 'stores', 'authors', 'series', 'books', 'chapters', 'books_stores') try: for table_name in tables_in_order: table = getattr(tables, table_name) values = data[table_name] for value in values: query = table.insert().values(value) conn.execute(query) trans.commit() except Exception as exc: trans.rollback() raise print('\nDatabase is successfully populated!') ## Instruction: Refactor populate_db pyinvoke task to use it in tests ## Code After: import json from pathlib import Path import sys import sqlalchemy as sa from invoke import task FANTASY_DATA_FOLDER = Path(__file__).parent / 'fantasy-database' @task def populate_db(ctx, data_folder=FANTASY_DATA_FOLDER, dsn=None): from examples.fantasy import tables data_file = data_folder / 'data.json' if not Path(data_file).exists(): sys.exit(f'Invalid data file: {data_file}') with data_file.open() as f: data = json.load(f) create_sql = (data_folder / 'schema.sql').read_text() if dsn is None: dsn = 'postgresql://example:somepassword@localhost/example' engine = sa.create_engine(dsn, echo=True) conn = engine.connect() trans = conn.begin() conn.execute(sa.text(create_sql)) tables_in_order = ('photos', 'stores', 'authors', 'series', 'books', 'chapters', 'books_stores') try: for table_name in tables_in_order: table = getattr(tables, table_name) values = data[table_name] for value in values: query = table.insert().values(value) conn.execute(query) trans.commit() except Exception as exc: trans.rollback() raise print('\nDatabase is successfully populated!')
// ... existing code ... FANTASY_DATA_FOLDER = Path(__file__).parent / 'fantasy-database' // ... modified code ... @task def populate_db(ctx, data_folder=FANTASY_DATA_FOLDER, dsn=None): from examples.fantasy import tables ... data_file = data_folder / 'data.json' if not Path(data_file).exists(): ... create_sql = (data_folder / 'schema.sql').read_text() if dsn is None: dsn = 'postgresql://example:somepassword@localhost/example' engine = sa.create_engine(dsn, echo=True) conn = engine.connect() // ... rest of the code ...
f80febf88c3f045493e75efc788d88058f021f0f
merge_sort.py
merge_sort.py
def merge_sort(lyst): buf = [len(lyst)] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high): lyst[i] = buf[i]
def merge_sort(lyst): buf = [None for x in range(len(lyst))] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high+1): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high+1): lyst[i] = buf[i]
Fix initial buf variable to act as an array
Fix initial buf variable to act as an array
Python
mit
nbeck90/data_structures_2
def merge_sort(lyst): - buf = [len(lyst)] + buf = [None for x in range(len(lyst))] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 - for i in range(low, high): + for i in range(low, high+1): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 - for i in range(low, high): + for i in range(low, high+1): lyst[i] = buf[i]
Fix initial buf variable to act as an array
## Code Before: def merge_sort(lyst): buf = [len(lyst)] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high): lyst[i] = buf[i] ## Instruction: Fix initial buf variable to act as an array ## Code After: def merge_sort(lyst): buf = [None for x in range(len(lyst))] _merge_sort(lyst, buf, 0, len(lyst)-1) def _merge_sort(lyst, buf, low, high): if low < high: middle = (low + high) // 2 _merge_sort(lyst, buf, low, middle) _merge_sort(lyst, buf, middle+1, high) merge(lyst, buf, low, middle, high) def merge(lyst, buf, low, middle, high): i1 = low i2 = middle + 1 for i in range(low, high+1): if i1 > middle: buf[i] = lyst[i2] i2 += 1 elif i2 > high: buf[i] = lyst[i1] i1 += 1 elif lyst[i1] < lyst[i2]: buf[i] = lyst[i] i1 += 1 else: buf[i] = lyst[i2] i2 += 1 for i in range(low, high+1): lyst[i] = buf[i]
// ... existing code ... def merge_sort(lyst): buf = [None for x in range(len(lyst))] _merge_sort(lyst, buf, 0, len(lyst)-1) // ... modified code ... for i in range(low, high+1): if i1 > middle: ... i2 += 1 for i in range(low, high+1): lyst[i] = buf[i] // ... rest of the code ...
5cf17b6a46a3d4bbf4cecb65e4b9ef43066869d9
feincms/templatetags/applicationcontent_tags.py
feincms/templatetags/applicationcontent_tags.py
from django import template # backwards compatibility import from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment register = template.Library() register.tag(fragment) register.tag(get_fragment) register.filter(has_fragment) @register.simple_tag def feincms_render_region_appcontent(page, region, request): """Render only the application content for the region This allows template authors to choose whether their page behaves differently when displaying embedded application subpages by doing something like this:: {% if not in_appcontent_subpage %} {% feincms_render_region feincms_page "main" request %} {% else %} {% feincms_render_region_appcontent feincms_page "main" request %} {% endif %} """ from feincms.content.application.models import ApplicationContent from feincms.templatetags.feincms_tags import _render_content return u''.join(_render_content(content, request=request) for content in\ getattr(page.content, region) if isinstance(content, ApplicationContent))
from django import template # backwards compatibility import from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment register = template.Library() register.tag(fragment) register.tag(get_fragment) register.filter(has_fragment) @register.simple_tag def feincms_render_region_appcontent(page, region, request): """Render only the application content for the region This allows template authors to choose whether their page behaves differently when displaying embedded application subpages by doing something like this:: {% if not in_appcontent_subpage %} {% feincms_render_region feincms_page "main" request %} {% else %} {% feincms_render_region_appcontent feincms_page "main" request %} {% endif %} """ from feincms.content.application.models import ApplicationContent from feincms.templatetags.feincms_tags import _render_content return u''.join(_render_content(content, request=request) for content in\ page.content.all_of_type(ApplicationContent) if content.region == region)
Use all_of_type instead of isinstance check in feincms_render_region_appcontent
Use all_of_type instead of isinstance check in feincms_render_region_appcontent
Python
bsd-3-clause
feincms/feincms,joshuajonah/feincms,feincms/feincms,matthiask/feincms2-content,matthiask/django-content-editor,michaelkuty/feincms,mjl/feincms,matthiask/feincms2-content,mjl/feincms,matthiask/django-content-editor,matthiask/django-content-editor,michaelkuty/feincms,nickburlett/feincms,matthiask/django-content-editor,joshuajonah/feincms,matthiask/feincms2-content,nickburlett/feincms,pjdelport/feincms,pjdelport/feincms,joshuajonah/feincms,pjdelport/feincms,michaelkuty/feincms,michaelkuty/feincms,nickburlett/feincms,feincms/feincms,nickburlett/feincms,joshuajonah/feincms,mjl/feincms
from django import template # backwards compatibility import from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment register = template.Library() register.tag(fragment) register.tag(get_fragment) register.filter(has_fragment) @register.simple_tag def feincms_render_region_appcontent(page, region, request): """Render only the application content for the region This allows template authors to choose whether their page behaves differently when displaying embedded application subpages by doing something like this:: {% if not in_appcontent_subpage %} {% feincms_render_region feincms_page "main" request %} {% else %} {% feincms_render_region_appcontent feincms_page "main" request %} {% endif %} """ from feincms.content.application.models import ApplicationContent from feincms.templatetags.feincms_tags import _render_content return u''.join(_render_content(content, request=request) for content in\ - getattr(page.content, region) if isinstance(content, ApplicationContent)) + page.content.all_of_type(ApplicationContent) if content.region == region)
Use all_of_type instead of isinstance check in feincms_render_region_appcontent
## Code Before: from django import template # backwards compatibility import from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment register = template.Library() register.tag(fragment) register.tag(get_fragment) register.filter(has_fragment) @register.simple_tag def feincms_render_region_appcontent(page, region, request): """Render only the application content for the region This allows template authors to choose whether their page behaves differently when displaying embedded application subpages by doing something like this:: {% if not in_appcontent_subpage %} {% feincms_render_region feincms_page "main" request %} {% else %} {% feincms_render_region_appcontent feincms_page "main" request %} {% endif %} """ from feincms.content.application.models import ApplicationContent from feincms.templatetags.feincms_tags import _render_content return u''.join(_render_content(content, request=request) for content in\ getattr(page.content, region) if isinstance(content, ApplicationContent)) ## Instruction: Use all_of_type instead of isinstance check in feincms_render_region_appcontent ## Code After: from django import template # backwards compatibility import from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment register = template.Library() register.tag(fragment) register.tag(get_fragment) register.filter(has_fragment) @register.simple_tag def feincms_render_region_appcontent(page, region, request): """Render only the application content for the region This allows template authors to choose whether their page behaves differently when displaying embedded application subpages by doing something like this:: {% if not in_appcontent_subpage %} {% feincms_render_region feincms_page "main" request %} {% else %} {% feincms_render_region_appcontent feincms_page "main" request %} {% endif %} """ from feincms.content.application.models import ApplicationContent from feincms.templatetags.feincms_tags import _render_content return u''.join(_render_content(content, request=request) for content in\ page.content.all_of_type(ApplicationContent) if content.region == region)
# ... existing code ... return u''.join(_render_content(content, request=request) for content in\ page.content.all_of_type(ApplicationContent) if content.region == region) # ... rest of the code ...
d879d74aa078ca5a89a7e7cbd1bebe095449411d
snobol/constants.py
snobol/constants.py
coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64
# Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64
Add documentation string for cosntants module
Add documentation string for cosntants module
Python
mit
JALusk/SNoBoL,JALusk/SNoBoL,JALusk/SuperBoL
+ + # Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64
Add documentation string for cosntants module
## Code Before: coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64 ## Instruction: Add documentation string for cosntants module ## Code After: # Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] # Ranges of validity for polynomial fits min_BminusV = -0.2 max_BminusV = 1.65 min_VminusI = -0.1 max_VminusI = 1.0 min_BminusI = -0.4 max_BminusI = 3.0 # RMS errors in polynomial fits rms_err_BminusV = 0.113 rms_err_VminusI = 0.109 rms_err_BminusI = 0.091 # Zeropoint for use in the calculation of bolometric magnitude mbol_zeropoint = 11.64
// ... existing code ... # Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] // ... rest of the code ...
53a2d8781e3e5d8e5879d4ef7c62752483323cf9
bfg9000/shell/__init__.py
bfg9000/shell/__init__.py
import os import subprocess from ..platform_name import platform_name if platform_name() == 'windows': from .windows import * else: from .posix import * class shell_list(list): """A special subclass of list used to mark that this command line uses special shell characters.""" pass def execute(args, shell=False, env=None, quiet=False): if quiet: devnull = open(os.devnull, 'wb') try: return subprocess.check_output( args, universal_newlines=True, shell=shell, env=env ) except: if quiet: devnull.close() raise
import os import subprocess from ..platform_name import platform_name if platform_name() == 'windows': from .windows import * else: from .posix import * class shell_list(list): """A special subclass of list used to mark that this command line uses special shell characters.""" pass def execute(args, shell=False, env=None, quiet=False): stderr = None if quiet: stderr = open(os.devnull, 'wb') try: return subprocess.check_output( args, universal_newlines=True, shell=shell, env=env, stderr=stderr ) except: if quiet: stderr.close() raise
Fix "quiet" mode for shell.execute()
Fix "quiet" mode for shell.execute()
Python
bsd-3-clause
jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000
import os import subprocess from ..platform_name import platform_name if platform_name() == 'windows': from .windows import * else: from .posix import * class shell_list(list): """A special subclass of list used to mark that this command line uses special shell characters.""" pass def execute(args, shell=False, env=None, quiet=False): + stderr = None if quiet: - devnull = open(os.devnull, 'wb') + stderr = open(os.devnull, 'wb') try: return subprocess.check_output( - args, universal_newlines=True, shell=shell, env=env + args, universal_newlines=True, shell=shell, env=env, stderr=stderr ) except: if quiet: - devnull.close() + stderr.close() raise
Fix "quiet" mode for shell.execute()
## Code Before: import os import subprocess from ..platform_name import platform_name if platform_name() == 'windows': from .windows import * else: from .posix import * class shell_list(list): """A special subclass of list used to mark that this command line uses special shell characters.""" pass def execute(args, shell=False, env=None, quiet=False): if quiet: devnull = open(os.devnull, 'wb') try: return subprocess.check_output( args, universal_newlines=True, shell=shell, env=env ) except: if quiet: devnull.close() raise ## Instruction: Fix "quiet" mode for shell.execute() ## Code After: import os import subprocess from ..platform_name import platform_name if platform_name() == 'windows': from .windows import * else: from .posix import * class shell_list(list): """A special subclass of list used to mark that this command line uses special shell characters.""" pass def execute(args, shell=False, env=None, quiet=False): stderr = None if quiet: stderr = open(os.devnull, 'wb') try: return subprocess.check_output( args, universal_newlines=True, shell=shell, env=env, stderr=stderr ) except: if quiet: stderr.close() raise
// ... existing code ... def execute(args, shell=False, env=None, quiet=False): stderr = None if quiet: stderr = open(os.devnull, 'wb') try: // ... modified code ... return subprocess.check_output( args, universal_newlines=True, shell=shell, env=env, stderr=stderr ) ... if quiet: stderr.close() raise // ... rest of the code ...
70efd2427caf52a5ba45e05eb33dc47fce2147c6
redwind/tasks.py
redwind/tasks.py
from contextlib import contextmanager from flask import current_app from redis import StrictRedis import rq _queue = None def get_queue(): global _queue if _queue is None: _queue = create_queue() return _queue def create_queue(): """Connect to Redis and create the RQ. Since this is not imported directly, it is a convenient place to mock for tests that don't care about the queue. """ redis = StrictRedis( host=current_app.config.get('REDIS_HOST','localhost'), port=current_app.config.get('REDIS_PORT',6379), password=current_app.config.get('REDIS_PASSWORD',None) ) return rq.Queue('redwind:low', connection=redis) @contextmanager def async_app_context(app_config): from redwind import create_app app = create_app(app_config) with app.app_context(): yield
from contextlib import contextmanager from redis import StrictRedis import rq _queue = None def get_queue(): global _queue if _queue is None: _queue = create_queue() return _queue def create_queue(): """Connect to Redis and create the RQ. Since this is not imported directly, it is a convenient place to mock for tests that don't care about the queue. """ redis = StrictRedis() return rq.Queue('redwind:low', connection=redis) @contextmanager def async_app_context(app_config): from redwind import create_app app = create_app(app_config) with app.app_context(): yield
Revert "Added configuration options for Redis"
Revert "Added configuration options for Redis" This reverts commit 80129aac1fb4471e7a519b8f86df2db0b978903a.
Python
bsd-2-clause
Lancey6/redwind,Lancey6/redwind,Lancey6/redwind
from contextlib import contextmanager - from flask import current_app from redis import StrictRedis import rq _queue = None def get_queue(): global _queue if _queue is None: _queue = create_queue() return _queue def create_queue(): """Connect to Redis and create the RQ. Since this is not imported directly, it is a convenient place to mock for tests that don't care about the queue. """ - redis = StrictRedis( + redis = StrictRedis() - host=current_app.config.get('REDIS_HOST','localhost'), - port=current_app.config.get('REDIS_PORT',6379), - password=current_app.config.get('REDIS_PASSWORD',None) - ) return rq.Queue('redwind:low', connection=redis) @contextmanager def async_app_context(app_config): from redwind import create_app app = create_app(app_config) with app.app_context(): yield
Revert "Added configuration options for Redis"
## Code Before: from contextlib import contextmanager from flask import current_app from redis import StrictRedis import rq _queue = None def get_queue(): global _queue if _queue is None: _queue = create_queue() return _queue def create_queue(): """Connect to Redis and create the RQ. Since this is not imported directly, it is a convenient place to mock for tests that don't care about the queue. """ redis = StrictRedis( host=current_app.config.get('REDIS_HOST','localhost'), port=current_app.config.get('REDIS_PORT',6379), password=current_app.config.get('REDIS_PASSWORD',None) ) return rq.Queue('redwind:low', connection=redis) @contextmanager def async_app_context(app_config): from redwind import create_app app = create_app(app_config) with app.app_context(): yield ## Instruction: Revert "Added configuration options for Redis" ## Code After: from contextlib import contextmanager from redis import StrictRedis import rq _queue = None def get_queue(): global _queue if _queue is None: _queue = create_queue() return _queue def create_queue(): """Connect to Redis and create the RQ. Since this is not imported directly, it is a convenient place to mock for tests that don't care about the queue. """ redis = StrictRedis() return rq.Queue('redwind:low', connection=redis) @contextmanager def async_app_context(app_config): from redwind import create_app app = create_app(app_config) with app.app_context(): yield
# ... existing code ... from contextlib import contextmanager from redis import StrictRedis # ... modified code ... """ redis = StrictRedis() return rq.Queue('redwind:low', connection=redis) # ... rest of the code ...
5957999c52f939691cbe6b8dd5aa929980a24501
tests/unit/test_start.py
tests/unit/test_start.py
import pytest from iwant_bot import start def test_add(): assert start.add_numbers(0, 0) == 0 assert start.add_numbers(1, 1) == 2
from iwant_bot import start def test_add(): assert start.add_numbers(0, 0) == 0 assert start.add_numbers(1, 1) == 2
Remove the unused pytest import
Remove the unused pytest import
Python
mit
kiwicom/iwant-bot
- import pytest - - from iwant_bot import start def test_add(): assert start.add_numbers(0, 0) == 0 assert start.add_numbers(1, 1) == 2
Remove the unused pytest import
## Code Before: import pytest from iwant_bot import start def test_add(): assert start.add_numbers(0, 0) == 0 assert start.add_numbers(1, 1) == 2 ## Instruction: Remove the unused pytest import ## Code After: from iwant_bot import start def test_add(): assert start.add_numbers(0, 0) == 0 assert start.add_numbers(1, 1) == 2
... from iwant_bot import start ...
140e75fb3d96de3784c4ccc7272bbfa0e6b67d39
pinax/invitations/__init__.py
pinax/invitations/__init__.py
import pkg_resources __version__ = pkg_resources.get_distribution("pinax-invitations").version
import pkg_resources __version__ = pkg_resources.get_distribution("pinax-invitations").version default_app_config = "pinax.invitations.apps.AppConfig"
Set default_app_config to point to the correct AppConfig
Set default_app_config to point to the correct AppConfig
Python
unknown
pinax/pinax-invitations,jacobwegner/pinax-invitations,eldarion/kaleo,rizumu/pinax-invitations
import pkg_resources __version__ = pkg_resources.get_distribution("pinax-invitations").version + default_app_config = "pinax.invitations.apps.AppConfig"
Set default_app_config to point to the correct AppConfig
## Code Before: import pkg_resources __version__ = pkg_resources.get_distribution("pinax-invitations").version ## Instruction: Set default_app_config to point to the correct AppConfig ## Code After: import pkg_resources __version__ = pkg_resources.get_distribution("pinax-invitations").version default_app_config = "pinax.invitations.apps.AppConfig"
# ... existing code ... __version__ = pkg_resources.get_distribution("pinax-invitations").version default_app_config = "pinax.invitations.apps.AppConfig" # ... rest of the code ...
7f13b29cc918f63c4d1fc24717c0a0b5d2f5f8ad
filter.py
filter.py
import numpy as np class LowPassFilter(object): ''' First order discrete IIR filter. ''' def __init__(self, feedback_gain, initial_value=0.0): self.feedback_gain = np.ones_like(initial_value) * feedback_gain self.initial_value = initial_value self.output_gain = 1.0 - feedback_gain self.input = np.nan self.output = initial_value self.feedback_value = initial_value / self.output_gain def filter(self, value): #if not math.isanan(value) and math.isinf(value): self.input = value self.feedback_value = value + self.feedback_gain * self.feedback_value self.output = self.output_gain * self.feedback_value return self.output class MovingAverage(object): ''' Moving average filter. ''' def __init__(self, lifetime, sampling_time): self.lifetime = lifetime self.sampling_time = sampling_time self.exp = np.exp(-sampling_time / lifetime) self.last_value = np.nan self.mean_value = np.nan def filter(self, value): self.last_value = value if np.isnan(self.mean_value): self.mean_value = value else: self.mean_value = value + self.exp * (self.mean_value - value) return self.mean_value
import numpy as np class LowPassFilter(object): ''' First order discrete IIR filter. ''' def __init__(self, feedback_gain, initial_value=0.0): self.feedback_gain = np.ones_like(initial_value) * feedback_gain self.initial_value = initial_value self.output_gain = 1.0 - feedback_gain self.input = np.nan self.output = initial_value self.feedback_value = initial_value / self.output_gain def filter(self, value): #if not math.isanan(value) and math.isinf(value): self.input = value self.feedback_value = value + self.feedback_gain * self.feedback_value self.output = self.output_gain * self.feedback_value return self.output class MovingAverage(object): ''' Moving average filter. ''' def __init__(self, lifetime, sampling_time): self.lifetime = lifetime self.sampling_time = sampling_time self.exp = np.exp(-sampling_time / lifetime) self.last_value = None self.mean_value = None def filter(self, value): self.last_value = value if self.mean_value is None: self.mean_value = value else: self.mean_value = value + self.exp * (self.mean_value - value) return self.mean_value
Fix problem with array values.
Fix problem with array values.
Python
mit
jcsharp/DriveIt
import numpy as np class LowPassFilter(object): ''' First order discrete IIR filter. ''' def __init__(self, feedback_gain, initial_value=0.0): self.feedback_gain = np.ones_like(initial_value) * feedback_gain self.initial_value = initial_value self.output_gain = 1.0 - feedback_gain self.input = np.nan self.output = initial_value self.feedback_value = initial_value / self.output_gain def filter(self, value): #if not math.isanan(value) and math.isinf(value): self.input = value self.feedback_value = value + self.feedback_gain * self.feedback_value self.output = self.output_gain * self.feedback_value return self.output class MovingAverage(object): ''' Moving average filter. ''' def __init__(self, lifetime, sampling_time): self.lifetime = lifetime self.sampling_time = sampling_time self.exp = np.exp(-sampling_time / lifetime) - self.last_value = np.nan + self.last_value = None - self.mean_value = np.nan + self.mean_value = None def filter(self, value): self.last_value = value - if np.isnan(self.mean_value): + if self.mean_value is None: self.mean_value = value else: self.mean_value = value + self.exp * (self.mean_value - value) return self.mean_value
Fix problem with array values.
## Code Before: import numpy as np class LowPassFilter(object): ''' First order discrete IIR filter. ''' def __init__(self, feedback_gain, initial_value=0.0): self.feedback_gain = np.ones_like(initial_value) * feedback_gain self.initial_value = initial_value self.output_gain = 1.0 - feedback_gain self.input = np.nan self.output = initial_value self.feedback_value = initial_value / self.output_gain def filter(self, value): #if not math.isanan(value) and math.isinf(value): self.input = value self.feedback_value = value + self.feedback_gain * self.feedback_value self.output = self.output_gain * self.feedback_value return self.output class MovingAverage(object): ''' Moving average filter. ''' def __init__(self, lifetime, sampling_time): self.lifetime = lifetime self.sampling_time = sampling_time self.exp = np.exp(-sampling_time / lifetime) self.last_value = np.nan self.mean_value = np.nan def filter(self, value): self.last_value = value if np.isnan(self.mean_value): self.mean_value = value else: self.mean_value = value + self.exp * (self.mean_value - value) return self.mean_value ## Instruction: Fix problem with array values. ## Code After: import numpy as np class LowPassFilter(object): ''' First order discrete IIR filter. ''' def __init__(self, feedback_gain, initial_value=0.0): self.feedback_gain = np.ones_like(initial_value) * feedback_gain self.initial_value = initial_value self.output_gain = 1.0 - feedback_gain self.input = np.nan self.output = initial_value self.feedback_value = initial_value / self.output_gain def filter(self, value): #if not math.isanan(value) and math.isinf(value): self.input = value self.feedback_value = value + self.feedback_gain * self.feedback_value self.output = self.output_gain * self.feedback_value return self.output class MovingAverage(object): ''' Moving average filter. ''' def __init__(self, lifetime, sampling_time): self.lifetime = lifetime self.sampling_time = sampling_time self.exp = np.exp(-sampling_time / lifetime) self.last_value = None self.mean_value = None def filter(self, value): self.last_value = value if self.mean_value is None: self.mean_value = value else: self.mean_value = value + self.exp * (self.mean_value - value) return self.mean_value
... self.exp = np.exp(-sampling_time / lifetime) self.last_value = None self.mean_value = None ... self.last_value = value if self.mean_value is None: self.mean_value = value ...
18261acd87a2e9c6735d9081eff50e2a09277605
src/pyshark/config.py
src/pyshark/config.py
from pathlib import Path from configparser import ConfigParser import pyshark fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini' def get_config(): if Path.exists(fp_config_path): config_path = fp_config_path elif Path.exists(pyshark_config_path): config_path = pyshark_config_path else: return None config = ConfigParser() config.read(config_path) return config
from pathlib import Path from configparser import ConfigParser import pyshark fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini' def get_config(): if fp_config_path.exists(): config_path = fp_config_path elif pyshark_config_path.exists(): config_path = pyshark_config_path else: return None config = ConfigParser() config.read(config_path) return config
Use `x_path.exists()` instead of `Path.exists(x)`.
Use `x_path.exists()` instead of `Path.exists(x)`.
Python
mit
KimiNewt/pyshark
from pathlib import Path from configparser import ConfigParser import pyshark fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini' def get_config(): - if Path.exists(fp_config_path): + if fp_config_path.exists(): config_path = fp_config_path - elif Path.exists(pyshark_config_path): + elif pyshark_config_path.exists(): config_path = pyshark_config_path else: return None config = ConfigParser() config.read(config_path) return config
Use `x_path.exists()` instead of `Path.exists(x)`.
## Code Before: from pathlib import Path from configparser import ConfigParser import pyshark fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini' def get_config(): if Path.exists(fp_config_path): config_path = fp_config_path elif Path.exists(pyshark_config_path): config_path = pyshark_config_path else: return None config = ConfigParser() config.read(config_path) return config ## Instruction: Use `x_path.exists()` instead of `Path.exists(x)`. ## Code After: from pathlib import Path from configparser import ConfigParser import pyshark fp_config_path = Path.cwd() / 'config.ini' # get config from the current directory pyshark_config_path = Path(pyshark.__file__).parent / 'config.ini' def get_config(): if fp_config_path.exists(): config_path = fp_config_path elif pyshark_config_path.exists(): config_path = pyshark_config_path else: return None config = ConfigParser() config.read(config_path) return config
... def get_config(): if fp_config_path.exists(): config_path = fp_config_path elif pyshark_config_path.exists(): config_path = pyshark_config_path ...
20a92ff1ffe143193d95235c7a5ea8e9edb0df64
yowsup/layers/protocol_acks/protocolentities/ack_outgoing.py
yowsup/layers/protocol_acks/protocolentities/ack_outgoing.py
from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .ack import AckProtocolEntity class OutgoingAckProtocolEntity(AckProtocolEntity): ''' <ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}"> </ack> ''' def __init__(self, _id, _class, _type, _to): super(OutgoingAckProtocolEntity, self).__init__(_id, _class) self.setOutgoingData(_type, _to) def setOutgoingData(self, _type, _to): self._type = _type self._to = _to def toProtocolTreeNode(self): node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode() if self._type: node.setAttribute("type", self._type) node.setAttribute("to", self._to) return node def __str__(self): out = super(OutgoingAckProtocolEntity, self).__str__() out += "Type: %s\n" % self._type out += "To: %s\n" % self._to return out @staticmethod def fromProtocolTreeNode(node): entity = AckProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = OutgoingAckProtocolEntity entity.setOutgoingData( node.getAttributeValue("type"), node.getAttributeValue("to") ) return entity
from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .ack import AckProtocolEntity class OutgoingAckProtocolEntity(AckProtocolEntity): ''' <ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}"> </ack> <ack to="{{GROUP_JID}}" participant="{{JID}}" id="{{MESSAGE_ID}}" class="receipt" type="{{read | }}"> </ack> ''' def __init__(self, _id, _class, _type, _to, _participant = None): super(OutgoingAckProtocolEntity, self).__init__(_id, _class) self.setOutgoingData(_type, _to, _participant) def setOutgoingData(self, _type, _to, _participant): self._type = _type self._to = _to self._participant = _participant def toProtocolTreeNode(self): node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode() if self._type: node.setAttribute("type", self._type) node.setAttribute("to", self._to) if self._participant: node.setAttribute("participant", self._participant) return node def __str__(self): out = super(OutgoingAckProtocolEntity, self).__str__() out += "Type: %s\n" % self._type out += "To: %s\n" % self._to if self._participant: out += "Participant: %s\n" % self._participant return out @staticmethod def fromProtocolTreeNode(node): entity = AckProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = OutgoingAckProtocolEntity entity.setOutgoingData( node.getAttributeValue("type"), node.getAttributeValue("to"), node.getAttributeValue("participant") ) return entity
Include participant in outgoing ack
Include participant in outgoing ack
Python
mit
ongair/yowsup,biji/yowsup
from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .ack import AckProtocolEntity class OutgoingAckProtocolEntity(AckProtocolEntity): ''' <ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}"> </ack> + + <ack to="{{GROUP_JID}}" participant="{{JID}}" id="{{MESSAGE_ID}}" class="receipt" type="{{read | }}"> + </ack> + ''' - def __init__(self, _id, _class, _type, _to): + def __init__(self, _id, _class, _type, _to, _participant = None): super(OutgoingAckProtocolEntity, self).__init__(_id, _class) - self.setOutgoingData(_type, _to) + self.setOutgoingData(_type, _to, _participant) - def setOutgoingData(self, _type, _to): + def setOutgoingData(self, _type, _to, _participant): self._type = _type self._to = _to + self._participant = _participant def toProtocolTreeNode(self): node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode() if self._type: node.setAttribute("type", self._type) node.setAttribute("to", self._to) + if self._participant: + node.setAttribute("participant", self._participant) return node def __str__(self): out = super(OutgoingAckProtocolEntity, self).__str__() out += "Type: %s\n" % self._type out += "To: %s\n" % self._to + if self._participant: + out += "Participant: %s\n" % self._participant return out @staticmethod def fromProtocolTreeNode(node): entity = AckProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = OutgoingAckProtocolEntity entity.setOutgoingData( node.getAttributeValue("type"), - node.getAttributeValue("to") + node.getAttributeValue("to"), + node.getAttributeValue("participant") ) return entity
Include participant in outgoing ack
## Code Before: from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .ack import AckProtocolEntity class OutgoingAckProtocolEntity(AckProtocolEntity): ''' <ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}"> </ack> ''' def __init__(self, _id, _class, _type, _to): super(OutgoingAckProtocolEntity, self).__init__(_id, _class) self.setOutgoingData(_type, _to) def setOutgoingData(self, _type, _to): self._type = _type self._to = _to def toProtocolTreeNode(self): node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode() if self._type: node.setAttribute("type", self._type) node.setAttribute("to", self._to) return node def __str__(self): out = super(OutgoingAckProtocolEntity, self).__str__() out += "Type: %s\n" % self._type out += "To: %s\n" % self._to return out @staticmethod def fromProtocolTreeNode(node): entity = AckProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = OutgoingAckProtocolEntity entity.setOutgoingData( node.getAttributeValue("type"), node.getAttributeValue("to") ) return entity ## Instruction: Include participant in outgoing ack ## Code After: from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .ack import AckProtocolEntity class OutgoingAckProtocolEntity(AckProtocolEntity): ''' <ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}"> </ack> <ack to="{{GROUP_JID}}" participant="{{JID}}" id="{{MESSAGE_ID}}" class="receipt" type="{{read | }}"> </ack> ''' def __init__(self, _id, _class, _type, _to, _participant = None): super(OutgoingAckProtocolEntity, self).__init__(_id, _class) self.setOutgoingData(_type, _to, _participant) def setOutgoingData(self, _type, _to, _participant): self._type = _type self._to = _to self._participant = _participant def toProtocolTreeNode(self): node = super(OutgoingAckProtocolEntity, self).toProtocolTreeNode() if self._type: node.setAttribute("type", self._type) node.setAttribute("to", self._to) if self._participant: node.setAttribute("participant", self._participant) return node def __str__(self): out = super(OutgoingAckProtocolEntity, self).__str__() out += "Type: %s\n" % self._type out += "To: %s\n" % self._to if self._participant: out += "Participant: %s\n" % self._participant return out @staticmethod def fromProtocolTreeNode(node): entity = AckProtocolEntity.fromProtocolTreeNode(node) entity.__class__ = OutgoingAckProtocolEntity entity.setOutgoingData( node.getAttributeValue("type"), node.getAttributeValue("to"), node.getAttributeValue("participant") ) return entity
# ... existing code ... </ack> <ack to="{{GROUP_JID}}" participant="{{JID}}" id="{{MESSAGE_ID}}" class="receipt" type="{{read | }}"> </ack> ''' # ... modified code ... def __init__(self, _id, _class, _type, _to, _participant = None): super(OutgoingAckProtocolEntity, self).__init__(_id, _class) self.setOutgoingData(_type, _to, _participant) def setOutgoingData(self, _type, _to, _participant): self._type = _type ... self._to = _to self._participant = _participant ... node.setAttribute("to", self._to) if self._participant: node.setAttribute("participant", self._participant) return node ... out += "To: %s\n" % self._to if self._participant: out += "Participant: %s\n" % self._participant return out ... node.getAttributeValue("type"), node.getAttributeValue("to"), node.getAttributeValue("participant") ) # ... rest of the code ...
6091fccc90bb6b90c47a2e4fb7ee6821876eb1a1
synthnotes/generators/lengthgenerator.py
synthnotes/generators/lengthgenerator.py
from pkg_resources import resource_filename import pandas as pd import numpy as np class LengthGenerator(object): def __init__(self, length_file=resource_filename(__name__, 'resources/note_lengths.csv')): # print(length_file) df = pd.read_csv(length_file) notes_count = df['count'].sum() df['probability'] = df['count'] / notes_count self.note_lengths = df['note_length'].as_matrix() self.p = df['probability'].as_matrix() def generate(self, size=1): return np.random.choice(self.note_lengths, size=size, p=self.p)
from pkg_resources import resource_filename import pandas as pd import numpy as np class LengthGenerator(object): def __init__(self, length_file=resource_filename('synthnotes.resources', 'note_lengths.csv')): # print(length_file) df = pd.read_csv(length_file) notes_count = df['count'].sum() df['probability'] = df['count'] / notes_count self.note_lengths = df['note_length'].as_matrix() self.p = df['probability'].as_matrix() def generate(self, size=1): return np.random.choice(self.note_lengths, size=size, p=self.p)
Change LengthGenerator to get appropriate file path
Change LengthGenerator to get appropriate file path
Python
mit
ebegoli/SynthNotes
from pkg_resources import resource_filename import pandas as pd import numpy as np class LengthGenerator(object): def __init__(self, - length_file=resource_filename(__name__, + length_file=resource_filename('synthnotes.resources', - 'resources/note_lengths.csv')): + 'note_lengths.csv')): # print(length_file) df = pd.read_csv(length_file) notes_count = df['count'].sum() df['probability'] = df['count'] / notes_count self.note_lengths = df['note_length'].as_matrix() self.p = df['probability'].as_matrix() def generate(self, size=1): return np.random.choice(self.note_lengths, size=size, p=self.p)
Change LengthGenerator to get appropriate file path
## Code Before: from pkg_resources import resource_filename import pandas as pd import numpy as np class LengthGenerator(object): def __init__(self, length_file=resource_filename(__name__, 'resources/note_lengths.csv')): # print(length_file) df = pd.read_csv(length_file) notes_count = df['count'].sum() df['probability'] = df['count'] / notes_count self.note_lengths = df['note_length'].as_matrix() self.p = df['probability'].as_matrix() def generate(self, size=1): return np.random.choice(self.note_lengths, size=size, p=self.p) ## Instruction: Change LengthGenerator to get appropriate file path ## Code After: from pkg_resources import resource_filename import pandas as pd import numpy as np class LengthGenerator(object): def __init__(self, length_file=resource_filename('synthnotes.resources', 'note_lengths.csv')): # print(length_file) df = pd.read_csv(length_file) notes_count = df['count'].sum() df['probability'] = df['count'] / notes_count self.note_lengths = df['note_length'].as_matrix() self.p = df['probability'].as_matrix() def generate(self, size=1): return np.random.choice(self.note_lengths, size=size, p=self.p)
... def __init__(self, length_file=resource_filename('synthnotes.resources', 'note_lengths.csv')): # print(length_file) ...
ce5e322367a15198bdbea9d32401b8c779d0e4bf
config.py
config.py
import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name
import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] def get(self, attrname, fallback=None): try: return self.config[attrname] except KeyError: return fallback # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name
Add Config.get() to skip KeyErrors
Add Config.get() to skip KeyErrors Adds common `dict.get()` pattern to our own Config class, to enable use of fallbacks or `None`, as appropriate.
Python
apache-2.0
rossrader/destalinator
import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] + def get(self, attrname, fallback=None): + try: + return self.config[attrname] + except KeyError: + return fallback + # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name
Add Config.get() to skip KeyErrors
## Code Before: import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name ## Instruction: Add Config.get() to skip KeyErrors ## Code After: import os import warnings import yaml class Config(object): config_fname = "configuration.yaml" def __init__(self, config_fname=None): config_fname = config_fname or self.config_fname fo = open(config_fname, "r") blob = fo.read() fo.close() self.config = yaml.load(blob) def __getattr__(self, attrname): if attrname == "slack_name": warnings.warn("The `slack_name` key in %s is deprecated in favor of the `SLACK_NAME` environment variable" % self.config_fname, DeprecationWarning) return self.config[attrname] def get(self, attrname, fallback=None): try: return self.config[attrname] except KeyError: return fallback # This deliberately isn't a `getenv` default so `.slack_name` isn't tried if there's a SLACK_NAME SLACK_NAME = os.getenv("SLACK_NAME") if SLACK_NAME is None: SLACK_NAME = Config().slack_name
... def get(self, attrname, fallback=None): try: return self.config[attrname] except KeyError: return fallback ...
90a265c9c673856a6f119ab04bbd5d57ab375dc6
django_fsm_log/models.py
django_fsm_log/models.py
from __future__ import unicode_literals from django.conf import settings from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django_fsm.signals import post_transition from .managers import StateLogManager class StateLog(models.Model): timestamp = models.DateTimeField(auto_now_add=True) by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True) state = models.CharField(max_length=255, db_index=True) transition = models.CharField(max_length=255) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey('content_type', 'object_id') objects = StateLogManager() def transition_callback(sender, instance, name, source, target, **kwargs): state_log = StateLog( by=getattr(instance, 'by', None), state=target, transition=name, content_object=instance, ) state_log.save() post_transition.connect(transition_callback)
from __future__ import unicode_literals from django.conf import settings from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.timezone import now from django_fsm.signals import post_transition from .managers import StateLogManager class StateLog(models.Model): timestamp = models.DateTimeField(default=now) by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True) state = models.CharField(max_length=255, db_index=True) transition = models.CharField(max_length=255) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey('content_type', 'object_id') objects = StateLogManager() def transition_callback(sender, instance, name, source, target, **kwargs): state_log = StateLog( by=getattr(instance, 'by', None), state=target, transition=name, content_object=instance, ) state_log.save() post_transition.connect(transition_callback)
Switch from auto_now_add=True to default=now
Switch from auto_now_add=True to default=now This allows for optional direct setting of the timestamp, eg when loading fixtures.
Python
mit
ticosax/django-fsm-log,blueyed/django-fsm-log,Andrey86/django-fsm-log,gizmag/django-fsm-log,fjcapdevila/django-fsm-log,mord4z/django-fsm-log,pombredanne/django-fsm-log
from __future__ import unicode_literals from django.conf import settings from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models + from django.utils.timezone import now from django_fsm.signals import post_transition from .managers import StateLogManager class StateLog(models.Model): - timestamp = models.DateTimeField(auto_now_add=True) + timestamp = models.DateTimeField(default=now) by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True) state = models.CharField(max_length=255, db_index=True) transition = models.CharField(max_length=255) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey('content_type', 'object_id') objects = StateLogManager() def transition_callback(sender, instance, name, source, target, **kwargs): state_log = StateLog( by=getattr(instance, 'by', None), state=target, transition=name, content_object=instance, ) state_log.save() post_transition.connect(transition_callback)
Switch from auto_now_add=True to default=now
## Code Before: from __future__ import unicode_literals from django.conf import settings from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django_fsm.signals import post_transition from .managers import StateLogManager class StateLog(models.Model): timestamp = models.DateTimeField(auto_now_add=True) by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True) state = models.CharField(max_length=255, db_index=True) transition = models.CharField(max_length=255) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey('content_type', 'object_id') objects = StateLogManager() def transition_callback(sender, instance, name, source, target, **kwargs): state_log = StateLog( by=getattr(instance, 'by', None), state=target, transition=name, content_object=instance, ) state_log.save() post_transition.connect(transition_callback) ## Instruction: Switch from auto_now_add=True to default=now ## Code After: from __future__ import unicode_literals from django.conf import settings from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.timezone import now from django_fsm.signals import post_transition from .managers import StateLogManager class StateLog(models.Model): timestamp = models.DateTimeField(default=now) by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True) state = models.CharField(max_length=255, db_index=True) transition = models.CharField(max_length=255) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey('content_type', 'object_id') objects = StateLogManager() def transition_callback(sender, instance, name, source, target, **kwargs): state_log = StateLog( by=getattr(instance, 'by', None), state=target, transition=name, content_object=instance, ) state_log.save() post_transition.connect(transition_callback)
# ... existing code ... from django.db import models from django.utils.timezone import now # ... modified code ... class StateLog(models.Model): timestamp = models.DateTimeField(default=now) by = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), blank=True, null=True) # ... rest of the code ...
ef102617e5d73b32c43e4e9422a19917a1d3d717
molo/polls/wagtail_hooks.py
molo/polls/wagtail_hooks.py
from django.conf.urls import url from molo.polls.admin import QuestionsModelAdmin from molo.polls.admin_views import QuestionResultsAdminView from wagtail.wagtailcore import hooks from wagtail.contrib.modeladmin.options import modeladmin_register from django.contrib.auth.models import User @hooks.register('register_admin_urls') def register_question_results_admin_view_url(): return [ url(r'polls/question/(?P<parent>\d+)/results/$', QuestionResultsAdminView.as_view(), name='question-results-admin'), ] modeladmin_register(QuestionsModelAdmin) @hooks.register('construct_main_menu') def show_polls_entries_for_users_have_access(request, menu_items): if not request.user.is_superuser and not User.objects.filter( pk=request.user.pk, groups__name='Moderators').exists(): menu_items[:] = [ item for item in menu_items if item.name != 'polls']
from django.conf.urls import url from molo.polls.admin import QuestionsModelAdmin from molo.polls.admin_views import QuestionResultsAdminView from wagtail.wagtailcore import hooks from wagtail.contrib.modeladmin.options import modeladmin_register from django.contrib.auth.models import User @hooks.register('register_admin_urls') def register_question_results_admin_view_url(): return [ url(r'polls/question/(?P<parent>\d+)/results/$', QuestionResultsAdminView.as_view(), name='question-results-admin'), ] modeladmin_register(QuestionsModelAdmin) @hooks.register('construct_main_menu') def show_polls_entries_for_users_have_access(request, menu_items): if not request.user.is_superuser and not User.objects.filter( pk=request.user.pk, groups__name='Moderators').exists()\ and not User.objects.filter( pk=request.user.pk, groups__name='M&E Expert').exists(): menu_items[:] = [ item for item in menu_items if item.name != 'polls']
Add M&E Expert to polls entries permissions
Add M&E Expert to polls entries permissions
Python
bsd-2-clause
praekelt/molo.polls,praekelt/molo.polls
from django.conf.urls import url from molo.polls.admin import QuestionsModelAdmin from molo.polls.admin_views import QuestionResultsAdminView from wagtail.wagtailcore import hooks from wagtail.contrib.modeladmin.options import modeladmin_register from django.contrib.auth.models import User @hooks.register('register_admin_urls') def register_question_results_admin_view_url(): return [ url(r'polls/question/(?P<parent>\d+)/results/$', QuestionResultsAdminView.as_view(), name='question-results-admin'), ] modeladmin_register(QuestionsModelAdmin) @hooks.register('construct_main_menu') def show_polls_entries_for_users_have_access(request, menu_items): if not request.user.is_superuser and not User.objects.filter( - pk=request.user.pk, groups__name='Moderators').exists(): + pk=request.user.pk, groups__name='Moderators').exists()\ + and not User.objects.filter( + pk=request.user.pk, groups__name='M&E Expert').exists(): menu_items[:] = [ item for item in menu_items if item.name != 'polls']
Add M&E Expert to polls entries permissions
## Code Before: from django.conf.urls import url from molo.polls.admin import QuestionsModelAdmin from molo.polls.admin_views import QuestionResultsAdminView from wagtail.wagtailcore import hooks from wagtail.contrib.modeladmin.options import modeladmin_register from django.contrib.auth.models import User @hooks.register('register_admin_urls') def register_question_results_admin_view_url(): return [ url(r'polls/question/(?P<parent>\d+)/results/$', QuestionResultsAdminView.as_view(), name='question-results-admin'), ] modeladmin_register(QuestionsModelAdmin) @hooks.register('construct_main_menu') def show_polls_entries_for_users_have_access(request, menu_items): if not request.user.is_superuser and not User.objects.filter( pk=request.user.pk, groups__name='Moderators').exists(): menu_items[:] = [ item for item in menu_items if item.name != 'polls'] ## Instruction: Add M&E Expert to polls entries permissions ## Code After: from django.conf.urls import url from molo.polls.admin import QuestionsModelAdmin from molo.polls.admin_views import QuestionResultsAdminView from wagtail.wagtailcore import hooks from wagtail.contrib.modeladmin.options import modeladmin_register from django.contrib.auth.models import User @hooks.register('register_admin_urls') def register_question_results_admin_view_url(): return [ url(r'polls/question/(?P<parent>\d+)/results/$', QuestionResultsAdminView.as_view(), name='question-results-admin'), ] modeladmin_register(QuestionsModelAdmin) @hooks.register('construct_main_menu') def show_polls_entries_for_users_have_access(request, menu_items): if not request.user.is_superuser and not User.objects.filter( pk=request.user.pk, groups__name='Moderators').exists()\ and not User.objects.filter( pk=request.user.pk, groups__name='M&E Expert').exists(): menu_items[:] = [ item for item in menu_items if item.name != 'polls']
// ... existing code ... if not request.user.is_superuser and not User.objects.filter( pk=request.user.pk, groups__name='Moderators').exists()\ and not User.objects.filter( pk=request.user.pk, groups__name='M&E Expert').exists(): menu_items[:] = [ // ... rest of the code ...
10ef76977e724cff86361db07a7fcb844d8376e7
scrapi/util.py
scrapi/util.py
from datetime import datetime import pytz def timestamp(): return pytz.utc.localize(datetime.utcnow()).isoformat().decode('utf-8') def copy_to_unicode(element): """ used to transform the lxml version of unicode to a standard version of unicode that can be pickalable - necessary for linting """ if isinstance(element, dict): for key, val in element.items(): element[key] = copy_to_unicode(val) elif isinstance(element, list): for idx, item in enumerate(element): element[idx] = copy_to_unicode(item) else: try: # A dirty way to convert to unicode in python 2 + 3.3+ element = u''.join(element) except TypeError: pass return element def stamp_from_raw(raw_doc, **kwargs): kwargs['normalizeFinished'] = timestamp() stamps = raw_doc['timestamps'] stamps.update(kwargs) return stamps def format_date_with_slashes(date): return date.strftime('%m/%d/%Y')
from datetime import datetime import pytz def timestamp(): return pytz.utc.localize(datetime.utcnow()).isoformat().decode('utf-8') def copy_to_unicode(element): """ used to transform the lxml version of unicode to a standard version of unicode that can be pickalable - necessary for linting """ if isinstance(element, dict): for key, val in element.items(): element[key] = copy_to_unicode(val) elif isinstance(element, list): for idx, item in enumerate(element): element[idx] = copy_to_unicode(item) else: try: # A dirty way to convert to unicode in python 2 + 3.3+ element = u''.join(element) except TypeError: pass return element def stamp_from_raw(raw_doc, **kwargs): kwargs['normalizeFinished'] = timestamp() stamps = raw_doc['timestamps'] stamps.update(kwargs) return stamps def format_date_with_slashes(date): return date.strftime('%m/%d/%Y') def create_rename_iterable(documents, source, target, dry): return [(doc, source, target, dry) for doc in documents]
Add scrapi create rename iterable if we want to move to chunks in the fuure
Add scrapi create rename iterable if we want to move to chunks in the fuure
Python
apache-2.0
mehanig/scrapi,fabianvf/scrapi,fabianvf/scrapi,jeffreyliu3230/scrapi,erinspace/scrapi,felliott/scrapi,alexgarciac/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,icereval/scrapi,mehanig/scrapi,erinspace/scrapi,ostwald/scrapi
from datetime import datetime import pytz def timestamp(): return pytz.utc.localize(datetime.utcnow()).isoformat().decode('utf-8') def copy_to_unicode(element): """ used to transform the lxml version of unicode to a standard version of unicode that can be pickalable - necessary for linting """ if isinstance(element, dict): for key, val in element.items(): element[key] = copy_to_unicode(val) elif isinstance(element, list): for idx, item in enumerate(element): element[idx] = copy_to_unicode(item) else: try: # A dirty way to convert to unicode in python 2 + 3.3+ element = u''.join(element) except TypeError: pass return element def stamp_from_raw(raw_doc, **kwargs): kwargs['normalizeFinished'] = timestamp() stamps = raw_doc['timestamps'] stamps.update(kwargs) return stamps def format_date_with_slashes(date): return date.strftime('%m/%d/%Y') + + def create_rename_iterable(documents, source, target, dry): + return [(doc, source, target, dry) for doc in documents] +
Add scrapi create rename iterable if we want to move to chunks in the fuure
## Code Before: from datetime import datetime import pytz def timestamp(): return pytz.utc.localize(datetime.utcnow()).isoformat().decode('utf-8') def copy_to_unicode(element): """ used to transform the lxml version of unicode to a standard version of unicode that can be pickalable - necessary for linting """ if isinstance(element, dict): for key, val in element.items(): element[key] = copy_to_unicode(val) elif isinstance(element, list): for idx, item in enumerate(element): element[idx] = copy_to_unicode(item) else: try: # A dirty way to convert to unicode in python 2 + 3.3+ element = u''.join(element) except TypeError: pass return element def stamp_from_raw(raw_doc, **kwargs): kwargs['normalizeFinished'] = timestamp() stamps = raw_doc['timestamps'] stamps.update(kwargs) return stamps def format_date_with_slashes(date): return date.strftime('%m/%d/%Y') ## Instruction: Add scrapi create rename iterable if we want to move to chunks in the fuure ## Code After: from datetime import datetime import pytz def timestamp(): return pytz.utc.localize(datetime.utcnow()).isoformat().decode('utf-8') def copy_to_unicode(element): """ used to transform the lxml version of unicode to a standard version of unicode that can be pickalable - necessary for linting """ if isinstance(element, dict): for key, val in element.items(): element[key] = copy_to_unicode(val) elif isinstance(element, list): for idx, item in enumerate(element): element[idx] = copy_to_unicode(item) else: try: # A dirty way to convert to unicode in python 2 + 3.3+ element = u''.join(element) except TypeError: pass return element def stamp_from_raw(raw_doc, **kwargs): kwargs['normalizeFinished'] = timestamp() stamps = raw_doc['timestamps'] stamps.update(kwargs) return stamps def format_date_with_slashes(date): return date.strftime('%m/%d/%Y') def create_rename_iterable(documents, source, target, dry): return [(doc, source, target, dry) for doc in documents]
... return date.strftime('%m/%d/%Y') def create_rename_iterable(documents, source, target, dry): return [(doc, source, target, dry) for doc in documents] ...
c0b76d401b305c1bcd2ed5814a89719d4c6a3d83
heat_cfnclient/tests/test_cli.py
heat_cfnclient/tests/test_cli.py
import testtools import heat_cfnclient import os import subprocess basepath = os.path.join(heat_cfnclient.__path__[0], os.path.pardir) class CliTest(testtools.TestCase): def test_heat_cfn(self): self.bin_run('heat-cfn') def test_heat_boto(self): self.bin_run('heat-boto') def test_heat_watch(self): self.bin_run('heat-watch') def bin_run(self, bin): fullpath = basepath + '/bin/' + bin proc = subprocess.Popen(fullpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() if proc.returncode: print('Error executing %s:\n %s %s ' % (bin, stdout, stderr)) raise subprocess.CalledProcessError(proc.returncode, bin)
import testtools import heat_cfnclient import os import subprocess basepath = os.path.join(heat_cfnclient.__path__[0], os.path.pardir) @testtools.skip class CliTest(testtools.TestCase): def test_heat_cfn(self): self.bin_run('heat-cfn') def test_heat_boto(self): self.bin_run('heat-boto') def test_heat_watch(self): self.bin_run('heat-watch') def bin_run(self, bin): fullpath = basepath + '/bin/' + bin proc = subprocess.Popen(fullpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() if proc.returncode: print('Error executing %s:\n %s %s ' % (bin, stdout, stderr)) raise subprocess.CalledProcessError(proc.returncode, bin)
Disable tests until new repo is stable
Disable tests until new repo is stable Change-Id: Ic6932c1028c72b5600d03ab59102d1c1cff1b36c
Python
apache-2.0
openstack-dev/heat-cfnclient
import testtools import heat_cfnclient import os import subprocess basepath = os.path.join(heat_cfnclient.__path__[0], os.path.pardir) + @testtools.skip class CliTest(testtools.TestCase): def test_heat_cfn(self): self.bin_run('heat-cfn') def test_heat_boto(self): self.bin_run('heat-boto') def test_heat_watch(self): self.bin_run('heat-watch') def bin_run(self, bin): fullpath = basepath + '/bin/' + bin proc = subprocess.Popen(fullpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() if proc.returncode: print('Error executing %s:\n %s %s ' % (bin, stdout, stderr)) raise subprocess.CalledProcessError(proc.returncode, bin)
Disable tests until new repo is stable
## Code Before: import testtools import heat_cfnclient import os import subprocess basepath = os.path.join(heat_cfnclient.__path__[0], os.path.pardir) class CliTest(testtools.TestCase): def test_heat_cfn(self): self.bin_run('heat-cfn') def test_heat_boto(self): self.bin_run('heat-boto') def test_heat_watch(self): self.bin_run('heat-watch') def bin_run(self, bin): fullpath = basepath + '/bin/' + bin proc = subprocess.Popen(fullpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() if proc.returncode: print('Error executing %s:\n %s %s ' % (bin, stdout, stderr)) raise subprocess.CalledProcessError(proc.returncode, bin) ## Instruction: Disable tests until new repo is stable ## Code After: import testtools import heat_cfnclient import os import subprocess basepath = os.path.join(heat_cfnclient.__path__[0], os.path.pardir) @testtools.skip class CliTest(testtools.TestCase): def test_heat_cfn(self): self.bin_run('heat-cfn') def test_heat_boto(self): self.bin_run('heat-boto') def test_heat_watch(self): self.bin_run('heat-watch') def bin_run(self, bin): fullpath = basepath + '/bin/' + bin proc = subprocess.Popen(fullpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() if proc.returncode: print('Error executing %s:\n %s %s ' % (bin, stdout, stderr)) raise subprocess.CalledProcessError(proc.returncode, bin)
// ... existing code ... @testtools.skip class CliTest(testtools.TestCase): // ... rest of the code ...
855434523df57183c31ed9b10e7458232b79046a
aclarknet/aclarknet/aclarknet/models.py
aclarknet/aclarknet/aclarknet/models.py
from django.db import models class Client(models.Model): client_name = models.CharField(max_length=60) class Service(models.Model): name = models.CharField(max_length=60) class TeamMember(models.Model): name = models.CharField(max_length=60)
from django.db import models class Client(models.Model): client_name = models.CharField(max_length=60) def __unicode__(self): return self.client_name class Service(models.Model): name = models.CharField(max_length=60) def __unicode__(self): return self.name class TeamMember(models.Model): name = models.CharField(max_length=60) def __unicode__(self): return self.name
Fix object name in Django Admin
Fix object name in Django Admin http://stackoverflow.com/questions/9336463/django-xxxxxx-object-display-customization-in-admin-action-sidebar
Python
mit
ACLARKNET/aclarknet-django,ACLARKNET/aclarknet-django
from django.db import models class Client(models.Model): client_name = models.CharField(max_length=60) + def __unicode__(self): + return self.client_name + class Service(models.Model): name = models.CharField(max_length=60) + + def __unicode__(self): + return self.name class TeamMember(models.Model): name = models.CharField(max_length=60) + def __unicode__(self): + return self.name +
Fix object name in Django Admin
## Code Before: from django.db import models class Client(models.Model): client_name = models.CharField(max_length=60) class Service(models.Model): name = models.CharField(max_length=60) class TeamMember(models.Model): name = models.CharField(max_length=60) ## Instruction: Fix object name in Django Admin ## Code After: from django.db import models class Client(models.Model): client_name = models.CharField(max_length=60) def __unicode__(self): return self.client_name class Service(models.Model): name = models.CharField(max_length=60) def __unicode__(self): return self.name class TeamMember(models.Model): name = models.CharField(max_length=60) def __unicode__(self): return self.name
# ... existing code ... def __unicode__(self): return self.client_name # ... modified code ... def __unicode__(self): return self.name ... name = models.CharField(max_length=60) def __unicode__(self): return self.name # ... rest of the code ...
84a2f2f019216ec96121159365ef4ca66f5d4e25
corehq/util/couch.py
corehq/util/couch.py
from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if (unwrapped.get('domain', domain) != domain or domain not in unwrapped.get('domains', [domain]) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404()
from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if ((unwrapped.get('domain', None) != domain and domain not in unwrapped.get('domains', [])) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404()
Handle doc without domain or domains
Handle doc without domain or domains
Python
bsd-3-clause
qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() - if (unwrapped.get('domain', domain) != domain or + if ((unwrapped.get('domain', None) != domain and - domain not in unwrapped.get('domains', [domain]) or + domain not in unwrapped.get('domains', [])) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404()
Handle doc without domain or domains
## Code Before: from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if (unwrapped.get('domain', domain) != domain or domain not in unwrapped.get('domains', [domain]) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404() ## Instruction: Handle doc without domain or domains ## Code After: from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if ((unwrapped.get('domain', None) != domain and domain not in unwrapped.get('domains', [])) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404()
# ... existing code ... if ((unwrapped.get('domain', None) != domain and domain not in unwrapped.get('domains', [])) or unwrapped['doc_type'] not in allowed_doc_types): # ... rest of the code ...
40a63fd8ca5dd574e729b9f531664ce384aa404c
app/schedule/tasks.py
app/schedule/tasks.py
from datetime import datetime from importlib import import_module import pytz from django.conf import settings from app.schedule.celery import celery_app from app.schedule.libs.sms import DeviceNotFoundError @celery_app.task(bind=True) def send_message(self, to, message, sg_user, sg_password): def load_sms_class(): module_name, class_name = settings.APP_MESSENGER_CLASS.rsplit(".", 1) return getattr(import_module(module_name), class_name) sms_class = load_sms_class() try: messenger = sms_class(sg_user, sg_password) messenger.send_message(to, message) except DeviceNotFoundError as e: # Workaround for Celery issue. Remove after next version is released. tz = pytz.timezone(settings.TIME_ZONE) self.request.expires = tz.localize(datetime.strptime(self.request.expires[:-6], '%Y-%m-%dT%H:%M:%S')) self.retry(exc=e, max_retries=50)
from datetime import datetime from importlib import import_module import pytz from django.conf import settings from app.schedule.celery import celery_app from app.schedule.libs.sms import DeviceNotFoundError @celery_app.task(bind=True) def send_message(self, to, message, sg_user, sg_password): def load_sms_class(): module_name, class_name = settings.APP_MESSENGER_CLASS.rsplit(".", 1) return getattr(import_module(module_name), class_name) sms_class = load_sms_class() try: messenger = sms_class(sg_user, sg_password) messenger.send_message(to, message) except DeviceNotFoundError as e: # Workaround for Celery issue. Remove after next version is released. tz = pytz.timezone(settings.TIME_ZONE) self.request.expires = tz.localize(datetime.strptime(self.request.expires[:-6], '%Y-%m-%dT%H:%M:%S')) self.retry(exc=e, max_retries=2000, countdown=60 * 5)
Increase retry count and add countdown to retry method
Increase retry count and add countdown to retry method
Python
agpl-3.0
agendaodonto/server,agendaodonto/server
from datetime import datetime from importlib import import_module import pytz from django.conf import settings from app.schedule.celery import celery_app from app.schedule.libs.sms import DeviceNotFoundError @celery_app.task(bind=True) def send_message(self, to, message, sg_user, sg_password): def load_sms_class(): module_name, class_name = settings.APP_MESSENGER_CLASS.rsplit(".", 1) return getattr(import_module(module_name), class_name) sms_class = load_sms_class() try: messenger = sms_class(sg_user, sg_password) messenger.send_message(to, message) except DeviceNotFoundError as e: # Workaround for Celery issue. Remove after next version is released. tz = pytz.timezone(settings.TIME_ZONE) self.request.expires = tz.localize(datetime.strptime(self.request.expires[:-6], '%Y-%m-%dT%H:%M:%S')) - self.retry(exc=e, max_retries=50) + self.retry(exc=e, max_retries=2000, countdown=60 * 5)
Increase retry count and add countdown to retry method
## Code Before: from datetime import datetime from importlib import import_module import pytz from django.conf import settings from app.schedule.celery import celery_app from app.schedule.libs.sms import DeviceNotFoundError @celery_app.task(bind=True) def send_message(self, to, message, sg_user, sg_password): def load_sms_class(): module_name, class_name = settings.APP_MESSENGER_CLASS.rsplit(".", 1) return getattr(import_module(module_name), class_name) sms_class = load_sms_class() try: messenger = sms_class(sg_user, sg_password) messenger.send_message(to, message) except DeviceNotFoundError as e: # Workaround for Celery issue. Remove after next version is released. tz = pytz.timezone(settings.TIME_ZONE) self.request.expires = tz.localize(datetime.strptime(self.request.expires[:-6], '%Y-%m-%dT%H:%M:%S')) self.retry(exc=e, max_retries=50) ## Instruction: Increase retry count and add countdown to retry method ## Code After: from datetime import datetime from importlib import import_module import pytz from django.conf import settings from app.schedule.celery import celery_app from app.schedule.libs.sms import DeviceNotFoundError @celery_app.task(bind=True) def send_message(self, to, message, sg_user, sg_password): def load_sms_class(): module_name, class_name = settings.APP_MESSENGER_CLASS.rsplit(".", 1) return getattr(import_module(module_name), class_name) sms_class = load_sms_class() try: messenger = sms_class(sg_user, sg_password) messenger.send_message(to, message) except DeviceNotFoundError as e: # Workaround for Celery issue. Remove after next version is released. tz = pytz.timezone(settings.TIME_ZONE) self.request.expires = tz.localize(datetime.strptime(self.request.expires[:-6], '%Y-%m-%dT%H:%M:%S')) self.retry(exc=e, max_retries=2000, countdown=60 * 5)
// ... existing code ... self.request.expires = tz.localize(datetime.strptime(self.request.expires[:-6], '%Y-%m-%dT%H:%M:%S')) self.retry(exc=e, max_retries=2000, countdown=60 * 5) // ... rest of the code ...
d99dfc16e7c14896a703da7868f26a710b3bc6f1
14B-088/HI/analysis/galaxy_params.py
14B-088/HI/analysis/galaxy_params.py
''' Use parameters from Diskfit in the Galaxy class ''' from astropy import units as u from galaxies import Galaxy from astropy.table import Table from paths import fourteenB_HI_data_path def update_galaxy_params(gal, param_table): ''' Use the fit values from fit rather than the hard-coded values in galaxies. ''' from astropy.coordinates import Angle, SkyCoord gal.inclination = Angle(param_table["inc"] * u.deg)[0] gal.position_angle = Angle(param_table["PA"] * u.deg)[0] gal.vsys = (param_table["Vsys"] * u.km / u.s)[0] # The positions in the table are in pixels, so convert to the sky using # the spatial WCS info. ra_cent, dec_cent = param_table["RAcent"], param_table["Deccent"] gal.center_position = SkyCoord(ra_cent, dec_cent, unit=(u.deg, u.deg), frame='fk5') folder_name = "diskfit_noasymm_noradial_nowarp_output" param_name = \ fourteenB_HI_data_path("{}/rad.out.params.csv".format(folder_name)) param_table = Table.read(param_name) gal = Galaxy("M33") update_galaxy_params(gal, param_table)
''' Use parameters from Diskfit in the Galaxy class ''' from galaxies import Galaxy from astropy.table import Table from cube_analysis.rotation_curves import update_galaxy_params from paths import fourteenB_HI_data_path, fourteenB_HI_data_wGBT_path # The models from the peak velocity aren't as biased, based on comparing # the VLA and VLA+GBT velocity curves. Using these as the defaults folder_name = "diskfit_peakvels_noasymm_noradial_nowarp_output" param_name = \ fourteenB_HI_data_path("{}/rad.out.params.csv".format(folder_name)) param_table = Table.read(param_name) gal = Galaxy("M33") update_galaxy_params(gal, param_table) # Load in the model from the feathered data as well. folder_name = "diskfit_peakvels_noasymm_noradial_nowarp_output" param_name = \ fourteenB_HI_data_wGBT_path("{}/rad.out.params.csv".format(folder_name)) param_table = Table.read(param_name) gal_feath = Galaxy("M33") update_galaxy_params(gal_feath, param_table)
Update galaxy params w/ new model choices
Update galaxy params w/ new model choices
Python
mit
e-koch/VLA_Lband,e-koch/VLA_Lband
''' Use parameters from Diskfit in the Galaxy class ''' - from astropy import units as u from galaxies import Galaxy from astropy.table import Table - from paths import fourteenB_HI_data_path + from cube_analysis.rotation_curves import update_galaxy_params + from paths import fourteenB_HI_data_path, fourteenB_HI_data_wGBT_path + # The models from the peak velocity aren't as biased, based on comparing + # the VLA and VLA+GBT velocity curves. Using these as the defaults - def update_galaxy_params(gal, param_table): - ''' - Use the fit values from fit rather than the hard-coded values in galaxies. - ''' - from astropy.coordinates import Angle, SkyCoord - - gal.inclination = Angle(param_table["inc"] * u.deg)[0] - gal.position_angle = Angle(param_table["PA"] * u.deg)[0] - gal.vsys = (param_table["Vsys"] * u.km / u.s)[0] - - # The positions in the table are in pixels, so convert to the sky using - # the spatial WCS info. - ra_cent, dec_cent = param_table["RAcent"], param_table["Deccent"] - - gal.center_position = SkyCoord(ra_cent, dec_cent, unit=(u.deg, u.deg), - frame='fk5') - - - folder_name = "diskfit_noasymm_noradial_nowarp_output" + folder_name = "diskfit_peakvels_noasymm_noradial_nowarp_output" param_name = \ fourteenB_HI_data_path("{}/rad.out.params.csv".format(folder_name)) param_table = Table.read(param_name) gal = Galaxy("M33") update_galaxy_params(gal, param_table) + # Load in the model from the feathered data as well. + folder_name = "diskfit_peakvels_noasymm_noradial_nowarp_output" + + param_name = \ + fourteenB_HI_data_wGBT_path("{}/rad.out.params.csv".format(folder_name)) + + param_table = Table.read(param_name) + + gal_feath = Galaxy("M33") + + update_galaxy_params(gal_feath, param_table) +
Update galaxy params w/ new model choices
## Code Before: ''' Use parameters from Diskfit in the Galaxy class ''' from astropy import units as u from galaxies import Galaxy from astropy.table import Table from paths import fourteenB_HI_data_path def update_galaxy_params(gal, param_table): ''' Use the fit values from fit rather than the hard-coded values in galaxies. ''' from astropy.coordinates import Angle, SkyCoord gal.inclination = Angle(param_table["inc"] * u.deg)[0] gal.position_angle = Angle(param_table["PA"] * u.deg)[0] gal.vsys = (param_table["Vsys"] * u.km / u.s)[0] # The positions in the table are in pixels, so convert to the sky using # the spatial WCS info. ra_cent, dec_cent = param_table["RAcent"], param_table["Deccent"] gal.center_position = SkyCoord(ra_cent, dec_cent, unit=(u.deg, u.deg), frame='fk5') folder_name = "diskfit_noasymm_noradial_nowarp_output" param_name = \ fourteenB_HI_data_path("{}/rad.out.params.csv".format(folder_name)) param_table = Table.read(param_name) gal = Galaxy("M33") update_galaxy_params(gal, param_table) ## Instruction: Update galaxy params w/ new model choices ## Code After: ''' Use parameters from Diskfit in the Galaxy class ''' from galaxies import Galaxy from astropy.table import Table from cube_analysis.rotation_curves import update_galaxy_params from paths import fourteenB_HI_data_path, fourteenB_HI_data_wGBT_path # The models from the peak velocity aren't as biased, based on comparing # the VLA and VLA+GBT velocity curves. Using these as the defaults folder_name = "diskfit_peakvels_noasymm_noradial_nowarp_output" param_name = \ fourteenB_HI_data_path("{}/rad.out.params.csv".format(folder_name)) param_table = Table.read(param_name) gal = Galaxy("M33") update_galaxy_params(gal, param_table) # Load in the model from the feathered data as well. folder_name = "diskfit_peakvels_noasymm_noradial_nowarp_output" param_name = \ fourteenB_HI_data_wGBT_path("{}/rad.out.params.csv".format(folder_name)) param_table = Table.read(param_name) gal_feath = Galaxy("M33") update_galaxy_params(gal_feath, param_table)
... from galaxies import Galaxy ... from cube_analysis.rotation_curves import update_galaxy_params from paths import fourteenB_HI_data_path, fourteenB_HI_data_wGBT_path # The models from the peak velocity aren't as biased, based on comparing # the VLA and VLA+GBT velocity curves. Using these as the defaults folder_name = "diskfit_peakvels_noasymm_noradial_nowarp_output" ... update_galaxy_params(gal, param_table) # Load in the model from the feathered data as well. folder_name = "diskfit_peakvels_noasymm_noradial_nowarp_output" param_name = \ fourteenB_HI_data_wGBT_path("{}/rad.out.params.csv".format(folder_name)) param_table = Table.read(param_name) gal_feath = Galaxy("M33") update_galaxy_params(gal_feath, param_table) ...
81d9558c5d75671349228b8cde84d7049289d3df
troposphere/settings/__init__.py
troposphere/settings/__init__.py
from troposphere.settings.default import * from troposphere.settings.local import *
from troposphere.settings.default import * try: from troposphere.settings.local import * except ImportError: raise Exception("No local settings module found. Refer to README.md")
Add exception for people who dont read the docs
Add exception for people who dont read the docs
Python
apache-2.0
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
from troposphere.settings.default import * + try: - from troposphere.settings.local import * + from troposphere.settings.local import * + except ImportError: + raise Exception("No local settings module found. Refer to README.md")
Add exception for people who dont read the docs
## Code Before: from troposphere.settings.default import * from troposphere.settings.local import * ## Instruction: Add exception for people who dont read the docs ## Code After: from troposphere.settings.default import * try: from troposphere.settings.local import * except ImportError: raise Exception("No local settings module found. Refer to README.md")
... from troposphere.settings.default import * try: from troposphere.settings.local import * except ImportError: raise Exception("No local settings module found. Refer to README.md") ...
41c6a71e2a9e013966df06e3b5f458aa9a902bc8
tests/test_core.py
tests/test_core.py
import pytest from mock import Mock from saleor.core.utils import ( Country, get_country_by_ip, get_currency_for_country) @pytest.mark.parametrize('ip_data, expected_country', [ ({'country': {'iso_code': 'PL'}}, Country('PL')), ({'country': {'iso_code': 'UNKNOWN'}}, None), (None, None), ({}, None), ({'country': {}}, None)]) def test_get_country_by_ip(ip_data, expected_country, monkeypatch): monkeypatch.setattr( 'saleor.core.utils.georeader.get', Mock(return_value=ip_data)) country = get_country_by_ip('127.0.0.1') assert country == expected_country @pytest.mark.parametrize('country, expected_currency', [ (Country('PL'), 'PLN'), (Country('US'), 'USD'), (Country('GB'), 'GBP')]) def test_get_currency_for_country(country, expected_currency, monkeypatch): currency = get_currency_for_country(country) assert currency == expected_currency
import pytest from mock import Mock from saleor.core.utils import ( Country, get_country_by_ip, get_currency_for_country, create_superuser) from saleor.userprofile.models import User @pytest.mark.parametrize('ip_data, expected_country', [ ({'country': {'iso_code': 'PL'}}, Country('PL')), ({'country': {'iso_code': 'UNKNOWN'}}, None), (None, None), ({}, None), ({'country': {}}, None)]) def test_get_country_by_ip(ip_data, expected_country, monkeypatch): monkeypatch.setattr( 'saleor.core.utils.georeader.get', Mock(return_value=ip_data)) country = get_country_by_ip('127.0.0.1') assert country == expected_country @pytest.mark.parametrize('country, expected_currency', [ (Country('PL'), 'PLN'), (Country('US'), 'USD'), (Country('GB'), 'GBP')]) def test_get_currency_for_country(country, expected_currency, monkeypatch): currency = get_currency_for_country(country) assert currency == expected_currency def test_create_superuser(db, client): credentials = {'email': '[email protected]', 'password': 'admin'} # Test admin creation assert User.objects.all().count() == 0 create_superuser(credentials) assert User.objects.all().count() == 1 admin = User.objects.all().first() assert admin.is_superuser # Test duplicating create_superuser(credentials) assert User.objects.all().count() == 1 # Test logging in response = client.post('/account/login/', {'login': credentials['email'], 'password': credentials['password']}, follow=True) assert response.context['request'].user == admin
Add populatedb admin creation test
Add populatedb admin creation test
Python
bsd-3-clause
car3oon/saleor,mociepka/saleor,jreigel/saleor,mociepka/saleor,tfroehlich82/saleor,maferelo/saleor,itbabu/saleor,itbabu/saleor,HyperManTT/ECommerceSaleor,KenMutemi/saleor,UITools/saleor,tfroehlich82/saleor,KenMutemi/saleor,maferelo/saleor,maferelo/saleor,UITools/saleor,mociepka/saleor,jreigel/saleor,jreigel/saleor,UITools/saleor,UITools/saleor,car3oon/saleor,HyperManTT/ECommerceSaleor,KenMutemi/saleor,itbabu/saleor,car3oon/saleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,UITools/saleor
import pytest from mock import Mock from saleor.core.utils import ( - Country, get_country_by_ip, get_currency_for_country) + Country, get_country_by_ip, get_currency_for_country, create_superuser) + from saleor.userprofile.models import User @pytest.mark.parametrize('ip_data, expected_country', [ ({'country': {'iso_code': 'PL'}}, Country('PL')), ({'country': {'iso_code': 'UNKNOWN'}}, None), (None, None), ({}, None), ({'country': {}}, None)]) def test_get_country_by_ip(ip_data, expected_country, monkeypatch): monkeypatch.setattr( 'saleor.core.utils.georeader.get', Mock(return_value=ip_data)) country = get_country_by_ip('127.0.0.1') assert country == expected_country @pytest.mark.parametrize('country, expected_currency', [ (Country('PL'), 'PLN'), (Country('US'), 'USD'), (Country('GB'), 'GBP')]) def test_get_currency_for_country(country, expected_currency, monkeypatch): currency = get_currency_for_country(country) assert currency == expected_currency + + def test_create_superuser(db, client): + credentials = {'email': '[email protected]', 'password': 'admin'} + # Test admin creation + assert User.objects.all().count() == 0 + create_superuser(credentials) + assert User.objects.all().count() == 1 + admin = User.objects.all().first() + assert admin.is_superuser + # Test duplicating + create_superuser(credentials) + assert User.objects.all().count() == 1 + # Test logging in + response = client.post('/account/login/', + {'login': credentials['email'], + 'password': credentials['password']}, + follow=True) + assert response.context['request'].user == admin +
Add populatedb admin creation test
## Code Before: import pytest from mock import Mock from saleor.core.utils import ( Country, get_country_by_ip, get_currency_for_country) @pytest.mark.parametrize('ip_data, expected_country', [ ({'country': {'iso_code': 'PL'}}, Country('PL')), ({'country': {'iso_code': 'UNKNOWN'}}, None), (None, None), ({}, None), ({'country': {}}, None)]) def test_get_country_by_ip(ip_data, expected_country, monkeypatch): monkeypatch.setattr( 'saleor.core.utils.georeader.get', Mock(return_value=ip_data)) country = get_country_by_ip('127.0.0.1') assert country == expected_country @pytest.mark.parametrize('country, expected_currency', [ (Country('PL'), 'PLN'), (Country('US'), 'USD'), (Country('GB'), 'GBP')]) def test_get_currency_for_country(country, expected_currency, monkeypatch): currency = get_currency_for_country(country) assert currency == expected_currency ## Instruction: Add populatedb admin creation test ## Code After: import pytest from mock import Mock from saleor.core.utils import ( Country, get_country_by_ip, get_currency_for_country, create_superuser) from saleor.userprofile.models import User @pytest.mark.parametrize('ip_data, expected_country', [ ({'country': {'iso_code': 'PL'}}, Country('PL')), ({'country': {'iso_code': 'UNKNOWN'}}, None), (None, None), ({}, None), ({'country': {}}, None)]) def test_get_country_by_ip(ip_data, expected_country, monkeypatch): monkeypatch.setattr( 'saleor.core.utils.georeader.get', Mock(return_value=ip_data)) country = get_country_by_ip('127.0.0.1') assert country == expected_country @pytest.mark.parametrize('country, expected_currency', [ (Country('PL'), 'PLN'), (Country('US'), 'USD'), (Country('GB'), 'GBP')]) def test_get_currency_for_country(country, expected_currency, monkeypatch): currency = get_currency_for_country(country) assert currency == expected_currency def test_create_superuser(db, client): credentials = {'email': '[email protected]', 'password': 'admin'} # Test admin creation assert User.objects.all().count() == 0 create_superuser(credentials) assert User.objects.all().count() == 1 admin = User.objects.all().first() assert admin.is_superuser # Test duplicating create_superuser(credentials) assert User.objects.all().count() == 1 # Test logging in response = client.post('/account/login/', {'login': credentials['email'], 'password': credentials['password']}, follow=True) assert response.context['request'].user == admin
# ... existing code ... from saleor.core.utils import ( Country, get_country_by_ip, get_currency_for_country, create_superuser) from saleor.userprofile.models import User # ... modified code ... assert currency == expected_currency def test_create_superuser(db, client): credentials = {'email': '[email protected]', 'password': 'admin'} # Test admin creation assert User.objects.all().count() == 0 create_superuser(credentials) assert User.objects.all().count() == 1 admin = User.objects.all().first() assert admin.is_superuser # Test duplicating create_superuser(credentials) assert User.objects.all().count() == 1 # Test logging in response = client.post('/account/login/', {'login': credentials['email'], 'password': credentials['password']}, follow=True) assert response.context['request'].user == admin # ... rest of the code ...
638e9761a6a42a8ab9d8eb7996b0a19d394ad3ea
precision/accounts/urls.py
precision/accounts/urls.py
from django.conf.urls import url from django.contrib.auth.views import login, logout, logout_then_login from .views import SignInView urlpatterns = [ # Authentication # ============== url( regex=r'^login/$', view=login, name='login' ), url( regex=r'^logout/$', view=logout, name='logout' ), url( regex=r'^logout-then-login/$', view=logout_then_login, name='logout_then_login' ), ]
from django.conf.urls import url from django.contrib.auth.views import login, logout, logout_then_login, password_change, password_change_done from .views import SignInView urlpatterns = [ # Authentication # ============== url( regex=r'^login/$', view=login, name='login' ), url( regex=r'^logout/$', view=logout, name='logout' ), # Password Change # =============== url( regex=r'^logout-then-login/$', view=logout_then_login, name='logout_then_login' ), url( regex=r'^password-change/$', view=password_change, name='password_change' ), url( regex=r'^password-change/done/$', view=password_change_done, name='password_change_done' ), ]
Add password change url patterns
Add password change url patterns
Python
mit
FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management
from django.conf.urls import url - from django.contrib.auth.views import login, logout, logout_then_login + from django.contrib.auth.views import login, logout, logout_then_login, password_change, password_change_done from .views import SignInView urlpatterns = [ # Authentication # ============== url( regex=r'^login/$', view=login, name='login' ), url( regex=r'^logout/$', view=logout, name='logout' ), + # Password Change + # =============== url( regex=r'^logout-then-login/$', view=logout_then_login, name='logout_then_login' ), + + url( + regex=r'^password-change/$', + view=password_change, + name='password_change' + ), + + url( + regex=r'^password-change/done/$', + view=password_change_done, + name='password_change_done' + ), ]
Add password change url patterns
## Code Before: from django.conf.urls import url from django.contrib.auth.views import login, logout, logout_then_login from .views import SignInView urlpatterns = [ # Authentication # ============== url( regex=r'^login/$', view=login, name='login' ), url( regex=r'^logout/$', view=logout, name='logout' ), url( regex=r'^logout-then-login/$', view=logout_then_login, name='logout_then_login' ), ] ## Instruction: Add password change url patterns ## Code After: from django.conf.urls import url from django.contrib.auth.views import login, logout, logout_then_login, password_change, password_change_done from .views import SignInView urlpatterns = [ # Authentication # ============== url( regex=r'^login/$', view=login, name='login' ), url( regex=r'^logout/$', view=logout, name='logout' ), # Password Change # =============== url( regex=r'^logout-then-login/$', view=logout_then_login, name='logout_then_login' ), url( regex=r'^password-change/$', view=password_change, name='password_change' ), url( regex=r'^password-change/done/$', view=password_change_done, name='password_change_done' ), ]
# ... existing code ... from django.conf.urls import url from django.contrib.auth.views import login, logout, logout_then_login, password_change, password_change_done from .views import SignInView # ... modified code ... # Password Change # =============== url( ... ), url( regex=r'^password-change/$', view=password_change, name='password_change' ), url( regex=r'^password-change/done/$', view=password_change_done, name='password_change_done' ), ] # ... rest of the code ...
aa360309f387f19f6566d08325cd1aa1131768da
bulbs/utils/filters.py
bulbs/utils/filters.py
from rest_framework import filters class CaseInsensitiveBooleanFilter(filters.BaseFilterBackend): """Set a boolean_fields tuple on the viewset and set this class as a filter_backend to filter listed fields through a case-insensitive transformation to be used for filtering. i.e. query params such as 'true' become boolean True, and params with a value 'false' become boolean False.""" def filter_queryset(self, request, queryset, view): boolean_fields = getattr(view, 'boolean_fields', None) if not boolean_fields: return queryset boolean_filters = {} for field in boolean_fields: if field in request.QUERY_PARAMS: val = request.QUERY_PARAMS[field] if val in ['true', 'True']: boolean_filters[field] = True elif val in ['false', 'False']: boolean_filters[field] = False if len(boolean_filters) > 0: return queryset.filter(**boolean_filters) return queryset
from rest_framework import filters class CaseInsensitiveBooleanFilter(filters.BaseFilterBackend): """Set a boolean_fields tuple on the viewset and set this class as a filter_backend to filter listed fields through a case-insensitive transformation to be used for filtering. i.e. query params such as 'true' become boolean True, and params with a value 'false' become boolean False.""" def filter_queryset(self, request, queryset, view): boolean_fields = getattr(view, 'boolean_fields', None) if not boolean_fields: return queryset boolean_filters = {} for field in boolean_fields: if field in request.QUERY_PARAMS: val = request.QUERY_PARAMS[field].lower() if val == 'true': boolean_filters[field] = True elif val == 'false': boolean_filters[field] = False if len(boolean_filters) > 0: return queryset.filter(**boolean_filters) return queryset
Cover every case for CaseInsensitiveBooleanFilter
Cover every case for CaseInsensitiveBooleanFilter
Python
mit
pombredanne/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,pombredanne/django-bulbs
from rest_framework import filters class CaseInsensitiveBooleanFilter(filters.BaseFilterBackend): """Set a boolean_fields tuple on the viewset and set this class as a filter_backend to filter listed fields through a case-insensitive transformation to be used for filtering. i.e. query params such as 'true' become boolean True, and params with a value 'false' become boolean False.""" def filter_queryset(self, request, queryset, view): boolean_fields = getattr(view, 'boolean_fields', None) if not boolean_fields: return queryset boolean_filters = {} for field in boolean_fields: if field in request.QUERY_PARAMS: - val = request.QUERY_PARAMS[field] + val = request.QUERY_PARAMS[field].lower() - if val in ['true', 'True']: + if val == 'true': boolean_filters[field] = True - elif val in ['false', 'False']: + elif val == 'false': boolean_filters[field] = False if len(boolean_filters) > 0: return queryset.filter(**boolean_filters) return queryset
Cover every case for CaseInsensitiveBooleanFilter
## Code Before: from rest_framework import filters class CaseInsensitiveBooleanFilter(filters.BaseFilterBackend): """Set a boolean_fields tuple on the viewset and set this class as a filter_backend to filter listed fields through a case-insensitive transformation to be used for filtering. i.e. query params such as 'true' become boolean True, and params with a value 'false' become boolean False.""" def filter_queryset(self, request, queryset, view): boolean_fields = getattr(view, 'boolean_fields', None) if not boolean_fields: return queryset boolean_filters = {} for field in boolean_fields: if field in request.QUERY_PARAMS: val = request.QUERY_PARAMS[field] if val in ['true', 'True']: boolean_filters[field] = True elif val in ['false', 'False']: boolean_filters[field] = False if len(boolean_filters) > 0: return queryset.filter(**boolean_filters) return queryset ## Instruction: Cover every case for CaseInsensitiveBooleanFilter ## Code After: from rest_framework import filters class CaseInsensitiveBooleanFilter(filters.BaseFilterBackend): """Set a boolean_fields tuple on the viewset and set this class as a filter_backend to filter listed fields through a case-insensitive transformation to be used for filtering. i.e. query params such as 'true' become boolean True, and params with a value 'false' become boolean False.""" def filter_queryset(self, request, queryset, view): boolean_fields = getattr(view, 'boolean_fields', None) if not boolean_fields: return queryset boolean_filters = {} for field in boolean_fields: if field in request.QUERY_PARAMS: val = request.QUERY_PARAMS[field].lower() if val == 'true': boolean_filters[field] = True elif val == 'false': boolean_filters[field] = False if len(boolean_filters) > 0: return queryset.filter(**boolean_filters) return queryset
// ... existing code ... if field in request.QUERY_PARAMS: val = request.QUERY_PARAMS[field].lower() if val == 'true': boolean_filters[field] = True elif val == 'false': boolean_filters[field] = False // ... rest of the code ...
de731520f9ad3f871a976fd597ff1a4d8acf155f
tests/modules/test_enumerable.py
tests/modules/test_enumerable.py
class TestEnumberable(object): def test_inject(self, ec): w_res = ec.space.execute(ec, """ return (5..10).inject(1) do |prod, n| prod * n end """) assert ec.space.int_w(w_res) == 15120 w_res = ec.space.execute(ec, """ return (1..10).inject 0 do |sum, n| sum + n end """) assert ec.space.int_w(w_res) == 45 def test_each_with_index(self, ec): w_res = ec.space.execute(ec, """ result = [] (5..10).each_with_index do |n, idx| result << [n, idx] end return result """) assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]] def test_all(self, ec): w_res = ec.space.execute(ec, """ return ["ant", "bear", "cat"].all? do |word| word.length >= 3 end """) assert ec.space.w_true
class TestEnumberable(object): def test_inject(self, ec): w_res = ec.space.execute(ec, """ return (5..10).inject(1) do |prod, n| prod * n end """) assert ec.space.int_w(w_res) == 15120 w_res = ec.space.execute(ec, """ return (1..10).inject 0 do |sum, n| sum + n end """) assert ec.space.int_w(w_res) == 45 def test_each_with_index(self, ec): w_res = ec.space.execute(ec, """ result = [] (5..10).each_with_index do |n, idx| result << [n, idx] end return result """) assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]] def test_all(self, ec): w_res = ec.space.execute(ec, """ return ["ant", "bear", "cat"].all? do |word| word.length >= 3 end """) assert w_res is ec.space.w_true def test_all_false(self, ec): w_res = ec.space.execute(ec, """ return ["ant", "bear", "cat"].all? do |word| word.length >= 4 end """) assert w_res is ec.space.w_false
Fix true test, add false test
Fix true test, add false test
Python
bsd-3-clause
babelsberg/babelsberg-r,topazproject/topaz,topazproject/topaz,babelsberg/babelsberg-r,babelsberg/babelsberg-r,babelsberg/babelsberg-r,babelsberg/babelsberg-r,topazproject/topaz,kachick/topaz,kachick/topaz,topazproject/topaz,kachick/topaz
class TestEnumberable(object): def test_inject(self, ec): w_res = ec.space.execute(ec, """ return (5..10).inject(1) do |prod, n| prod * n end """) assert ec.space.int_w(w_res) == 15120 w_res = ec.space.execute(ec, """ return (1..10).inject 0 do |sum, n| sum + n end """) assert ec.space.int_w(w_res) == 45 def test_each_with_index(self, ec): w_res = ec.space.execute(ec, """ result = [] (5..10).each_with_index do |n, idx| result << [n, idx] end return result """) assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]] def test_all(self, ec): w_res = ec.space.execute(ec, """ return ["ant", "bear", "cat"].all? do |word| word.length >= 3 end """) - assert ec.space.w_true + assert w_res is ec.space.w_true + def test_all_false(self, ec): + w_res = ec.space.execute(ec, """ + return ["ant", "bear", "cat"].all? do |word| + word.length >= 4 + end + """) + assert w_res is ec.space.w_false +
Fix true test, add false test
## Code Before: class TestEnumberable(object): def test_inject(self, ec): w_res = ec.space.execute(ec, """ return (5..10).inject(1) do |prod, n| prod * n end """) assert ec.space.int_w(w_res) == 15120 w_res = ec.space.execute(ec, """ return (1..10).inject 0 do |sum, n| sum + n end """) assert ec.space.int_w(w_res) == 45 def test_each_with_index(self, ec): w_res = ec.space.execute(ec, """ result = [] (5..10).each_with_index do |n, idx| result << [n, idx] end return result """) assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]] def test_all(self, ec): w_res = ec.space.execute(ec, """ return ["ant", "bear", "cat"].all? do |word| word.length >= 3 end """) assert ec.space.w_true ## Instruction: Fix true test, add false test ## Code After: class TestEnumberable(object): def test_inject(self, ec): w_res = ec.space.execute(ec, """ return (5..10).inject(1) do |prod, n| prod * n end """) assert ec.space.int_w(w_res) == 15120 w_res = ec.space.execute(ec, """ return (1..10).inject 0 do |sum, n| sum + n end """) assert ec.space.int_w(w_res) == 45 def test_each_with_index(self, ec): w_res = ec.space.execute(ec, """ result = [] (5..10).each_with_index do |n, idx| result << [n, idx] end return result """) assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]] def test_all(self, ec): w_res = ec.space.execute(ec, """ return ["ant", "bear", "cat"].all? do |word| word.length >= 3 end """) assert w_res is ec.space.w_true def test_all_false(self, ec): w_res = ec.space.execute(ec, """ return ["ant", "bear", "cat"].all? do |word| word.length >= 4 end """) assert w_res is ec.space.w_false
// ... existing code ... """) assert w_res is ec.space.w_true def test_all_false(self, ec): w_res = ec.space.execute(ec, """ return ["ant", "bear", "cat"].all? do |word| word.length >= 4 end """) assert w_res is ec.space.w_false // ... rest of the code ...
57f2a438845cd0d7263da6ac66142d5403e41d98
examples/markdown/build.py
examples/markdown/build.py
import os # Markdown to HTML library # https://pypi.org/project/Markdown/ import markdown from staticjinja import Site markdowner = markdown.Markdown(output_format="html5") def md_context(template): with open(template.filename) as f: markdown_content = f.read() return {"post_content_html": markdowner.convert(markdown_content)} def render_md(site, template, **kwargs): # Given a template such as posts/post1.md # Determine the post's title (post1) and it's directory (posts/) directory, fname = os.path.split(template.name) post_title, _ = fname.split(".") # Determine where the result will be streamed (build/posts/post1.html) out_dir = os.path.join(site.outpath, directory) post_fname = "{}.html".format(post_title) out = os.path.join(out_dir, post_fname) # Render and stream the result if not os.path.exists(out_dir): os.makedirs(out_dir) post_template = site.get_template("_post.html") post_template.stream(**kwargs).dump(out, encoding="utf-8") site = Site.make_site( searchpath="src", outpath="build", contexts=[(r".*\.md", md_context)], rules=[(r".*\.md", render_md)], ) site.render()
import os from pathlib import Path import markdown from staticjinja import Site markdowner = markdown.Markdown(output_format="html5") def md_context(template): markdown_content = Path(template.filename).read_text() return {"post_content_html": markdowner.convert(markdown_content)} def render_md(site, template, **kwargs): # i.e. posts/post1.md -> build/posts/post1.html out = site.outpath / Path(template.name).with_suffix(".html") # Compile and stream the result os.makedirs(out.parent, exist_ok=True) site.get_template("_post.html").stream(**kwargs).dump(str(out), encoding="utf-8") site = Site.make_site( searchpath="src", outpath="build", contexts=[(r".*\.md", md_context)], rules=[(r".*\.md", render_md)], ) site.render()
Simplify markdown example using pathlib
example: Simplify markdown example using pathlib
Python
mit
Ceasar/staticjinja,Ceasar/staticjinja
import os + from pathlib import Path - # Markdown to HTML library - # https://pypi.org/project/Markdown/ import markdown from staticjinja import Site markdowner = markdown.Markdown(output_format="html5") def md_context(template): + markdown_content = Path(template.filename).read_text() - with open(template.filename) as f: - markdown_content = f.read() - return {"post_content_html": markdowner.convert(markdown_content)} + return {"post_content_html": markdowner.convert(markdown_content)} def render_md(site, template, **kwargs): + # i.e. posts/post1.md -> build/posts/post1.html + out = site.outpath / Path(template.name).with_suffix(".html") - # Given a template such as posts/post1.md - # Determine the post's title (post1) and it's directory (posts/) - directory, fname = os.path.split(template.name) - post_title, _ = fname.split(".") - # Determine where the result will be streamed (build/posts/post1.html) - out_dir = os.path.join(site.outpath, directory) - post_fname = "{}.html".format(post_title) - out = os.path.join(out_dir, post_fname) - - # Render and stream the result + # Compile and stream the result + os.makedirs(out.parent, exist_ok=True) - if not os.path.exists(out_dir): - os.makedirs(out_dir) - post_template = site.get_template("_post.html") - post_template.stream(**kwargs).dump(out, encoding="utf-8") + site.get_template("_post.html").stream(**kwargs).dump(str(out), encoding="utf-8") site = Site.make_site( searchpath="src", outpath="build", contexts=[(r".*\.md", md_context)], rules=[(r".*\.md", render_md)], ) site.render()
Simplify markdown example using pathlib
## Code Before: import os # Markdown to HTML library # https://pypi.org/project/Markdown/ import markdown from staticjinja import Site markdowner = markdown.Markdown(output_format="html5") def md_context(template): with open(template.filename) as f: markdown_content = f.read() return {"post_content_html": markdowner.convert(markdown_content)} def render_md(site, template, **kwargs): # Given a template such as posts/post1.md # Determine the post's title (post1) and it's directory (posts/) directory, fname = os.path.split(template.name) post_title, _ = fname.split(".") # Determine where the result will be streamed (build/posts/post1.html) out_dir = os.path.join(site.outpath, directory) post_fname = "{}.html".format(post_title) out = os.path.join(out_dir, post_fname) # Render and stream the result if not os.path.exists(out_dir): os.makedirs(out_dir) post_template = site.get_template("_post.html") post_template.stream(**kwargs).dump(out, encoding="utf-8") site = Site.make_site( searchpath="src", outpath="build", contexts=[(r".*\.md", md_context)], rules=[(r".*\.md", render_md)], ) site.render() ## Instruction: Simplify markdown example using pathlib ## Code After: import os from pathlib import Path import markdown from staticjinja import Site markdowner = markdown.Markdown(output_format="html5") def md_context(template): markdown_content = Path(template.filename).read_text() return {"post_content_html": markdowner.convert(markdown_content)} def render_md(site, template, **kwargs): # i.e. posts/post1.md -> build/posts/post1.html out = site.outpath / Path(template.name).with_suffix(".html") # Compile and stream the result os.makedirs(out.parent, exist_ok=True) site.get_template("_post.html").stream(**kwargs).dump(str(out), encoding="utf-8") site = Site.make_site( searchpath="src", outpath="build", contexts=[(r".*\.md", md_context)], rules=[(r".*\.md", render_md)], ) site.render()
// ... existing code ... import os from pathlib import Path import markdown // ... modified code ... def md_context(template): markdown_content = Path(template.filename).read_text() return {"post_content_html": markdowner.convert(markdown_content)} ... def render_md(site, template, **kwargs): # i.e. posts/post1.md -> build/posts/post1.html out = site.outpath / Path(template.name).with_suffix(".html") # Compile and stream the result os.makedirs(out.parent, exist_ok=True) site.get_template("_post.html").stream(**kwargs).dump(str(out), encoding="utf-8") // ... rest of the code ...
6d645d5b58043d0668721727bbfdcc7ee021b504
rwt/tests/test_scripts.py
rwt/tests/test_scripts.py
import textwrap import sys import subprocess def test_pkg_imported(tmpdir): """ Create a script that loads cython and ensure it runs. """ body = textwrap.dedent(""" import cython print("Successfully imported cython") """).lstrip() script_file = tmpdir / 'script' script_file.write_text(body, 'utf-8') pip_args = ['cython'] cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)] out = subprocess.check_output(cmd, universal_newlines=True) assert 'Successfully imported cython' in out
from __future__ import unicode_literals import textwrap import sys import subprocess def test_pkg_imported(tmpdir): """ Create a script that loads cython and ensure it runs. """ body = textwrap.dedent(""" import cython print("Successfully imported cython") """).lstrip() script_file = tmpdir / 'script' script_file.write_text(body, 'utf-8') pip_args = ['cython'] cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)] out = subprocess.check_output(cmd, universal_newlines=True) assert 'Successfully imported cython' in out
Add support for Python 2.7
Add support for Python 2.7
Python
mit
jaraco/rwt
+ from __future__ import unicode_literals + import textwrap import sys import subprocess def test_pkg_imported(tmpdir): """ Create a script that loads cython and ensure it runs. """ body = textwrap.dedent(""" import cython print("Successfully imported cython") """).lstrip() script_file = tmpdir / 'script' script_file.write_text(body, 'utf-8') pip_args = ['cython'] cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)] out = subprocess.check_output(cmd, universal_newlines=True) assert 'Successfully imported cython' in out
Add support for Python 2.7
## Code Before: import textwrap import sys import subprocess def test_pkg_imported(tmpdir): """ Create a script that loads cython and ensure it runs. """ body = textwrap.dedent(""" import cython print("Successfully imported cython") """).lstrip() script_file = tmpdir / 'script' script_file.write_text(body, 'utf-8') pip_args = ['cython'] cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)] out = subprocess.check_output(cmd, universal_newlines=True) assert 'Successfully imported cython' in out ## Instruction: Add support for Python 2.7 ## Code After: from __future__ import unicode_literals import textwrap import sys import subprocess def test_pkg_imported(tmpdir): """ Create a script that loads cython and ensure it runs. """ body = textwrap.dedent(""" import cython print("Successfully imported cython") """).lstrip() script_file = tmpdir / 'script' script_file.write_text(body, 'utf-8') pip_args = ['cython'] cmd = [sys.executable, '-m', 'rwt'] + pip_args + ['--', str(script_file)] out = subprocess.check_output(cmd, universal_newlines=True) assert 'Successfully imported cython' in out
... from __future__ import unicode_literals import textwrap ...
d68f28581cd3c3f57f7c41adbd65676887a51136
opps/channels/tests/test_forms.py
opps/channels/tests/test_forms.py
from django.test import TestCase from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from opps.channels.models import Channel from opps.channels.forms import ChannelAdminForm class ChannelFormTest(TestCase): def setUp(self): User = get_user_model() self.user = User.objects.create(username=u'test', password='test') self.site = Site.objects.filter(name=u'example.com').get() self.parent = Channel.objects.create(name=u'Home', slug=u'home', description=u'home page', site=self.site, user=self.user) def test_init(self): """ Test successful init without data """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(isinstance(form.instance, Channel)) self.assertEqual(form.instance.pk, self.parent.pk)
from django.test import TestCase from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from opps.channels.models import Channel from opps.channels.forms import ChannelAdminForm class ChannelFormTest(TestCase): def setUp(self): User = get_user_model() self.user = User.objects.create(username=u'test', password='test') self.site = Site.objects.filter(name=u'example.com').get() self.parent = Channel.objects.create(name=u'Home', slug=u'home', description=u'home page', site=self.site, user=self.user) def test_init(self): """ Test successful init without data """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(isinstance(form.instance, Channel)) self.assertEqual(form.instance.pk, self.parent.pk) self.assertEqual(int(form.fields['slug'].widget.attrs['maxlength']), 150) def test_readonly_slug(self): """ Check readonly field slug """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(form.fields['slug'].widget.attrs['readonly']) form_2 = ChannelAdminForm() self.assertNotIn('readonly', form_2.fields['slug'].widget.attrs)
Add test check readonly field slug of channel
Add test check readonly field slug of channel
Python
mit
jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,opps/opps,jeanmask/opps,opps/opps
from django.test import TestCase from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from opps.channels.models import Channel from opps.channels.forms import ChannelAdminForm class ChannelFormTest(TestCase): def setUp(self): User = get_user_model() self.user = User.objects.create(username=u'test', password='test') self.site = Site.objects.filter(name=u'example.com').get() self.parent = Channel.objects.create(name=u'Home', slug=u'home', description=u'home page', site=self.site, user=self.user) def test_init(self): """ Test successful init without data """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(isinstance(form.instance, Channel)) self.assertEqual(form.instance.pk, self.parent.pk) + self.assertEqual(int(form.fields['slug'].widget.attrs['maxlength']), 150) + def test_readonly_slug(self): + """ + Check readonly field slug + """ + form = ChannelAdminForm(instance=self.parent) + self.assertTrue(form.fields['slug'].widget.attrs['readonly']) + form_2 = ChannelAdminForm() + self.assertNotIn('readonly', form_2.fields['slug'].widget.attrs) +
Add test check readonly field slug of channel
## Code Before: from django.test import TestCase from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from opps.channels.models import Channel from opps.channels.forms import ChannelAdminForm class ChannelFormTest(TestCase): def setUp(self): User = get_user_model() self.user = User.objects.create(username=u'test', password='test') self.site = Site.objects.filter(name=u'example.com').get() self.parent = Channel.objects.create(name=u'Home', slug=u'home', description=u'home page', site=self.site, user=self.user) def test_init(self): """ Test successful init without data """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(isinstance(form.instance, Channel)) self.assertEqual(form.instance.pk, self.parent.pk) ## Instruction: Add test check readonly field slug of channel ## Code After: from django.test import TestCase from django.contrib.sites.models import Site from django.contrib.auth import get_user_model from opps.channels.models import Channel from opps.channels.forms import ChannelAdminForm class ChannelFormTest(TestCase): def setUp(self): User = get_user_model() self.user = User.objects.create(username=u'test', password='test') self.site = Site.objects.filter(name=u'example.com').get() self.parent = Channel.objects.create(name=u'Home', slug=u'home', description=u'home page', site=self.site, user=self.user) def test_init(self): """ Test successful init without data """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(isinstance(form.instance, Channel)) self.assertEqual(form.instance.pk, self.parent.pk) self.assertEqual(int(form.fields['slug'].widget.attrs['maxlength']), 150) def test_readonly_slug(self): """ Check readonly field slug """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(form.fields['slug'].widget.attrs['readonly']) form_2 = ChannelAdminForm() self.assertNotIn('readonly', form_2.fields['slug'].widget.attrs)
# ... existing code ... self.assertEqual(form.instance.pk, self.parent.pk) self.assertEqual(int(form.fields['slug'].widget.attrs['maxlength']), 150) def test_readonly_slug(self): """ Check readonly field slug """ form = ChannelAdminForm(instance=self.parent) self.assertTrue(form.fields['slug'].widget.attrs['readonly']) form_2 = ChannelAdminForm() self.assertNotIn('readonly', form_2.fields['slug'].widget.attrs) # ... rest of the code ...
fd77039104175a4b5702b46b21a2fa223676ddf4
bowser/Database.py
bowser/Database.py
import json import redis class Database(object): def __init__(self): self.redis = redis.StrictRedis(host='redis', port=6379, db=0) def set_data_of_server_channel(self, server, channel, data): self.redis.hmset(server, {channel: json.dumps(data)}) def fetch_data_of_server_channel(self, server, channel): data = self.redis.hget(server, channel) json_data = json.loads(data.decode('utf-8')) return json_data
import json import redis class Database(object): def __init__(self): self.redis = redis.StrictRedis(host='redis', port=6379, db=0) def set_data_of_server_channel(self, server, channel, data): self.redis.hmset(server, {channel: json.dumps(data)}) def fetch_data_of_server_channel(self, server, channel): data = self.redis.hget(server, channel) if data is None: raise KeyError json_data = json.loads(data.decode('utf-8')) return json_data
Raise KeyErrors for missing data in redis
fix: Raise KeyErrors for missing data in redis
Python
mit
kevinkjt2000/discord-minecraft-server-status
import json import redis class Database(object): def __init__(self): self.redis = redis.StrictRedis(host='redis', port=6379, db=0) def set_data_of_server_channel(self, server, channel, data): self.redis.hmset(server, {channel: json.dumps(data)}) def fetch_data_of_server_channel(self, server, channel): data = self.redis.hget(server, channel) + if data is None: + raise KeyError json_data = json.loads(data.decode('utf-8')) return json_data
Raise KeyErrors for missing data in redis
## Code Before: import json import redis class Database(object): def __init__(self): self.redis = redis.StrictRedis(host='redis', port=6379, db=0) def set_data_of_server_channel(self, server, channel, data): self.redis.hmset(server, {channel: json.dumps(data)}) def fetch_data_of_server_channel(self, server, channel): data = self.redis.hget(server, channel) json_data = json.loads(data.decode('utf-8')) return json_data ## Instruction: Raise KeyErrors for missing data in redis ## Code After: import json import redis class Database(object): def __init__(self): self.redis = redis.StrictRedis(host='redis', port=6379, db=0) def set_data_of_server_channel(self, server, channel, data): self.redis.hmset(server, {channel: json.dumps(data)}) def fetch_data_of_server_channel(self, server, channel): data = self.redis.hget(server, channel) if data is None: raise KeyError json_data = json.loads(data.decode('utf-8')) return json_data
# ... existing code ... data = self.redis.hget(server, channel) if data is None: raise KeyError json_data = json.loads(data.decode('utf-8')) # ... rest of the code ...
564e611d7cb0b94e71c53e69971a49c312a0f7f8
tob-api/tob_api/custom_settings_ongov.py
tob-api/tob_api/custom_settings_ongov.py
''' Enclose property names in double quotes in order to JSON serialize the contents in the API ''' CUSTOMIZATIONS = { "serializers": { "Location": { "includeFields":{ "id", "verifiableOrgId", "doingBusinessAsId", "locationTypeId", "municipality", "province" } } } }
''' Enclose property names in double quotes in order to JSON serialize the contents in the API ''' CUSTOMIZATIONS = { "serializers": { "Location": { "includeFields":[ "id", "verifiableOrgId", "doingBusinessAsId", "locationTypeId", "municipality", "province" ] } } }
Fix ongov customs settings formatting.
Fix ongov customs settings formatting.
Python
apache-2.0
swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook
''' Enclose property names in double quotes in order to JSON serialize the contents in the API ''' CUSTOMIZATIONS = { "serializers": { "Location": { - "includeFields":{ + "includeFields":[ "id", "verifiableOrgId", "doingBusinessAsId", "locationTypeId", "municipality", "province" - } + ] } } } -
Fix ongov customs settings formatting.
## Code Before: ''' Enclose property names in double quotes in order to JSON serialize the contents in the API ''' CUSTOMIZATIONS = { "serializers": { "Location": { "includeFields":{ "id", "verifiableOrgId", "doingBusinessAsId", "locationTypeId", "municipality", "province" } } } } ## Instruction: Fix ongov customs settings formatting. ## Code After: ''' Enclose property names in double quotes in order to JSON serialize the contents in the API ''' CUSTOMIZATIONS = { "serializers": { "Location": { "includeFields":[ "id", "verifiableOrgId", "doingBusinessAsId", "locationTypeId", "municipality", "province" ] } } }
... { "includeFields":[ "id", ... "province" ] } ... } ...
50bab0199e2d209dc177f5e3b5f193330048e403
blinktCP.py
blinktCP.py
from bluedot import BlueDot import colorsys import time import blinkt last_time = time.time() def setall(r,g,b): for x in range(blinkt.NUM_PIXELS): blinkt.set_pixel(x, r, g, b) blinkt.show() def move(pos): h=((pos.angle+180) % 360) / 360 s=pos.distance v=1.0 r, g, b = [int(c*255) for c in colorsys.hsv_to_rgb(h, s, v)] setall(r,g,b) def rmove(pos): global last_time current_time=time.time() delta = current_time-last_time last_time = current_time if (delta<0.3) : setall(0,0,0) blinkt.set_brightness(0.1) blinkt.set_clear_on_exit() bd = BlueDot() bd.wait_for_press() bd.when_pressed = move bd.when_moved = move bd.when_released = rmove while True: time.sleep(1)
from bluedot import BlueDot import colorsys import time import blinkt last_time = time.time() def setall(r,g,b): # for x in range(blinkt.NUM_PIXELS): # blinkt.set_pixel(x, r, g, b) blinkt.set_all(r, g, b) blinkt.show() def move(pos): h=((pos.angle+180) % 360) / 360 s=pos.distance v=1.0 r, g, b = [int(c*255) for c in colorsys.hsv_to_rgb(h, s, v)] setall(r,g,b) def rmove(pos): global last_time current_time=time.time() delta = current_time-last_time last_time = current_time if (delta<0.3) : setall(0,0,0) blinkt.set_brightness(0.1) blinkt.set_clear_on_exit() bd = BlueDot() bd.wait_for_press() bd.when_pressed = move bd.when_moved = move bd.when_released = rmove while True: time.sleep(1)
Use the Blinkt! library set_all rather than to loop on 8 pixels.
Use the Blinkt! library set_all rather than to loop on 8 pixels.
Python
mit
dglaude/Blue-Dot-Colour-Picker
from bluedot import BlueDot import colorsys import time import blinkt last_time = time.time() def setall(r,g,b): - for x in range(blinkt.NUM_PIXELS): + # for x in range(blinkt.NUM_PIXELS): - blinkt.set_pixel(x, r, g, b) + # blinkt.set_pixel(x, r, g, b) + blinkt.set_all(r, g, b) blinkt.show() def move(pos): h=((pos.angle+180) % 360) / 360 s=pos.distance v=1.0 r, g, b = [int(c*255) for c in colorsys.hsv_to_rgb(h, s, v)] setall(r,g,b) def rmove(pos): global last_time current_time=time.time() delta = current_time-last_time last_time = current_time if (delta<0.3) : setall(0,0,0) blinkt.set_brightness(0.1) blinkt.set_clear_on_exit() bd = BlueDot() bd.wait_for_press() bd.when_pressed = move bd.when_moved = move bd.when_released = rmove while True: time.sleep(1)
Use the Blinkt! library set_all rather than to loop on 8 pixels.
## Code Before: from bluedot import BlueDot import colorsys import time import blinkt last_time = time.time() def setall(r,g,b): for x in range(blinkt.NUM_PIXELS): blinkt.set_pixel(x, r, g, b) blinkt.show() def move(pos): h=((pos.angle+180) % 360) / 360 s=pos.distance v=1.0 r, g, b = [int(c*255) for c in colorsys.hsv_to_rgb(h, s, v)] setall(r,g,b) def rmove(pos): global last_time current_time=time.time() delta = current_time-last_time last_time = current_time if (delta<0.3) : setall(0,0,0) blinkt.set_brightness(0.1) blinkt.set_clear_on_exit() bd = BlueDot() bd.wait_for_press() bd.when_pressed = move bd.when_moved = move bd.when_released = rmove while True: time.sleep(1) ## Instruction: Use the Blinkt! library set_all rather than to loop on 8 pixels. ## Code After: from bluedot import BlueDot import colorsys import time import blinkt last_time = time.time() def setall(r,g,b): # for x in range(blinkt.NUM_PIXELS): # blinkt.set_pixel(x, r, g, b) blinkt.set_all(r, g, b) blinkt.show() def move(pos): h=((pos.angle+180) % 360) / 360 s=pos.distance v=1.0 r, g, b = [int(c*255) for c in colorsys.hsv_to_rgb(h, s, v)] setall(r,g,b) def rmove(pos): global last_time current_time=time.time() delta = current_time-last_time last_time = current_time if (delta<0.3) : setall(0,0,0) blinkt.set_brightness(0.1) blinkt.set_clear_on_exit() bd = BlueDot() bd.wait_for_press() bd.when_pressed = move bd.when_moved = move bd.when_released = rmove while True: time.sleep(1)
... def setall(r,g,b): # for x in range(blinkt.NUM_PIXELS): # blinkt.set_pixel(x, r, g, b) blinkt.set_all(r, g, b) blinkt.show() ...
1c6b06f240d4388b3e140e3d9ab610711616f539
src/python/expedient/clearinghouse/resources/models.py
src/python/expedient/clearinghouse/resources/models.py
''' @author: jnaous ''' from django.db import models from expedient.clearinghouse.aggregate.models import Aggregate from expedient.common.extendable.models import Extendable from expedient.clearinghouse.slice.models import Slice class Resource(Extendable): ''' Generic model of a resource. @param aggregate: The L{Aggregate} that controls/owns this resource @type aggregate: L{models.ForeignKey} to L{Aggregate} @param name: A human-readable name for the resource @type name: L{str} ''' name = models.CharField(max_length=200) available = models.BooleanField("Available", default=True, editable=False) status_change_timestamp = models.DateTimeField(editable=False) aggregate = models.ForeignKey( Aggregate, verbose_name="Aggregate the resource belongs to") slice_set = models.ManyToManyField( Slice, through="Sliver", verbose_name="Slices this resource is used in") def __unicode__(self): return u"Resource: %s belonging to aggregate %s." % ( self.name, self.aggregate) class Sliver(Extendable): ''' Information on the reservation of a particular resource for a slice. ''' resource = models.ForeignKey( Resource, verbose_name="Resource this sliver is part of") slice = models.ForeignKey( Slice, verbose_name="Slice this sliver is part of")
''' @author: jnaous ''' from django.db import models from expedient.clearinghouse.aggregate.models import Aggregate from expedient.common.extendable.models import Extendable from expedient.clearinghouse.slice.models import Slice from datetime import datetime class Resource(Extendable): ''' Generic model of a resource. @param aggregate: The L{Aggregate} that controls/owns this resource @type aggregate: L{models.ForeignKey} to L{Aggregate} @param name: A human-readable name for the resource @type name: L{str} ''' name = models.CharField(max_length=200) available = models.BooleanField("Available", default=True, editable=False) status_change_timestamp = models.DateTimeField( editable=False, auto_now_add=True) aggregate = models.ForeignKey( Aggregate, verbose_name="Aggregate the resource belongs to") slice_set = models.ManyToManyField( Slice, through="Sliver", verbose_name="Slices this resource is used in") def update_timestamp(self): self.status_change_timestamp = datetime.now() def __unicode__(self): return u"Resource: %s belonging to aggregate %s." % ( self.name, self.aggregate) class Sliver(Extendable): ''' Information on the reservation of a particular resource for a slice. ''' resource = models.ForeignKey( Resource, verbose_name="Resource this sliver is part of") slice = models.ForeignKey( Slice, verbose_name="Slice this sliver is part of")
Add functions to manage status change timestamp better
Add functions to manage status change timestamp better
Python
bsd-3-clause
avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf
''' @author: jnaous ''' from django.db import models from expedient.clearinghouse.aggregate.models import Aggregate from expedient.common.extendable.models import Extendable from expedient.clearinghouse.slice.models import Slice + from datetime import datetime class Resource(Extendable): ''' Generic model of a resource. @param aggregate: The L{Aggregate} that controls/owns this resource @type aggregate: L{models.ForeignKey} to L{Aggregate} @param name: A human-readable name for the resource @type name: L{str} ''' name = models.CharField(max_length=200) available = models.BooleanField("Available", default=True, editable=False) - status_change_timestamp = models.DateTimeField(editable=False) + status_change_timestamp = models.DateTimeField( + editable=False, auto_now_add=True) aggregate = models.ForeignKey( Aggregate, verbose_name="Aggregate the resource belongs to") slice_set = models.ManyToManyField( Slice, through="Sliver", verbose_name="Slices this resource is used in") + def update_timestamp(self): + self.status_change_timestamp = datetime.now() + def __unicode__(self): return u"Resource: %s belonging to aggregate %s." % ( self.name, self.aggregate) - + class Sliver(Extendable): ''' Information on the reservation of a particular resource for a slice. ''' resource = models.ForeignKey( Resource, verbose_name="Resource this sliver is part of") slice = models.ForeignKey( Slice, verbose_name="Slice this sliver is part of")
Add functions to manage status change timestamp better
## Code Before: ''' @author: jnaous ''' from django.db import models from expedient.clearinghouse.aggregate.models import Aggregate from expedient.common.extendable.models import Extendable from expedient.clearinghouse.slice.models import Slice class Resource(Extendable): ''' Generic model of a resource. @param aggregate: The L{Aggregate} that controls/owns this resource @type aggregate: L{models.ForeignKey} to L{Aggregate} @param name: A human-readable name for the resource @type name: L{str} ''' name = models.CharField(max_length=200) available = models.BooleanField("Available", default=True, editable=False) status_change_timestamp = models.DateTimeField(editable=False) aggregate = models.ForeignKey( Aggregate, verbose_name="Aggregate the resource belongs to") slice_set = models.ManyToManyField( Slice, through="Sliver", verbose_name="Slices this resource is used in") def __unicode__(self): return u"Resource: %s belonging to aggregate %s." % ( self.name, self.aggregate) class Sliver(Extendable): ''' Information on the reservation of a particular resource for a slice. ''' resource = models.ForeignKey( Resource, verbose_name="Resource this sliver is part of") slice = models.ForeignKey( Slice, verbose_name="Slice this sliver is part of") ## Instruction: Add functions to manage status change timestamp better ## Code After: ''' @author: jnaous ''' from django.db import models from expedient.clearinghouse.aggregate.models import Aggregate from expedient.common.extendable.models import Extendable from expedient.clearinghouse.slice.models import Slice from datetime import datetime class Resource(Extendable): ''' Generic model of a resource. @param aggregate: The L{Aggregate} that controls/owns this resource @type aggregate: L{models.ForeignKey} to L{Aggregate} @param name: A human-readable name for the resource @type name: L{str} ''' name = models.CharField(max_length=200) available = models.BooleanField("Available", default=True, editable=False) status_change_timestamp = models.DateTimeField( editable=False, auto_now_add=True) aggregate = models.ForeignKey( Aggregate, verbose_name="Aggregate the resource belongs to") slice_set = models.ManyToManyField( Slice, through="Sliver", verbose_name="Slices this resource is used in") def update_timestamp(self): self.status_change_timestamp = datetime.now() def __unicode__(self): return u"Resource: %s belonging to aggregate %s." % ( self.name, self.aggregate) class Sliver(Extendable): ''' Information on the reservation of a particular resource for a slice. ''' resource = models.ForeignKey( Resource, verbose_name="Resource this sliver is part of") slice = models.ForeignKey( Slice, verbose_name="Slice this sliver is part of")
# ... existing code ... from expedient.clearinghouse.slice.models import Slice from datetime import datetime # ... modified code ... available = models.BooleanField("Available", default=True, editable=False) status_change_timestamp = models.DateTimeField( editable=False, auto_now_add=True) aggregate = models.ForeignKey( ... def update_timestamp(self): self.status_change_timestamp = datetime.now() def __unicode__(self): ... self.name, self.aggregate) class Sliver(Extendable): # ... rest of the code ...
e24f89366a8a58a29d26f58b8f21aba437ec1566
tests/integration/runners/test_cache.py
tests/integration/runners/test_cache.py
''' Tests for the salt-run command ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing libs import tests.integration as integration class ManageTest(integration.ShellCase): ''' Test the manage runner ''' def test_cache(self): ''' Store, list, fetch, then flush data ''' # Store the data ret = self.run_run_plus( 'cache.store', bank='test/runner', key='test_cache', data='The time has come the walrus said', ) # Make sure we can see the new key ret = self.run_run_plus('cache.list', bank='test/runner') self.assertIn('test_cache', ret['return']) # Make sure we can see the new data ret = self.run_run_plus('cache.fetch', bank='test/runner', key='test_cache') self.assertIn('The time has come the walrus said', ret['return']) # Make sure we can delete the data ret = self.run_run_plus('cache.flush', bank='test/runner', key='test_cache') ret = self.run_run_plus('cache.list', bank='test/runner') self.assertNotIn('test_cache', ret['return'])
''' Tests for the salt-run command ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing libs import tests.integration as integration class ManageTest(integration.ShellCase): ''' Test the manage runner ''' def test_cache(self): ''' Store, list, fetch, then flush data ''' # Store the data ret = self.run_run_plus( 'cache.store', bank='cachetest/runner', key='test_cache', data='The time has come the walrus said', ) # Make sure we can see the new key ret = self.run_run_plus('cache.list', bank='cachetest/runner') self.assertIn('test_cache', ret['return']) # Make sure we can see the new data ret = self.run_run_plus('cache.fetch', bank='cachetest/runner', key='test_cache') self.assertIn('The time has come the walrus said', ret['return']) # Make sure we can delete the data ret = self.run_run_plus('cache.flush', bank='cachetest/runner', key='test_cache') ret = self.run_run_plus('cache.list', bank='cachetest/runner') self.assertNotIn('test_cache', ret['return'])
Use a slightly more specific bank name
Use a slightly more specific bank name
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' Tests for the salt-run command ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing libs import tests.integration as integration class ManageTest(integration.ShellCase): ''' Test the manage runner ''' def test_cache(self): ''' Store, list, fetch, then flush data ''' # Store the data ret = self.run_run_plus( 'cache.store', - bank='test/runner', + bank='cachetest/runner', key='test_cache', data='The time has come the walrus said', ) # Make sure we can see the new key - ret = self.run_run_plus('cache.list', bank='test/runner') + ret = self.run_run_plus('cache.list', bank='cachetest/runner') self.assertIn('test_cache', ret['return']) # Make sure we can see the new data - ret = self.run_run_plus('cache.fetch', bank='test/runner', key='test_cache') + ret = self.run_run_plus('cache.fetch', bank='cachetest/runner', key='test_cache') self.assertIn('The time has come the walrus said', ret['return']) # Make sure we can delete the data - ret = self.run_run_plus('cache.flush', bank='test/runner', key='test_cache') + ret = self.run_run_plus('cache.flush', bank='cachetest/runner', key='test_cache') - ret = self.run_run_plus('cache.list', bank='test/runner') + ret = self.run_run_plus('cache.list', bank='cachetest/runner') self.assertNotIn('test_cache', ret['return'])
Use a slightly more specific bank name
## Code Before: ''' Tests for the salt-run command ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing libs import tests.integration as integration class ManageTest(integration.ShellCase): ''' Test the manage runner ''' def test_cache(self): ''' Store, list, fetch, then flush data ''' # Store the data ret = self.run_run_plus( 'cache.store', bank='test/runner', key='test_cache', data='The time has come the walrus said', ) # Make sure we can see the new key ret = self.run_run_plus('cache.list', bank='test/runner') self.assertIn('test_cache', ret['return']) # Make sure we can see the new data ret = self.run_run_plus('cache.fetch', bank='test/runner', key='test_cache') self.assertIn('The time has come the walrus said', ret['return']) # Make sure we can delete the data ret = self.run_run_plus('cache.flush', bank='test/runner', key='test_cache') ret = self.run_run_plus('cache.list', bank='test/runner') self.assertNotIn('test_cache', ret['return']) ## Instruction: Use a slightly more specific bank name ## Code After: ''' Tests for the salt-run command ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing libs import tests.integration as integration class ManageTest(integration.ShellCase): ''' Test the manage runner ''' def test_cache(self): ''' Store, list, fetch, then flush data ''' # Store the data ret = self.run_run_plus( 'cache.store', bank='cachetest/runner', key='test_cache', data='The time has come the walrus said', ) # Make sure we can see the new key ret = self.run_run_plus('cache.list', bank='cachetest/runner') self.assertIn('test_cache', ret['return']) # Make sure we can see the new data ret = self.run_run_plus('cache.fetch', bank='cachetest/runner', key='test_cache') self.assertIn('The time has come the walrus said', ret['return']) # Make sure we can delete the data ret = self.run_run_plus('cache.flush', bank='cachetest/runner', key='test_cache') ret = self.run_run_plus('cache.list', bank='cachetest/runner') self.assertNotIn('test_cache', ret['return'])
... 'cache.store', bank='cachetest/runner', key='test_cache', ... # Make sure we can see the new key ret = self.run_run_plus('cache.list', bank='cachetest/runner') self.assertIn('test_cache', ret['return']) ... # Make sure we can see the new data ret = self.run_run_plus('cache.fetch', bank='cachetest/runner', key='test_cache') self.assertIn('The time has come the walrus said', ret['return']) ... # Make sure we can delete the data ret = self.run_run_plus('cache.flush', bank='cachetest/runner', key='test_cache') ret = self.run_run_plus('cache.list', bank='cachetest/runner') self.assertNotIn('test_cache', ret['return']) ...
0ae9b232b82285f2fa275b8ffa5dced6b9377b0e
keyring/credentials.py
keyring/credentials.py
import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var)
import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def __eq__(self, other: object) -> bool: if not isinstance(other, EnvironCredential): return NotImplemented return ( self.user_env_var == other.user_env_var and self.pwd_env_var == other.pwd_env_var ) def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var)
Add equality operator to EnvironCredential
Add equality operator to EnvironCredential Equality operator is useful for testing EnvironCredential
Python
mit
jaraco/keyring
import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var + def __eq__(self, other: object) -> bool: + if not isinstance(other, EnvironCredential): + return NotImplemented + + return ( + self.user_env_var == other.user_env_var + and self.pwd_env_var == other.pwd_env_var + ) + def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var)
Add equality operator to EnvironCredential
## Code Before: import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var) ## Instruction: Add equality operator to EnvironCredential ## Code After: import os import abc class Credential(metaclass=abc.ABCMeta): """Abstract class to manage credentials""" @abc.abstractproperty def username(self): return None @abc.abstractproperty def password(self): return None class SimpleCredential(Credential): """Simple credentials implementation""" def __init__(self, username, password): self._username = username self._password = password @property def username(self): return self._username @property def password(self): return self._password class EnvironCredential(Credential): """Source credentials from environment variables. Actual sourcing is deferred until requested. """ def __init__(self, user_env_var, pwd_env_var): self.user_env_var = user_env_var self.pwd_env_var = pwd_env_var def __eq__(self, other: object) -> bool: if not isinstance(other, EnvironCredential): return NotImplemented return ( self.user_env_var == other.user_env_var and self.pwd_env_var == other.pwd_env_var ) def _get_env(self, env_var): """Helper to read an environment variable""" value = os.environ.get(env_var) if not value: raise ValueError('Missing environment variable:%s' % env_var) return value @property def username(self): return self._get_env(self.user_env_var) @property def password(self): return self._get_env(self.pwd_env_var)
# ... existing code ... def __eq__(self, other: object) -> bool: if not isinstance(other, EnvironCredential): return NotImplemented return ( self.user_env_var == other.user_env_var and self.pwd_env_var == other.pwd_env_var ) def _get_env(self, env_var): # ... rest of the code ...
b1504dac6d33b4f0774cabceeb219653b9b6201f
ui.py
ui.py
from terminaltables import SingleTable def render(object, **kw): if object == 'gallows': render_gallows(**kw) if object == 'bank': render_bank(**kw) if object == 'game_state': render_game_state(**kw) def render_gallows(parts=0, **kw): print(""" ______ | | O | | | | | / | | --------- """) def render_bank(letters=[], **kw): sz = 6 # Size of table if not any(letters): let = [' '] else: let = sorted(list(letters)) table = SingleTable([let[i:i + sz] for i in range(0, len(let), sz)], 'Incorrect Guesses') table.inner_heading_row_border = False table.inner_row_border = True table.justify_columns = {idx: val for idx, val in enumerate(['center'] * sz)} print() print(table.table) def render_game_state(word="", found=[], **kw): for letter in word: if letter in found: print(letter, end='') else: print(' _ ', end='')
from terminaltables import SingleTable def render(object, **kw): if object == 'gallows': render_gallows(**kw) if object == 'bank': render_bank(**kw) if object == 'game_state': render_game_state(**kw) def render_gallows(parts=0, **kw): print(""" ______ | | O | | | | | / | | --------- """) def render_bank(letters=[], **kw): sz = 6 # Size of table if not any(letters): let = [' '] else: let = sorted(list(letters)) table = SingleTable([let[i:i + sz] for i in range(0, len(let), sz)], 'Incorrect Guesses') table.inner_heading_row_border = False table.inner_row_border = True table.justify_columns = {idx: val for idx, val in enumerate(['center'] * sz)} print("\n{}".format(table.table)) def render_game_state(word="", found=[], **kw): for letter in word: if letter in found: print(letter, end='') else: print(' _ ', end='')
Change the way we get a clean, blank line before rendering letter bank
Change the way we get a clean, blank line before rendering letter bank
Python
mit
tml/python-hangman-2017-summer
from terminaltables import SingleTable def render(object, **kw): if object == 'gallows': render_gallows(**kw) if object == 'bank': render_bank(**kw) if object == 'game_state': render_game_state(**kw) def render_gallows(parts=0, **kw): print(""" ______ | | O | | | | | / | | --------- """) def render_bank(letters=[], **kw): sz = 6 # Size of table if not any(letters): let = [' '] else: let = sorted(list(letters)) table = SingleTable([let[i:i + sz] for i in range(0, len(let), sz)], 'Incorrect Guesses') table.inner_heading_row_border = False table.inner_row_border = True table.justify_columns = {idx: val for idx, val in enumerate(['center'] * sz)} + print("\n{}".format(table.table)) - print() - print(table.table) def render_game_state(word="", found=[], **kw): for letter in word: if letter in found: print(letter, end='') else: print(' _ ', end='')
Change the way we get a clean, blank line before rendering letter bank
## Code Before: from terminaltables import SingleTable def render(object, **kw): if object == 'gallows': render_gallows(**kw) if object == 'bank': render_bank(**kw) if object == 'game_state': render_game_state(**kw) def render_gallows(parts=0, **kw): print(""" ______ | | O | | | | | / | | --------- """) def render_bank(letters=[], **kw): sz = 6 # Size of table if not any(letters): let = [' '] else: let = sorted(list(letters)) table = SingleTable([let[i:i + sz] for i in range(0, len(let), sz)], 'Incorrect Guesses') table.inner_heading_row_border = False table.inner_row_border = True table.justify_columns = {idx: val for idx, val in enumerate(['center'] * sz)} print() print(table.table) def render_game_state(word="", found=[], **kw): for letter in word: if letter in found: print(letter, end='') else: print(' _ ', end='') ## Instruction: Change the way we get a clean, blank line before rendering letter bank ## Code After: from terminaltables import SingleTable def render(object, **kw): if object == 'gallows': render_gallows(**kw) if object == 'bank': render_bank(**kw) if object == 'game_state': render_game_state(**kw) def render_gallows(parts=0, **kw): print(""" ______ | | O | | | | | / | | --------- """) def render_bank(letters=[], **kw): sz = 6 # Size of table if not any(letters): let = [' '] else: let = sorted(list(letters)) table = SingleTable([let[i:i + sz] for i in range(0, len(let), sz)], 'Incorrect Guesses') table.inner_heading_row_border = False table.inner_row_border = True table.justify_columns = {idx: val for idx, val in enumerate(['center'] * sz)} print("\n{}".format(table.table)) def render_game_state(word="", found=[], **kw): for letter in word: if letter in found: print(letter, end='') else: print(' _ ', end='')
// ... existing code ... enumerate(['center'] * sz)} print("\n{}".format(table.table)) // ... rest of the code ...
f8b52162748ccf62db881fad101e6a91ed014bd4
plugins/Hitman_Codename_47.py
plugins/Hitman_Codename_47.py
import os from lib.base_plugin import BasePlugin from lib.paths import SteamGamesPath class HitmanCodename47Plugin(BasePlugin): Name = "Hitman: Codename 47" support_os = ["Windows"] def backup(self, _): _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') def restore(self, _): _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') def detect(self): if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')): return True return False
import os from lib.base_plugin import BasePlugin from lib.paths import SteamGamesPath class HitmanCodename47Plugin(BasePlugin): Name = "Hitman: Codename 47" support_os = ["Windows"] def backup(self, _): _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') _.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) def restore(self, _): _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') _.restore_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) def detect(self): if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')): return True return False
Add backuping config files for Hitman: Codename 47
Add backuping config files for Hitman: Codename 47
Python
mit
Pr0Ger/SGSB
import os from lib.base_plugin import BasePlugin from lib.paths import SteamGamesPath class HitmanCodename47Plugin(BasePlugin): Name = "Hitman: Codename 47" support_os = ["Windows"] def backup(self, _): _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') + _.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) def restore(self, _): _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') + _.restore_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) def detect(self): if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')): return True return False
Add backuping config files for Hitman: Codename 47
## Code Before: import os from lib.base_plugin import BasePlugin from lib.paths import SteamGamesPath class HitmanCodename47Plugin(BasePlugin): Name = "Hitman: Codename 47" support_os = ["Windows"] def backup(self, _): _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') def restore(self, _): _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') def detect(self): if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')): return True return False ## Instruction: Add backuping config files for Hitman: Codename 47 ## Code After: import os from lib.base_plugin import BasePlugin from lib.paths import SteamGamesPath class HitmanCodename47Plugin(BasePlugin): Name = "Hitman: Codename 47" support_os = ["Windows"] def backup(self, _): _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') _.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) def restore(self, _): _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') _.restore_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) def detect(self): if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')): return True return False
... _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') _.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) ... _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav') _.restore_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini']) ...
af3525bf174d0774b61464f9cc8ab8441babc7ae
examples/flask_alchemy/test_demoapp.py
examples/flask_alchemy/test_demoapp.py
import os import unittest import tempfile import demoapp import demoapp_factories class DemoAppTestCase(unittest.TestCase): def setUp(self): demoapp.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' demoapp.app.config['TESTING'] = True self.app = demoapp.app.test_client() self.db = demoapp.db self.db.create_all() def tearDown(self): self.db.drop_all() def test_user_factory(self): user = demoapp_factories.UserFactory() self.db.session.commit() self.assertIsNotNone(user.id) self.assertEqual(1, len(demoapp.User.query.all())) def test_userlog_factory(self): userlog = demoapp_factories.UserLogFactory() self.db.session.commit() self.assertIsNotNone(userlog.id) self.assertIsNotNone(userlog.user.id) self.assertEqual(1, len(demoapp.User.query.all())) self.assertEqual(1, len(demoapp.UserLog.query.all()))
import unittest import demoapp import demoapp_factories class DemoAppTestCase(unittest.TestCase): def setUp(self): demoapp.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' demoapp.app.config['TESTING'] = True self.app = demoapp.app.test_client() self.db = demoapp.db self.db.create_all() def tearDown(self): self.db.drop_all() def test_user_factory(self): user = demoapp_factories.UserFactory() self.db.session.commit() self.assertIsNotNone(user.id) self.assertEqual(1, len(demoapp.User.query.all())) def test_userlog_factory(self): userlog = demoapp_factories.UserLogFactory() self.db.session.commit() self.assertIsNotNone(userlog.id) self.assertIsNotNone(userlog.user.id) self.assertEqual(1, len(demoapp.User.query.all())) self.assertEqual(1, len(demoapp.UserLog.query.all()))
Remove useless imports from flask alchemy demo
Remove useless imports from flask alchemy demo
Python
mit
FactoryBoy/factory_boy
- import os import unittest - import tempfile import demoapp import demoapp_factories + class DemoAppTestCase(unittest.TestCase): def setUp(self): demoapp.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' demoapp.app.config['TESTING'] = True self.app = demoapp.app.test_client() self.db = demoapp.db self.db.create_all() def tearDown(self): self.db.drop_all() def test_user_factory(self): user = demoapp_factories.UserFactory() self.db.session.commit() self.assertIsNotNone(user.id) self.assertEqual(1, len(demoapp.User.query.all())) def test_userlog_factory(self): userlog = demoapp_factories.UserLogFactory() self.db.session.commit() self.assertIsNotNone(userlog.id) self.assertIsNotNone(userlog.user.id) self.assertEqual(1, len(demoapp.User.query.all())) self.assertEqual(1, len(demoapp.UserLog.query.all()))
Remove useless imports from flask alchemy demo
## Code Before: import os import unittest import tempfile import demoapp import demoapp_factories class DemoAppTestCase(unittest.TestCase): def setUp(self): demoapp.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' demoapp.app.config['TESTING'] = True self.app = demoapp.app.test_client() self.db = demoapp.db self.db.create_all() def tearDown(self): self.db.drop_all() def test_user_factory(self): user = demoapp_factories.UserFactory() self.db.session.commit() self.assertIsNotNone(user.id) self.assertEqual(1, len(demoapp.User.query.all())) def test_userlog_factory(self): userlog = demoapp_factories.UserLogFactory() self.db.session.commit() self.assertIsNotNone(userlog.id) self.assertIsNotNone(userlog.user.id) self.assertEqual(1, len(demoapp.User.query.all())) self.assertEqual(1, len(demoapp.UserLog.query.all())) ## Instruction: Remove useless imports from flask alchemy demo ## Code After: import unittest import demoapp import demoapp_factories class DemoAppTestCase(unittest.TestCase): def setUp(self): demoapp.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' demoapp.app.config['TESTING'] = True self.app = demoapp.app.test_client() self.db = demoapp.db self.db.create_all() def tearDown(self): self.db.drop_all() def test_user_factory(self): user = demoapp_factories.UserFactory() self.db.session.commit() self.assertIsNotNone(user.id) self.assertEqual(1, len(demoapp.User.query.all())) def test_userlog_factory(self): userlog = demoapp_factories.UserLogFactory() self.db.session.commit() self.assertIsNotNone(userlog.id) self.assertIsNotNone(userlog.user.id) self.assertEqual(1, len(demoapp.User.query.all())) self.assertEqual(1, len(demoapp.UserLog.query.all()))
// ... existing code ... import unittest // ... modified code ... import demoapp_factories // ... rest of the code ...
6830f29022746838677ecca420aeff190943c5ed
random/__init__.py
random/__init__.py
"""Nomisma Quantitative Finance random number samplers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nomisma_quant_finance.random.random_ops import multivariate_normal from nomisma_quant_finance.random.stateless_random_ops import stateless_random_shuffle __all__ = [ 'multivariate_normal', 'stateless_random_shuffle' ]
"""Random number samplers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nomisma_quant_finance.random.random_ops import multivariate_normal from nomisma_quant_finance.random.stateless_random_ops import stateless_random_shuffle __all__ = [ 'multivariate_normal', 'stateless_random_shuffle' ]
Remove remnants of internal project naming in one docstring.
Remove remnants of internal project naming in one docstring. PiperOrigin-RevId: 263530441
Python
apache-2.0
google/tf-quant-finance,google/tf-quant-finance
- """Nomisma Quantitative Finance random number samplers.""" + """Random number samplers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nomisma_quant_finance.random.random_ops import multivariate_normal from nomisma_quant_finance.random.stateless_random_ops import stateless_random_shuffle __all__ = [ 'multivariate_normal', 'stateless_random_shuffle' ]
Remove remnants of internal project naming in one docstring.
## Code Before: """Nomisma Quantitative Finance random number samplers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nomisma_quant_finance.random.random_ops import multivariate_normal from nomisma_quant_finance.random.stateless_random_ops import stateless_random_shuffle __all__ = [ 'multivariate_normal', 'stateless_random_shuffle' ] ## Instruction: Remove remnants of internal project naming in one docstring. ## Code After: """Random number samplers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from nomisma_quant_finance.random.random_ops import multivariate_normal from nomisma_quant_finance.random.stateless_random_ops import stateless_random_shuffle __all__ = [ 'multivariate_normal', 'stateless_random_shuffle' ]
# ... existing code ... """Random number samplers.""" # ... rest of the code ...
cebfd01451a2d78217bffd171ab3bcccbabf895f
zerodb/collective/indexing/indexer.py
zerodb/collective/indexing/indexer.py
from zope.interface import implements #from Products.Archetypes.CatalogMultiplex import CatalogMultiplex #from Products.CMFCore.CMFCatalogAware import CMFCatalogAware from zerodb.collective.indexing.interfaces import IIndexQueueProcessor # container to hold references to the original and "monkeyed" indexing methods # these are populated by `collective.indexing.monkey` catalogMultiplexMethods = {} catalogAwareMethods = {} monkeyMethods = {} def getOwnIndexMethod(obj, name): """ return private indexing method if the given object has one """ attr = getattr(obj.__class__, name, None) if attr is not None: method = attr.im_func monkey = monkeyMethods.get(name.rstrip('Object'), None) if monkey is not None and method is not monkey: return method class IPortalCatalogQueueProcessor(IIndexQueueProcessor): """ an index queue processor for the standard portal catalog via the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """ class PortalCatalogProcessor(object): implements(IPortalCatalogQueueProcessor) def index(self, obj, attributes=None): #index(obj, attributes) pass def reindex(self, obj, attributes=None): #reindex(obj, attributes) pass def unindex(self, obj): #unindex(obj) pass def begin(self): pass def commit(self): pass def abort(self): pass
from zope.interface import implements from zerodb.collective.indexing.interfaces import IIndexQueueProcessor class IPortalCatalogQueueProcessor(IIndexQueueProcessor): """ an index queue processor for the standard portal catalog via the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """ class PortalCatalogProcessor(object): implements(IPortalCatalogQueueProcessor) def index(self, obj, attributes=None): #index(obj, attributes) pass def reindex(self, obj, attributes=None): #reindex(obj, attributes) pass def unindex(self, obj): #unindex(obj) pass def begin(self): pass def commit(self): pass def abort(self): pass
Remove unused code for monkeyed methods
Remove unused code for monkeyed methods
Python
agpl-3.0
zero-db/zerodb,zerodb/zerodb,zero-db/zerodb,zerodb/zerodb
from zope.interface import implements - #from Products.Archetypes.CatalogMultiplex import CatalogMultiplex - #from Products.CMFCore.CMFCatalogAware import CMFCatalogAware from zerodb.collective.indexing.interfaces import IIndexQueueProcessor - - - # container to hold references to the original and "monkeyed" indexing methods - # these are populated by `collective.indexing.monkey` - catalogMultiplexMethods = {} - catalogAwareMethods = {} - monkeyMethods = {} - - - def getOwnIndexMethod(obj, name): - """ return private indexing method if the given object has one """ - attr = getattr(obj.__class__, name, None) - if attr is not None: - method = attr.im_func - monkey = monkeyMethods.get(name.rstrip('Object'), None) - if monkey is not None and method is not monkey: - return method class IPortalCatalogQueueProcessor(IIndexQueueProcessor): """ an index queue processor for the standard portal catalog via the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """ class PortalCatalogProcessor(object): implements(IPortalCatalogQueueProcessor) def index(self, obj, attributes=None): #index(obj, attributes) pass def reindex(self, obj, attributes=None): #reindex(obj, attributes) pass def unindex(self, obj): #unindex(obj) pass def begin(self): pass def commit(self): pass def abort(self): pass
Remove unused code for monkeyed methods
## Code Before: from zope.interface import implements #from Products.Archetypes.CatalogMultiplex import CatalogMultiplex #from Products.CMFCore.CMFCatalogAware import CMFCatalogAware from zerodb.collective.indexing.interfaces import IIndexQueueProcessor # container to hold references to the original and "monkeyed" indexing methods # these are populated by `collective.indexing.monkey` catalogMultiplexMethods = {} catalogAwareMethods = {} monkeyMethods = {} def getOwnIndexMethod(obj, name): """ return private indexing method if the given object has one """ attr = getattr(obj.__class__, name, None) if attr is not None: method = attr.im_func monkey = monkeyMethods.get(name.rstrip('Object'), None) if monkey is not None and method is not monkey: return method class IPortalCatalogQueueProcessor(IIndexQueueProcessor): """ an index queue processor for the standard portal catalog via the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """ class PortalCatalogProcessor(object): implements(IPortalCatalogQueueProcessor) def index(self, obj, attributes=None): #index(obj, attributes) pass def reindex(self, obj, attributes=None): #reindex(obj, attributes) pass def unindex(self, obj): #unindex(obj) pass def begin(self): pass def commit(self): pass def abort(self): pass ## Instruction: Remove unused code for monkeyed methods ## Code After: from zope.interface import implements from zerodb.collective.indexing.interfaces import IIndexQueueProcessor class IPortalCatalogQueueProcessor(IIndexQueueProcessor): """ an index queue processor for the standard portal catalog via the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """ class PortalCatalogProcessor(object): implements(IPortalCatalogQueueProcessor) def index(self, obj, attributes=None): #index(obj, attributes) pass def reindex(self, obj, attributes=None): #reindex(obj, attributes) pass def unindex(self, obj): #unindex(obj) pass def begin(self): pass def commit(self): pass def abort(self): pass
... from zope.interface import implements from zerodb.collective.indexing.interfaces import IIndexQueueProcessor ...
d328129a2f2909c1b8769f1edb94746c4a88dd28
test_project/test_models.py
test_project/test_models.py
from django.db import models class TestUser0(models.Model): username = models.CharField() test_field = models.CharField('My title') class Meta: app_label = 'controlcenter' def foo(self): return 'original foo value' foo.short_description = 'original foo label' def bar(self): return 'original bar value' bar.short_description = 'original bar label' def baz(self): pass baz.short_description = '' def egg(self): return 'original egg value' class TestUser1(models.Model): primary = models.AutoField(primary_key=True) username = models.CharField() class Meta: app_label = 'controlcenter'
from django.db import models class TestUser0(models.Model): username = models.CharField(max_length=255) test_field = models.CharField('My title', max_length=255) class Meta: app_label = 'controlcenter' def foo(self): return 'original foo value' foo.short_description = 'original foo label' def bar(self): return 'original bar value' bar.short_description = 'original bar label' def baz(self): pass baz.short_description = '' def egg(self): return 'original egg value' class TestUser1(models.Model): primary = models.AutoField(primary_key=True) username = models.CharField(max_length=255) class Meta: app_label = 'controlcenter'
Add `max_length` to char fields
Add `max_length` to char fields
Python
bsd-3-clause
byashimov/django-controlcenter,byashimov/django-controlcenter,byashimov/django-controlcenter
from django.db import models class TestUser0(models.Model): - username = models.CharField() + username = models.CharField(max_length=255) - test_field = models.CharField('My title') + test_field = models.CharField('My title', max_length=255) class Meta: app_label = 'controlcenter' def foo(self): return 'original foo value' foo.short_description = 'original foo label' def bar(self): return 'original bar value' bar.short_description = 'original bar label' def baz(self): pass baz.short_description = '' def egg(self): return 'original egg value' class TestUser1(models.Model): primary = models.AutoField(primary_key=True) - username = models.CharField() + username = models.CharField(max_length=255) class Meta: app_label = 'controlcenter'
Add `max_length` to char fields
## Code Before: from django.db import models class TestUser0(models.Model): username = models.CharField() test_field = models.CharField('My title') class Meta: app_label = 'controlcenter' def foo(self): return 'original foo value' foo.short_description = 'original foo label' def bar(self): return 'original bar value' bar.short_description = 'original bar label' def baz(self): pass baz.short_description = '' def egg(self): return 'original egg value' class TestUser1(models.Model): primary = models.AutoField(primary_key=True) username = models.CharField() class Meta: app_label = 'controlcenter' ## Instruction: Add `max_length` to char fields ## Code After: from django.db import models class TestUser0(models.Model): username = models.CharField(max_length=255) test_field = models.CharField('My title', max_length=255) class Meta: app_label = 'controlcenter' def foo(self): return 'original foo value' foo.short_description = 'original foo label' def bar(self): return 'original bar value' bar.short_description = 'original bar label' def baz(self): pass baz.short_description = '' def egg(self): return 'original egg value' class TestUser1(models.Model): primary = models.AutoField(primary_key=True) username = models.CharField(max_length=255) class Meta: app_label = 'controlcenter'
// ... existing code ... class TestUser0(models.Model): username = models.CharField(max_length=255) test_field = models.CharField('My title', max_length=255) // ... modified code ... primary = models.AutoField(primary_key=True) username = models.CharField(max_length=255) // ... rest of the code ...
31a9b285a0445c895aeff02b2abbeda12bf7f3d7
wagtail/admin/tests/pages/test_content_type_use_view.py
wagtail/admin/tests/pages/test_content_type_use_view.py
from django.test import TestCase from django.urls import reverse from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): self.user = self.login() def test_content_type_use(self): # Get use of event page response = self.client.get(reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage'))) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html') self.assertContains(response, "Christmas")
from django.test import TestCase from django.urls import reverse from django.utils.http import urlencode from wagtail.tests.testapp.models import EventPage from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): self.user = self.login() self.christmas_page = EventPage.objects.get(title="Christmas") def test_content_type_use(self): # Get use of event page request_url = reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage')) response = self.client.get(request_url) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html') self.assertContains(response, "Christmas") # Links to 'delete' etc should include a 'next' URL parameter pointing back here delete_url = ( reverse('wagtailadmin_pages:delete', args=(self.christmas_page.id,)) + '?' + urlencode({'next': request_url}) ) self.assertContains(response, delete_url)
Add test for button URLs including a 'next' parameter
Add test for button URLs including a 'next' parameter
Python
bsd-3-clause
torchbox/wagtail,FlipperPA/wagtail,gasman/wagtail,gasman/wagtail,mixxorz/wagtail,thenewguy/wagtail,mixxorz/wagtail,torchbox/wagtail,torchbox/wagtail,thenewguy/wagtail,gasman/wagtail,rsalmaso/wagtail,mixxorz/wagtail,wagtail/wagtail,takeflight/wagtail,FlipperPA/wagtail,torchbox/wagtail,zerolab/wagtail,thenewguy/wagtail,takeflight/wagtail,zerolab/wagtail,kaedroho/wagtail,wagtail/wagtail,zerolab/wagtail,thenewguy/wagtail,gasman/wagtail,rsalmaso/wagtail,kaedroho/wagtail,kaedroho/wagtail,thenewguy/wagtail,mixxorz/wagtail,zerolab/wagtail,jnns/wagtail,takeflight/wagtail,rsalmaso/wagtail,gasman/wagtail,FlipperPA/wagtail,wagtail/wagtail,wagtail/wagtail,zerolab/wagtail,rsalmaso/wagtail,kaedroho/wagtail,FlipperPA/wagtail,jnns/wagtail,jnns/wagtail,takeflight/wagtail,kaedroho/wagtail,mixxorz/wagtail,wagtail/wagtail,rsalmaso/wagtail,jnns/wagtail
from django.test import TestCase from django.urls import reverse + from django.utils.http import urlencode + from wagtail.tests.testapp.models import EventPage from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): self.user = self.login() + self.christmas_page = EventPage.objects.get(title="Christmas") def test_content_type_use(self): # Get use of event page - response = self.client.get(reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage'))) + request_url = reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage')) + response = self.client.get(request_url) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html') self.assertContains(response, "Christmas") + # Links to 'delete' etc should include a 'next' URL parameter pointing back here + delete_url = ( + reverse('wagtailadmin_pages:delete', args=(self.christmas_page.id,)) + + '?' + urlencode({'next': request_url}) + ) + self.assertContains(response, delete_url) +
Add test for button URLs including a 'next' parameter
## Code Before: from django.test import TestCase from django.urls import reverse from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): self.user = self.login() def test_content_type_use(self): # Get use of event page response = self.client.get(reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage'))) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html') self.assertContains(response, "Christmas") ## Instruction: Add test for button URLs including a 'next' parameter ## Code After: from django.test import TestCase from django.urls import reverse from django.utils.http import urlencode from wagtail.tests.testapp.models import EventPage from wagtail.tests.utils import WagtailTestUtils class TestContentTypeUse(TestCase, WagtailTestUtils): fixtures = ['test.json'] def setUp(self): self.user = self.login() self.christmas_page = EventPage.objects.get(title="Christmas") def test_content_type_use(self): # Get use of event page request_url = reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage')) response = self.client.get(request_url) # Check response self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'wagtailadmin/pages/content_type_use.html') self.assertContains(response, "Christmas") # Links to 'delete' etc should include a 'next' URL parameter pointing back here delete_url = ( reverse('wagtailadmin_pages:delete', args=(self.christmas_page.id,)) + '?' + urlencode({'next': request_url}) ) self.assertContains(response, delete_url)
# ... existing code ... from django.urls import reverse from django.utils.http import urlencode from wagtail.tests.testapp.models import EventPage from wagtail.tests.utils import WagtailTestUtils # ... modified code ... self.user = self.login() self.christmas_page = EventPage.objects.get(title="Christmas") ... # Get use of event page request_url = reverse('wagtailadmin_pages:type_use', args=('tests', 'eventpage')) response = self.client.get(request_url) ... self.assertContains(response, "Christmas") # Links to 'delete' etc should include a 'next' URL parameter pointing back here delete_url = ( reverse('wagtailadmin_pages:delete', args=(self.christmas_page.id,)) + '?' + urlencode({'next': request_url}) ) self.assertContains(response, delete_url) # ... rest of the code ...
ef8f869c5a254d2e3d84c3fa8829215da88681b4
djangocms_export_objects/tests/docs.py
djangocms_export_objects/tests/docs.py
from __future__ import with_statement import os import socket from sphinx.application import Sphinx from six import StringIO from .base import unittest from .tmpdir import temp_dir from unittest import skipIf ROOT_DIR = os.path.dirname(__file__) DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'..', u'docs')) def has_no_internet(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('4.4.4.2', 80)) s.send(b"hello") except socket.error: # no internet return True return False class DocsTestCase(unittest.TestCase): """ Test docs building correctly for HTML """ @skipIf(has_no_internet(), "No internet") def test_html(self): nullout = StringIO() with temp_dir() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=False, status=nullout, ) try: app.build() except: print(nullout.getvalue()) raise
from __future__ import with_statement import os import socket from sphinx.application import Sphinx from six import StringIO from .base import unittest from .tmpdir import temp_dir ROOT_DIR = os.path.dirname(__file__) DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'..', u'docs')) def has_no_internet(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('4.4.4.2', 80)) s.send(b"hello") except socket.error: # no internet return True return False class DocsTestCase(unittest.TestCase): """ Test docs building correctly for HTML """ @unittest.skipIf(has_no_internet(), "No internet") def test_html(self): nullout = StringIO() with temp_dir() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=False, status=nullout, ) try: app.build() except: print(nullout.getvalue()) raise
Fix build on python 2.6
Fix build on python 2.6
Python
bsd-3-clause
nephila/djangocms-export-objects,nephila/djangocms-export-objects
from __future__ import with_statement import os import socket from sphinx.application import Sphinx from six import StringIO from .base import unittest from .tmpdir import temp_dir - from unittest import skipIf ROOT_DIR = os.path.dirname(__file__) DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'..', u'docs')) def has_no_internet(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('4.4.4.2', 80)) s.send(b"hello") except socket.error: # no internet return True return False class DocsTestCase(unittest.TestCase): """ Test docs building correctly for HTML """ - @skipIf(has_no_internet(), "No internet") + @unittest.skipIf(has_no_internet(), "No internet") def test_html(self): nullout = StringIO() with temp_dir() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=False, status=nullout, ) try: app.build() except: print(nullout.getvalue()) raise
Fix build on python 2.6
## Code Before: from __future__ import with_statement import os import socket from sphinx.application import Sphinx from six import StringIO from .base import unittest from .tmpdir import temp_dir from unittest import skipIf ROOT_DIR = os.path.dirname(__file__) DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'..', u'docs')) def has_no_internet(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('4.4.4.2', 80)) s.send(b"hello") except socket.error: # no internet return True return False class DocsTestCase(unittest.TestCase): """ Test docs building correctly for HTML """ @skipIf(has_no_internet(), "No internet") def test_html(self): nullout = StringIO() with temp_dir() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=False, status=nullout, ) try: app.build() except: print(nullout.getvalue()) raise ## Instruction: Fix build on python 2.6 ## Code After: from __future__ import with_statement import os import socket from sphinx.application import Sphinx from six import StringIO from .base import unittest from .tmpdir import temp_dir ROOT_DIR = os.path.dirname(__file__) DOCS_DIR = os.path.abspath(os.path.join(ROOT_DIR, u'..', u'..', u'docs')) def has_no_internet(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('4.4.4.2', 80)) s.send(b"hello") except socket.error: # no internet return True return False class DocsTestCase(unittest.TestCase): """ Test docs building correctly for HTML """ @unittest.skipIf(has_no_internet(), "No internet") def test_html(self): nullout = StringIO() with temp_dir() as OUT_DIR: app = Sphinx( DOCS_DIR, DOCS_DIR, OUT_DIR, OUT_DIR, "html", warningiserror=False, status=nullout, ) try: app.build() except: print(nullout.getvalue()) raise
... from .tmpdir import temp_dir ... """ @unittest.skipIf(has_no_internet(), "No internet") def test_html(self): ...
fa78c5b5442c904ba3888b858eb2c284f16664ed
pages/urls/page.py
pages/urls/page.py
from django.conf.urls import include, patterns, url from rest_framework.routers import SimpleRouter from .. import views router = SimpleRouter(trailing_slash=False) router.register(r'pages', views.PageViewSet) urlpatterns = patterns('', url(r'', include(router.urls)), )
from django.conf.urls import include, url from rest_framework.routers import SimpleRouter from .. import views router = SimpleRouter(trailing_slash=False) router.register(r'pages', views.PageViewSet) urlpatterns = [ url(r'', include(router.urls)), ]
Purge unnecessary patterns function from urls
Purge unnecessary patterns function from urls
Python
bsd-2-clause
incuna/feincms-pages-api
- from django.conf.urls import include, patterns, url + from django.conf.urls import include, url from rest_framework.routers import SimpleRouter from .. import views router = SimpleRouter(trailing_slash=False) router.register(r'pages', views.PageViewSet) - urlpatterns = patterns('', + urlpatterns = [ url(r'', include(router.urls)), - ) + ]
Purge unnecessary patterns function from urls
## Code Before: from django.conf.urls import include, patterns, url from rest_framework.routers import SimpleRouter from .. import views router = SimpleRouter(trailing_slash=False) router.register(r'pages', views.PageViewSet) urlpatterns = patterns('', url(r'', include(router.urls)), ) ## Instruction: Purge unnecessary patterns function from urls ## Code After: from django.conf.urls import include, url from rest_framework.routers import SimpleRouter from .. import views router = SimpleRouter(trailing_slash=False) router.register(r'pages', views.PageViewSet) urlpatterns = [ url(r'', include(router.urls)), ]
// ... existing code ... from django.conf.urls import include, url // ... modified code ... urlpatterns = [ url(r'', include(router.urls)), ] // ... rest of the code ...
647707293524440f014ed0a3ef7d4322a96775e4
tests/example_app/flask_app.py
tests/example_app/flask_app.py
import flask from pale.adapters import flask as pale_flask_adapter from tests.example_app import api def create_pale_flask_app(): """Creates a flask app, and registers a blueprint bound to pale.""" blueprint = flask.Blueprint('api', 'tests.example_app') pale_flask_adapter.bind_blueprint(api, blueprint) app = flask.Flask(__name__) app.register_blueprint(blueprint, url_prefix='/api') return app
import flask from pale.adapters import flask as pale_flask_adapter from pale.config import authenticator, context_creator from tests.example_app import api @authenticator def authenticate_pale_context(context): """Don't actually authenticate anything in this test.""" return context @context_creator def create_pale_context(endpoint,request): return pale_flask_adapter.DefaultFlaskContext(endpoint, request) def create_pale_flask_app(): """Creates a flask app, and registers a blueprint bound to pale.""" blueprint = flask.Blueprint('api', 'tests.example_app') pale_flask_adapter.bind_blueprint(api, blueprint) app = flask.Flask(__name__) app.register_blueprint(blueprint, url_prefix='/api') return app
Add authenticator and context creator to example app
Add authenticator and context creator to example app
Python
mit
Loudr/pale
import flask from pale.adapters import flask as pale_flask_adapter + from pale.config import authenticator, context_creator from tests.example_app import api + + + @authenticator + def authenticate_pale_context(context): + """Don't actually authenticate anything in this test.""" + return context + + @context_creator + def create_pale_context(endpoint,request): + return pale_flask_adapter.DefaultFlaskContext(endpoint, request) def create_pale_flask_app(): """Creates a flask app, and registers a blueprint bound to pale.""" blueprint = flask.Blueprint('api', 'tests.example_app') pale_flask_adapter.bind_blueprint(api, blueprint) app = flask.Flask(__name__) app.register_blueprint(blueprint, url_prefix='/api') return app
Add authenticator and context creator to example app
## Code Before: import flask from pale.adapters import flask as pale_flask_adapter from tests.example_app import api def create_pale_flask_app(): """Creates a flask app, and registers a blueprint bound to pale.""" blueprint = flask.Blueprint('api', 'tests.example_app') pale_flask_adapter.bind_blueprint(api, blueprint) app = flask.Flask(__name__) app.register_blueprint(blueprint, url_prefix='/api') return app ## Instruction: Add authenticator and context creator to example app ## Code After: import flask from pale.adapters import flask as pale_flask_adapter from pale.config import authenticator, context_creator from tests.example_app import api @authenticator def authenticate_pale_context(context): """Don't actually authenticate anything in this test.""" return context @context_creator def create_pale_context(endpoint,request): return pale_flask_adapter.DefaultFlaskContext(endpoint, request) def create_pale_flask_app(): """Creates a flask app, and registers a blueprint bound to pale.""" blueprint = flask.Blueprint('api', 'tests.example_app') pale_flask_adapter.bind_blueprint(api, blueprint) app = flask.Flask(__name__) app.register_blueprint(blueprint, url_prefix='/api') return app
// ... existing code ... from pale.adapters import flask as pale_flask_adapter from pale.config import authenticator, context_creator // ... modified code ... from tests.example_app import api @authenticator def authenticate_pale_context(context): """Don't actually authenticate anything in this test.""" return context @context_creator def create_pale_context(endpoint,request): return pale_flask_adapter.DefaultFlaskContext(endpoint, request) // ... rest of the code ...
38aed64e1c20d25a6bda750a096a513b7d414c45
websod/views.py
websod/views.py
from werkzeug import redirect from werkzeug.exceptions import NotFound from websod.utils import session, expose, url_for, serve_template from websod.models import Integration from datetime import timedelta, datetime @expose('/') def home(request): # show results from last 3 days integrations_from = datetime.now() + timedelta(days=-3) from_str = integrations_from.strftime("%Y-%m-%d 00:00:00") latest_integrations = session.query(Integration).\ filter("started > '%s'" % from_str).\ order_by(Integration.started.desc()).all() return serve_template('home.html', latest_integrations=latest_integrations) @expose('/integration/<int:id>') def integration(request, id): integration = session.query(Integration).get(id) return serve_template('integration.html', integration=integration) @expose('/integration/') def integration_list(request): integrations = session.query(Integration).all() return serve_template('integration_list.html', integrations=integrations)
from werkzeug import redirect from werkzeug.exceptions import NotFound from websod.utils import session, expose, url_for, serve_template from websod.models import Integration from datetime import timedelta, datetime def home(request): # show results from last 3 days integrations_from = datetime.now() + timedelta(days=-3) from_str = integrations_from.strftime("%Y-%m-%d 00:00:00") latest_integrations = session.query(Integration).\ filter("started > '%s'" % from_str).\ order_by(Integration.started.desc()).all() return serve_template('home.html', latest_integrations=latest_integrations) @expose('/integration/<int:id>') def integration(request, id): integration = session.query(Integration).get(id) return serve_template('integration.html', integration=integration) @expose('/') @expose('/integration/') def integration_list(request): integrations = session.query(Integration).all() return serve_template('integration_list.html', integrations=integrations)
Set integrations for the index page now
Set integrations for the index page now
Python
mit
schettino72/serveronduty
from werkzeug import redirect from werkzeug.exceptions import NotFound from websod.utils import session, expose, url_for, serve_template from websod.models import Integration from datetime import timedelta, datetime - @expose('/') def home(request): # show results from last 3 days integrations_from = datetime.now() + timedelta(days=-3) from_str = integrations_from.strftime("%Y-%m-%d 00:00:00") latest_integrations = session.query(Integration).\ filter("started > '%s'" % from_str).\ order_by(Integration.started.desc()).all() return serve_template('home.html', latest_integrations=latest_integrations) @expose('/integration/<int:id>') def integration(request, id): integration = session.query(Integration).get(id) return serve_template('integration.html', integration=integration) + @expose('/') @expose('/integration/') def integration_list(request): integrations = session.query(Integration).all() return serve_template('integration_list.html', integrations=integrations)
Set integrations for the index page now
## Code Before: from werkzeug import redirect from werkzeug.exceptions import NotFound from websod.utils import session, expose, url_for, serve_template from websod.models import Integration from datetime import timedelta, datetime @expose('/') def home(request): # show results from last 3 days integrations_from = datetime.now() + timedelta(days=-3) from_str = integrations_from.strftime("%Y-%m-%d 00:00:00") latest_integrations = session.query(Integration).\ filter("started > '%s'" % from_str).\ order_by(Integration.started.desc()).all() return serve_template('home.html', latest_integrations=latest_integrations) @expose('/integration/<int:id>') def integration(request, id): integration = session.query(Integration).get(id) return serve_template('integration.html', integration=integration) @expose('/integration/') def integration_list(request): integrations = session.query(Integration).all() return serve_template('integration_list.html', integrations=integrations) ## Instruction: Set integrations for the index page now ## Code After: from werkzeug import redirect from werkzeug.exceptions import NotFound from websod.utils import session, expose, url_for, serve_template from websod.models import Integration from datetime import timedelta, datetime def home(request): # show results from last 3 days integrations_from = datetime.now() + timedelta(days=-3) from_str = integrations_from.strftime("%Y-%m-%d 00:00:00") latest_integrations = session.query(Integration).\ filter("started > '%s'" % from_str).\ order_by(Integration.started.desc()).all() return serve_template('home.html', latest_integrations=latest_integrations) @expose('/integration/<int:id>') def integration(request, id): integration = session.query(Integration).get(id) return serve_template('integration.html', integration=integration) @expose('/') @expose('/integration/') def integration_list(request): integrations = session.query(Integration).all() return serve_template('integration_list.html', integrations=integrations)
... def home(request): ... @expose('/') @expose('/integration/') ...
80b882b3a790241d3d67ae190b0e32d7e9d7b8ed
mesonwrap/inventory.py
mesonwrap/inventory.py
_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonbuild.github.io', 'mesonwrap', 'wrapdb', 'wrapdevtools', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS
_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'dubtestproject', 'meson', 'meson-ci', 'mesonbuild.github.io', 'mesonwrap', 'wrapdb', 'wrapdevtools', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS
Add dubtestproject to the list of restricted projects
Add dubtestproject to the list of restricted projects
Python
apache-2.0
mesonbuild/wrapweb,mesonbuild/wrapweb,mesonbuild/wrapweb
_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ + 'dubtestproject', 'meson', 'meson-ci', 'mesonbuild.github.io', 'mesonwrap', 'wrapdb', 'wrapdevtools', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS
Add dubtestproject to the list of restricted projects
## Code Before: _ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonbuild.github.io', 'mesonwrap', 'wrapdb', 'wrapdevtools', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS ## Instruction: Add dubtestproject to the list of restricted projects ## Code After: _ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'dubtestproject', 'meson', 'meson-ci', 'mesonbuild.github.io', 'mesonwrap', 'wrapdb', 'wrapdevtools', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS
... _RESTRICTED_PROJECTS = [ 'dubtestproject', 'meson', ...
8528f21397672b5719fcf4edecd8efa3a1eec60a
cellardoor/serializers/json_serializer.py
cellardoor/serializers/json_serializer.py
import re import json from datetime import datetime from . import Serializer class CellarDoorJSONEncoder(json.JSONEncoder): def default(self, obj): try: iterable = iter(obj) except TypeError: pass else: return list(iterable) if isinstance(obj, datetime): return obj.isoformat() return super(CellarDoorJSONEncoder, self).default(obj) def as_date(obj): if '_date' in obj: return datetime(*map(int, re.split('[^\d]', obj['_date'])[:-1])) else: return obj class JSONSerializer(Serializer): mimetype = 'application/json' def serialize(self, obj): return json.dumps(obj, cls=CellarDoorJSONEncoder) def unserialize(self, stream): return json.load(stream, object_hook=as_date) def unserialize_string(self, data): return json.loads(data, object_hook=as_date)
import re import json from datetime import datetime import collections from . import Serializer class CellarDoorJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, collections.Iterable): return list(obj) if isinstance(obj, datetime): return obj.isoformat() return super(CellarDoorJSONEncoder, self).default(obj) def as_date(obj): if '_date' in obj: return datetime(*map(int, re.split('[^\d]', obj['_date'])[:-1])) else: return obj class JSONSerializer(Serializer): mimetype = 'application/json' def serialize(self, obj): return json.dumps(obj, cls=CellarDoorJSONEncoder) def unserialize(self, stream): return json.load(stream, object_hook=as_date) def unserialize_string(self, data): return json.loads(data, object_hook=as_date)
Use more reliable method of detecting iterables
Use more reliable method of detecting iterables
Python
mit
cooper-software/cellardoor
import re import json from datetime import datetime + import collections from . import Serializer class CellarDoorJSONEncoder(json.JSONEncoder): def default(self, obj): + if isinstance(obj, collections.Iterable): - try: - iterable = iter(obj) - except TypeError: - pass - else: - return list(iterable) + return list(obj) if isinstance(obj, datetime): return obj.isoformat() return super(CellarDoorJSONEncoder, self).default(obj) def as_date(obj): if '_date' in obj: return datetime(*map(int, re.split('[^\d]', obj['_date'])[:-1])) else: return obj class JSONSerializer(Serializer): mimetype = 'application/json' def serialize(self, obj): return json.dumps(obj, cls=CellarDoorJSONEncoder) def unserialize(self, stream): return json.load(stream, object_hook=as_date) def unserialize_string(self, data): return json.loads(data, object_hook=as_date)
Use more reliable method of detecting iterables
## Code Before: import re import json from datetime import datetime from . import Serializer class CellarDoorJSONEncoder(json.JSONEncoder): def default(self, obj): try: iterable = iter(obj) except TypeError: pass else: return list(iterable) if isinstance(obj, datetime): return obj.isoformat() return super(CellarDoorJSONEncoder, self).default(obj) def as_date(obj): if '_date' in obj: return datetime(*map(int, re.split('[^\d]', obj['_date'])[:-1])) else: return obj class JSONSerializer(Serializer): mimetype = 'application/json' def serialize(self, obj): return json.dumps(obj, cls=CellarDoorJSONEncoder) def unserialize(self, stream): return json.load(stream, object_hook=as_date) def unserialize_string(self, data): return json.loads(data, object_hook=as_date) ## Instruction: Use more reliable method of detecting iterables ## Code After: import re import json from datetime import datetime import collections from . import Serializer class CellarDoorJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, collections.Iterable): return list(obj) if isinstance(obj, datetime): return obj.isoformat() return super(CellarDoorJSONEncoder, self).default(obj) def as_date(obj): if '_date' in obj: return datetime(*map(int, re.split('[^\d]', obj['_date'])[:-1])) else: return obj class JSONSerializer(Serializer): mimetype = 'application/json' def serialize(self, obj): return json.dumps(obj, cls=CellarDoorJSONEncoder) def unserialize(self, stream): return json.load(stream, object_hook=as_date) def unserialize_string(self, data): return json.loads(data, object_hook=as_date)
// ... existing code ... from datetime import datetime import collections // ... modified code ... def default(self, obj): if isinstance(obj, collections.Iterable): return list(obj) // ... rest of the code ...
835aa149e4bccd7bcf94390d1a878133b79b768f
yaacl/models.py
yaacl/models.py
from datetime import datetime from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class ACL(models.Model): acl_list = {} resource = models.CharField( _("Resource name"), max_length=255, db_index=True, ) display = models.CharField( _("displayed name"), max_length=255, null=True, blank=True, ) created_at = models.DateTimeField( _("Creation time"), default=datetime.now(), ) is_available = models.BooleanField( _("Is available to assign"), default=True, ) class Meta: app_label = 'yaacl' def __str__(self): if self.display: return "%s (%s)" % (self.display, self.resource) else: return self.resource
from datetime import datetime from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class ACL(models.Model): acl_list = {} resource = models.CharField( _("Resource name"), max_length=255, db_index=True, ) display = models.CharField( _("displayed name"), max_length=255, null=True, blank=True, ) created_at = models.DateTimeField( _("Creation time"), auto_now_add=True, ) is_available = models.BooleanField( _("Is available to assign"), default=True, ) class Meta: app_label = 'yaacl' def __str__(self): if self.display: return "%s (%s)" % (self.display, self.resource) else: return self.resource
Use `auto_now_add` to make ACL.created_at timezone aware
Use `auto_now_add` to make ACL.created_at timezone aware
Python
mit
Alkemic/yaACL,Alkemic/yaACL
from datetime import datetime from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class ACL(models.Model): acl_list = {} resource = models.CharField( _("Resource name"), max_length=255, db_index=True, ) display = models.CharField( _("displayed name"), max_length=255, null=True, blank=True, ) created_at = models.DateTimeField( _("Creation time"), - default=datetime.now(), + auto_now_add=True, ) is_available = models.BooleanField( _("Is available to assign"), default=True, ) class Meta: app_label = 'yaacl' def __str__(self): if self.display: return "%s (%s)" % (self.display, self.resource) else: return self.resource
Use `auto_now_add` to make ACL.created_at timezone aware
## Code Before: from datetime import datetime from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class ACL(models.Model): acl_list = {} resource = models.CharField( _("Resource name"), max_length=255, db_index=True, ) display = models.CharField( _("displayed name"), max_length=255, null=True, blank=True, ) created_at = models.DateTimeField( _("Creation time"), default=datetime.now(), ) is_available = models.BooleanField( _("Is available to assign"), default=True, ) class Meta: app_label = 'yaacl' def __str__(self): if self.display: return "%s (%s)" % (self.display, self.resource) else: return self.resource ## Instruction: Use `auto_now_add` to make ACL.created_at timezone aware ## Code After: from datetime import datetime from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class ACL(models.Model): acl_list = {} resource = models.CharField( _("Resource name"), max_length=255, db_index=True, ) display = models.CharField( _("displayed name"), max_length=255, null=True, blank=True, ) created_at = models.DateTimeField( _("Creation time"), auto_now_add=True, ) is_available = models.BooleanField( _("Is available to assign"), default=True, ) class Meta: app_label = 'yaacl' def __str__(self): if self.display: return "%s (%s)" % (self.display, self.resource) else: return self.resource
# ... existing code ... _("Creation time"), auto_now_add=True, ) # ... rest of the code ...
5503a615db51a6ae0461cc0417c61ba508a43eae
ufyr/storage/utils.py
ufyr/storage/utils.py
from os import chmod, unlink, stat, makedirs from os.path import isfile, split, exists from shutil import copyfile def move_verify_delete(in_file, out_file): ''' Moves in_file to out_file, verifies that the filesizes are the same and then does a chmod 666 ''' if not exists(split(out_file)[0]): makedirs(split(out_file)[0]) if isfile(in_file) and not isfile(out_file): orig_file_size = stat(in_file).st_size copyfile(in_file, out_file) new_file_size = stat(out_file).st_size if new_file_size != orig_file_size: raise Exception('File Transfer Error! %s:%d -> %s:%d'%(in_file, orig_file_size, out_file, new_file_size)) unlink(in_file) #chmod(out_file, 666) else: raise Exception('File Transfer Error! %s EXISTS %s %s EXISTS %s'%(in_file, isfile(in_file), out_file, isfile(out_file)))
from os import chmod, unlink, stat, makedirs from os.path import isfile, split, exists from shutil import copyfile def move_verify_delete(in_file, out_file, overwrite=False): ''' Moves in_file to out_file, verifies that the filesizes are the same and then does a chmod 666 ''' if not exists(split(out_file)[0]): makedirs(split(out_file)[0]) if isfile(in_file) and (overwrite or not isfile(out_file)): orig_file_size = stat(in_file).st_size copyfile(in_file, out_file) new_file_size = stat(out_file).st_size if new_file_size != orig_file_size: raise Exception('File Transfer Error! %s:%d -> %s:%d'%(in_file, orig_file_size, out_file, new_file_size)) unlink(in_file) #chmod(out_file, 666) else: raise Exception('File Transfer Error! %s EXISTS %s %s EXISTS %s'%(in_file, isfile(in_file), out_file, isfile(out_file)))
Add in overwrite output file
Add in overwrite output file
Python
unlicense
timeartist/ufyr
from os import chmod, unlink, stat, makedirs from os.path import isfile, split, exists from shutil import copyfile - def move_verify_delete(in_file, out_file): + def move_verify_delete(in_file, out_file, overwrite=False): ''' Moves in_file to out_file, verifies that the filesizes are the same and then does a chmod 666 ''' if not exists(split(out_file)[0]): makedirs(split(out_file)[0]) - if isfile(in_file) and not isfile(out_file): + if isfile(in_file) and (overwrite or not isfile(out_file)): orig_file_size = stat(in_file).st_size copyfile(in_file, out_file) new_file_size = stat(out_file).st_size if new_file_size != orig_file_size: raise Exception('File Transfer Error! %s:%d -> %s:%d'%(in_file, orig_file_size, out_file, new_file_size)) unlink(in_file) #chmod(out_file, 666) else: raise Exception('File Transfer Error! %s EXISTS %s %s EXISTS %s'%(in_file, isfile(in_file), out_file, isfile(out_file)))
Add in overwrite output file
## Code Before: from os import chmod, unlink, stat, makedirs from os.path import isfile, split, exists from shutil import copyfile def move_verify_delete(in_file, out_file): ''' Moves in_file to out_file, verifies that the filesizes are the same and then does a chmod 666 ''' if not exists(split(out_file)[0]): makedirs(split(out_file)[0]) if isfile(in_file) and not isfile(out_file): orig_file_size = stat(in_file).st_size copyfile(in_file, out_file) new_file_size = stat(out_file).st_size if new_file_size != orig_file_size: raise Exception('File Transfer Error! %s:%d -> %s:%d'%(in_file, orig_file_size, out_file, new_file_size)) unlink(in_file) #chmod(out_file, 666) else: raise Exception('File Transfer Error! %s EXISTS %s %s EXISTS %s'%(in_file, isfile(in_file), out_file, isfile(out_file))) ## Instruction: Add in overwrite output file ## Code After: from os import chmod, unlink, stat, makedirs from os.path import isfile, split, exists from shutil import copyfile def move_verify_delete(in_file, out_file, overwrite=False): ''' Moves in_file to out_file, verifies that the filesizes are the same and then does a chmod 666 ''' if not exists(split(out_file)[0]): makedirs(split(out_file)[0]) if isfile(in_file) and (overwrite or not isfile(out_file)): orig_file_size = stat(in_file).st_size copyfile(in_file, out_file) new_file_size = stat(out_file).st_size if new_file_size != orig_file_size: raise Exception('File Transfer Error! %s:%d -> %s:%d'%(in_file, orig_file_size, out_file, new_file_size)) unlink(in_file) #chmod(out_file, 666) else: raise Exception('File Transfer Error! %s EXISTS %s %s EXISTS %s'%(in_file, isfile(in_file), out_file, isfile(out_file)))
// ... existing code ... def move_verify_delete(in_file, out_file, overwrite=False): ''' // ... modified code ... if isfile(in_file) and (overwrite or not isfile(out_file)): orig_file_size = stat(in_file).st_size // ... rest of the code ...
a017c75c7e2b8915cd2ab0bce29a0ed68c306f38
get_data.py
get_data.py
import urllib, json import numpy as np from secrets import API_KEY # JCDECAUX's API KEY def retrieve_data(contract="paris"): url = "https://api.jcdecaux.com/vls/v1/stations?apiKey={}&contract={}".format(API_KEY, contract) response = urllib.urlopen(url) data = json.loads(response.read()) return data def extract_data(data): y = -np.array([p['position']['lat'] for p in data]) x = np.array([p['position']['lng'] for p in data]) st_free = np.array([p['available_bike_stands'] for p in data]).astype(np.float32) st_busy = np.array([p['available_bikes'] for p in data]).astype(np.float32) return (x, y), (st_free, st_busy)
import urllib, json import numpy as np import time from secrets import API_KEY # JCDECAUX's API KEY def retrieve_data(contract="paris"): url = "https://api.jcdecaux.com/vls/v1/stations?apiKey={}&contract={}".format(API_KEY, contract) response = urllib.urlopen(url) data = json.loads(response.read()) return data def extract_data(data): y = -np.array([p['position']['lat'] for p in data]) x = np.array([p['position']['lng'] for p in data]) st_free = np.array([p['available_bike_stands'] for p in data]).astype(np.float32) st_busy = np.array([p['available_bikes'] for p in data]).astype(np.float32) return (x, y), (st_free, st_busy) def save_data(data, ofile="output/data.npy"): np.save(ofile, data) if __name__ == '__main__': data = extract_data(retrieve_data()) save_data(data, 'output/{}.npy'.format(int(time.time())))
Save the data fron cron
Save the data fron cron
Python
mit
Evarin/velib-exp
import urllib, json import numpy as np + import time from secrets import API_KEY # JCDECAUX's API KEY def retrieve_data(contract="paris"): url = "https://api.jcdecaux.com/vls/v1/stations?apiKey={}&contract={}".format(API_KEY, contract) response = urllib.urlopen(url) data = json.loads(response.read()) return data def extract_data(data): y = -np.array([p['position']['lat'] for p in data]) x = np.array([p['position']['lng'] for p in data]) st_free = np.array([p['available_bike_stands'] for p in data]).astype(np.float32) st_busy = np.array([p['available_bikes'] for p in data]).astype(np.float32) return (x, y), (st_free, st_busy) + def save_data(data, ofile="output/data.npy"): + np.save(ofile, data) + + if __name__ == '__main__': + data = extract_data(retrieve_data()) + save_data(data, 'output/{}.npy'.format(int(time.time()))) +
Save the data fron cron
## Code Before: import urllib, json import numpy as np from secrets import API_KEY # JCDECAUX's API KEY def retrieve_data(contract="paris"): url = "https://api.jcdecaux.com/vls/v1/stations?apiKey={}&contract={}".format(API_KEY, contract) response = urllib.urlopen(url) data = json.loads(response.read()) return data def extract_data(data): y = -np.array([p['position']['lat'] for p in data]) x = np.array([p['position']['lng'] for p in data]) st_free = np.array([p['available_bike_stands'] for p in data]).astype(np.float32) st_busy = np.array([p['available_bikes'] for p in data]).astype(np.float32) return (x, y), (st_free, st_busy) ## Instruction: Save the data fron cron ## Code After: import urllib, json import numpy as np import time from secrets import API_KEY # JCDECAUX's API KEY def retrieve_data(contract="paris"): url = "https://api.jcdecaux.com/vls/v1/stations?apiKey={}&contract={}".format(API_KEY, contract) response = urllib.urlopen(url) data = json.loads(response.read()) return data def extract_data(data): y = -np.array([p['position']['lat'] for p in data]) x = np.array([p['position']['lng'] for p in data]) st_free = np.array([p['available_bike_stands'] for p in data]).astype(np.float32) st_busy = np.array([p['available_bikes'] for p in data]).astype(np.float32) return (x, y), (st_free, st_busy) def save_data(data, ofile="output/data.npy"): np.save(ofile, data) if __name__ == '__main__': data = extract_data(retrieve_data()) save_data(data, 'output/{}.npy'.format(int(time.time())))
# ... existing code ... import numpy as np import time # ... modified code ... return (x, y), (st_free, st_busy) def save_data(data, ofile="output/data.npy"): np.save(ofile, data) if __name__ == '__main__': data = extract_data(retrieve_data()) save_data(data, 'output/{}.npy'.format(int(time.time()))) # ... rest of the code ...