commit
stringlengths
40
40
old_file
stringlengths
4
106
new_file
stringlengths
4
106
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
2.95k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
43k
ndiff
stringlengths
52
3.31k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
diff
stringlengths
49
3.61k
6160da958f4b8ecb1553c7bcca0b32bc1a5a1649
tests/conftest.py
tests/conftest.py
import os import shutil import tempfile import builtins import subprocess import pytest from rever import environ @pytest.fixture def gitrepo(request): """A test fixutre that creates and destroys a git repo in a temporary directory. This will yield the path to the repo. """ cwd = os.getcwd() name = request.node.name repo = os.path.join(tempfile.gettempdir(), name) if os.path.exists(repo): shutil.rmtree(repo) subprocess.run(['git', 'init', repo]) os.chdir(repo) with open('README', 'w') as f: f.write('testing ' + name) subprocess.run(['git', 'add', '.']) subprocess.run(['git', 'commit', '-am', 'Initial readme']) with environ.context(): yield repo os.chdir(cwd) shutil.rmtree(repo) @pytest.fixture def gitecho(request): aliases = builtins.aliases aliases['git'] = lambda args: 'Would have run: ' + ' '.join(args) + '\n' yield None del aliases['git']
import os import shutil import tempfile import builtins import subprocess import pytest import sys from rever import environ @pytest.fixture def gitrepo(request): """A test fixutre that creates and destroys a git repo in a temporary directory. This will yield the path to the repo. """ cwd = os.getcwd() name = request.node.name repo = os.path.join(tempfile.gettempdir(), name) if os.path.exists(repo): rmtree(repo) subprocess.run(['git', 'init', repo]) os.chdir(repo) with open('README', 'w') as f: f.write('testing ' + name) subprocess.run(['git', 'add', '.']) subprocess.run(['git', 'commit', '-am', 'Initial readme']) with environ.context(): yield repo os.chdir(cwd) rmtree(repo) @pytest.fixture def gitecho(request): aliases = builtins.aliases aliases['git'] = lambda args: 'Would have run: ' + ' '.join(args) + '\n' yield None del aliases['git'] def rmtree(dirname): """Remove a directory, even if it has read-only files (Windows). Git creates read-only files that must be removed on teardown. See https://stackoverflow.com/questions/2656322 for more info. Parameters ---------- dirname : str Directory to be removed """ try: shutil.rmtree(dirname) except PermissionError: if sys.platform == 'win32': subprocess.check_call(['del', '/F/S/Q', dirname], shell=True) else: raise
Make sure .git test directory is removed on Windows
Make sure .git test directory is removed on Windows
Python
bsd-3-clause
scopatz/rever,ergs/rever
import os import shutil import tempfile import builtins import subprocess import pytest + import sys from rever import environ @pytest.fixture def gitrepo(request): """A test fixutre that creates and destroys a git repo in a temporary directory. This will yield the path to the repo. """ cwd = os.getcwd() name = request.node.name repo = os.path.join(tempfile.gettempdir(), name) if os.path.exists(repo): - shutil.rmtree(repo) + rmtree(repo) subprocess.run(['git', 'init', repo]) os.chdir(repo) with open('README', 'w') as f: f.write('testing ' + name) subprocess.run(['git', 'add', '.']) subprocess.run(['git', 'commit', '-am', 'Initial readme']) with environ.context(): yield repo os.chdir(cwd) - shutil.rmtree(repo) + rmtree(repo) @pytest.fixture def gitecho(request): aliases = builtins.aliases aliases['git'] = lambda args: 'Would have run: ' + ' '.join(args) + '\n' yield None del aliases['git'] + + def rmtree(dirname): + """Remove a directory, even if it has read-only files (Windows). + Git creates read-only files that must be removed on teardown. See + https://stackoverflow.com/questions/2656322 for more info. + + Parameters + ---------- + dirname : str + Directory to be removed + """ + try: + shutil.rmtree(dirname) + except PermissionError: + if sys.platform == 'win32': + subprocess.check_call(['del', '/F/S/Q', dirname], shell=True) + else: + raise +
Make sure .git test directory is removed on Windows
## Code Before: import os import shutil import tempfile import builtins import subprocess import pytest from rever import environ @pytest.fixture def gitrepo(request): """A test fixutre that creates and destroys a git repo in a temporary directory. This will yield the path to the repo. """ cwd = os.getcwd() name = request.node.name repo = os.path.join(tempfile.gettempdir(), name) if os.path.exists(repo): shutil.rmtree(repo) subprocess.run(['git', 'init', repo]) os.chdir(repo) with open('README', 'w') as f: f.write('testing ' + name) subprocess.run(['git', 'add', '.']) subprocess.run(['git', 'commit', '-am', 'Initial readme']) with environ.context(): yield repo os.chdir(cwd) shutil.rmtree(repo) @pytest.fixture def gitecho(request): aliases = builtins.aliases aliases['git'] = lambda args: 'Would have run: ' + ' '.join(args) + '\n' yield None del aliases['git'] ## Instruction: Make sure .git test directory is removed on Windows ## Code After: import os import shutil import tempfile import builtins import subprocess import pytest import sys from rever import environ @pytest.fixture def gitrepo(request): """A test fixutre that creates and destroys a git repo in a temporary directory. This will yield the path to the repo. """ cwd = os.getcwd() name = request.node.name repo = os.path.join(tempfile.gettempdir(), name) if os.path.exists(repo): rmtree(repo) subprocess.run(['git', 'init', repo]) os.chdir(repo) with open('README', 'w') as f: f.write('testing ' + name) subprocess.run(['git', 'add', '.']) subprocess.run(['git', 'commit', '-am', 'Initial readme']) with environ.context(): yield repo os.chdir(cwd) rmtree(repo) @pytest.fixture def gitecho(request): aliases = builtins.aliases aliases['git'] = lambda args: 'Would have run: ' + ' '.join(args) + '\n' yield None del aliases['git'] def rmtree(dirname): """Remove a directory, even if it has read-only files (Windows). Git creates read-only files that must be removed on teardown. See https://stackoverflow.com/questions/2656322 for more info. Parameters ---------- dirname : str Directory to be removed """ try: shutil.rmtree(dirname) except PermissionError: if sys.platform == 'win32': subprocess.check_call(['del', '/F/S/Q', dirname], shell=True) else: raise
import os import shutil import tempfile import builtins import subprocess import pytest + import sys from rever import environ @pytest.fixture def gitrepo(request): """A test fixutre that creates and destroys a git repo in a temporary directory. This will yield the path to the repo. """ cwd = os.getcwd() name = request.node.name repo = os.path.join(tempfile.gettempdir(), name) if os.path.exists(repo): - shutil.rmtree(repo) ? ------- + rmtree(repo) subprocess.run(['git', 'init', repo]) os.chdir(repo) with open('README', 'w') as f: f.write('testing ' + name) subprocess.run(['git', 'add', '.']) subprocess.run(['git', 'commit', '-am', 'Initial readme']) with environ.context(): yield repo os.chdir(cwd) - shutil.rmtree(repo) ? ------- + rmtree(repo) @pytest.fixture def gitecho(request): aliases = builtins.aliases aliases['git'] = lambda args: 'Would have run: ' + ' '.join(args) + '\n' yield None del aliases['git'] + + + def rmtree(dirname): + """Remove a directory, even if it has read-only files (Windows). + Git creates read-only files that must be removed on teardown. See + https://stackoverflow.com/questions/2656322 for more info. + + Parameters + ---------- + dirname : str + Directory to be removed + """ + try: + shutil.rmtree(dirname) + except PermissionError: + if sys.platform == 'win32': + subprocess.check_call(['del', '/F/S/Q', dirname], shell=True) + else: + raise
6e6c60613180bb3d7e2d019129e57d1a2c33286d
backend/backend/models.py
backend/backend/models.py
from django.db import models class Animal(models.Model): MALE = 'male' FEMALE = 'female' GENDER_CHOICES = ((MALE, 'Male'), (FEMALE, 'Female')) father = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_father") mother = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_mother") name = models.CharField(max_length = 100) dob = models.IntegerField() gender = models.CharField(max_length = 6, choices = GENDER_CHOICES, default = FEMALE) active = models.BooleanField() own = models.BooleanField() class Meta: unique_together = ("name", "dob")
from django.db import models from django.core.validators import MaxValueValidator, MaxLengthValidator from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from datetime import datetime def current_year(): return datetime.now().year class Animal(models.Model): MALE = 'male' FEMALE = 'female' GENDER_CHOICES = ((MALE, 'Male'), (FEMALE, 'Female')) father = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_father") mother = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_mother") name = models.CharField(max_length = 100, validators = [MaxLengthValidator(100)]) dob = models.IntegerField(validators = [MaxValueValidator(current_year())]) gender = models.CharField(max_length = 6, choices = GENDER_CHOICES, default = FEMALE) active = models.BooleanField() own = models.BooleanField() class Meta: unique_together = ("name", "dob")
Add length validator to name. Add dob validator can't be higher than current year.
Add length validator to name. Add dob validator can't be higher than current year.
Python
apache-2.0
mmlado/animal_pairing,mmlado/animal_pairing
from django.db import models + from django.core.validators import MaxValueValidator, MaxLengthValidator + from django.core.exceptions import ValidationError + from django.utils.translation import gettext_lazy as _ + from datetime import datetime + + def current_year(): + return datetime.now().year class Animal(models.Model): MALE = 'male' FEMALE = 'female' GENDER_CHOICES = ((MALE, 'Male'), (FEMALE, 'Female')) father = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_father") mother = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_mother") - name = models.CharField(max_length = 100) - dob = models.IntegerField() + name = models.CharField(max_length = 100, validators = [MaxLengthValidator(100)]) + dob = models.IntegerField(validators = [MaxValueValidator(current_year())]) gender = models.CharField(max_length = 6, choices = GENDER_CHOICES, default = FEMALE) active = models.BooleanField() own = models.BooleanField() class Meta: unique_together = ("name", "dob")
Add length validator to name. Add dob validator can't be higher than current year.
## Code Before: from django.db import models class Animal(models.Model): MALE = 'male' FEMALE = 'female' GENDER_CHOICES = ((MALE, 'Male'), (FEMALE, 'Female')) father = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_father") mother = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_mother") name = models.CharField(max_length = 100) dob = models.IntegerField() gender = models.CharField(max_length = 6, choices = GENDER_CHOICES, default = FEMALE) active = models.BooleanField() own = models.BooleanField() class Meta: unique_together = ("name", "dob") ## Instruction: Add length validator to name. Add dob validator can't be higher than current year. ## Code After: from django.db import models from django.core.validators import MaxValueValidator, MaxLengthValidator from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from datetime import datetime def current_year(): return datetime.now().year class Animal(models.Model): MALE = 'male' FEMALE = 'female' GENDER_CHOICES = ((MALE, 'Male'), (FEMALE, 'Female')) father = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_father") mother = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_mother") name = models.CharField(max_length = 100, validators = [MaxLengthValidator(100)]) dob = models.IntegerField(validators = [MaxValueValidator(current_year())]) gender = models.CharField(max_length = 6, choices = GENDER_CHOICES, default = FEMALE) active = models.BooleanField() own = models.BooleanField() class Meta: unique_together = ("name", "dob")
from django.db import models + from django.core.validators import MaxValueValidator, MaxLengthValidator + from django.core.exceptions import ValidationError + from django.utils.translation import gettext_lazy as _ + from datetime import datetime + + def current_year(): + return datetime.now().year class Animal(models.Model): MALE = 'male' FEMALE = 'female' GENDER_CHOICES = ((MALE, 'Male'), (FEMALE, 'Female')) father = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_father") mother = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_mother") - name = models.CharField(max_length = 100) - dob = models.IntegerField() + name = models.CharField(max_length = 100, validators = [MaxLengthValidator(100)]) + dob = models.IntegerField(validators = [MaxValueValidator(current_year())]) gender = models.CharField(max_length = 6, choices = GENDER_CHOICES, default = FEMALE) active = models.BooleanField() own = models.BooleanField() class Meta: unique_together = ("name", "dob")
8b51c9904fd09354ff5385fc1740d9270da8287c
should-I-boot-this.py
should-I-boot-this.py
import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Check if we need to stop here if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0)
import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Is the lab existing? if os.environ['LAB'] not in config.sections(): print("Unknown lab (%s). Allowing boot of %s." % (os.environ['LAB'], os.environ['TREE'])) sys.exit(0) # Is the tree blacklisted for this lab? if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0)
Allow boots for unknown labs
jenkins: Allow boots for unknown labs Signed-off-by: Florent Jacquet <692930aa2e4df70616939784b5b6c25eb1f2335c@free-electrons.com>
Python
lgpl-2.1
kernelci/lava-ci-staging,kernelci/lava-ci-staging,kernelci/lava-ci-staging
import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') - # Check if we need to stop here + # Is the lab existing? + if os.environ['LAB'] not in config.sections(): + print("Unknown lab (%s). Allowing boot of %s." % (os.environ['LAB'], os.environ['TREE'])) + sys.exit(0) + + # Is the tree blacklisted for this lab? if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0)
Allow boots for unknown labs
## Code Before: import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Check if we need to stop here if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0) ## Instruction: Allow boots for unknown labs ## Code After: import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Is the lab existing? if os.environ['LAB'] not in config.sections(): print("Unknown lab (%s). Allowing boot of %s." % (os.environ['LAB'], os.environ['TREE'])) sys.exit(0) # Is the tree blacklisted for this lab? if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0)
import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') - # Check if we need to stop here + # Is the lab existing? + if os.environ['LAB'] not in config.sections(): + print("Unknown lab (%s). Allowing boot of %s." % (os.environ['LAB'], os.environ['TREE'])) + sys.exit(0) + + # Is the tree blacklisted for this lab? if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0)
ca0d9b40442f3ca9499f4b1630650c61700668ec
tests/conftest.py
tests/conftest.py
import os import warnings import pytest pytest_plugins = 'pytester' @pytest.fixture(scope='session', autouse=True) def verify_target_path(): import pytest_testdox current_path_root = os.path.dirname( os.path.dirname(os.path.realpath(__file__)) ) if current_path_root not in pytest_testdox.__file__: warnings.warn( 'pytest-testdox was not imported from your repository. ' 'You might be testing the wrong code ' '-- More: https://github.com/renanivo/pytest-testdox/issues/13', UserWarning )
import os import warnings import pytest pytest_plugins = 'pytester' @pytest.fixture(scope='session', autouse=True) def verify_target_path(): import pytest_testdox current_path_root = os.path.dirname( os.path.dirname(os.path.realpath(__file__)) ) if current_path_root not in pytest_testdox.__file__: warnings.warn( 'pytest-testdox was not imported from your repository. ' 'You might be testing the wrong code. ' 'Uninstall pytest-testdox to be able to run all test cases ' '-- More: https://github.com/renanivo/pytest-testdox/issues/13', UserWarning )
Add the action required to fix the issue to the warning
Add the action required to fix the issue to the warning
Python
mit
renanivo/pytest-testdox
import os import warnings import pytest pytest_plugins = 'pytester' @pytest.fixture(scope='session', autouse=True) def verify_target_path(): import pytest_testdox current_path_root = os.path.dirname( os.path.dirname(os.path.realpath(__file__)) ) if current_path_root not in pytest_testdox.__file__: warnings.warn( 'pytest-testdox was not imported from your repository. ' - 'You might be testing the wrong code ' + 'You might be testing the wrong code. ' + 'Uninstall pytest-testdox to be able to run all test cases ' '-- More: https://github.com/renanivo/pytest-testdox/issues/13', UserWarning )
Add the action required to fix the issue to the warning
## Code Before: import os import warnings import pytest pytest_plugins = 'pytester' @pytest.fixture(scope='session', autouse=True) def verify_target_path(): import pytest_testdox current_path_root = os.path.dirname( os.path.dirname(os.path.realpath(__file__)) ) if current_path_root not in pytest_testdox.__file__: warnings.warn( 'pytest-testdox was not imported from your repository. ' 'You might be testing the wrong code ' '-- More: https://github.com/renanivo/pytest-testdox/issues/13', UserWarning ) ## Instruction: Add the action required to fix the issue to the warning ## Code After: import os import warnings import pytest pytest_plugins = 'pytester' @pytest.fixture(scope='session', autouse=True) def verify_target_path(): import pytest_testdox current_path_root = os.path.dirname( os.path.dirname(os.path.realpath(__file__)) ) if current_path_root not in pytest_testdox.__file__: warnings.warn( 'pytest-testdox was not imported from your repository. ' 'You might be testing the wrong code. ' 'Uninstall pytest-testdox to be able to run all test cases ' '-- More: https://github.com/renanivo/pytest-testdox/issues/13', UserWarning )
import os import warnings import pytest pytest_plugins = 'pytester' @pytest.fixture(scope='session', autouse=True) def verify_target_path(): import pytest_testdox current_path_root = os.path.dirname( os.path.dirname(os.path.realpath(__file__)) ) if current_path_root not in pytest_testdox.__file__: warnings.warn( 'pytest-testdox was not imported from your repository. ' - 'You might be testing the wrong code ' + 'You might be testing the wrong code. ' ? + + 'Uninstall pytest-testdox to be able to run all test cases ' '-- More: https://github.com/renanivo/pytest-testdox/issues/13', UserWarning )
901bd73c61fbc6d9d8971ec1ce12e64100e633cb
base/settings/testing.py
base/settings/testing.py
import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-celery. # ------------------------------------------------------------------ Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery',] BROKER_URL = 'django://' # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
Fix the Celery configuration under test settings.
Fix the Celery configuration under test settings.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } + # django-celery. + # ------------------------------------------------------------------ + Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery',] + BROKER_URL = 'django://' + # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
Fix the Celery configuration under test settings.
## Code Before: import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } ## Instruction: Fix the Celery configuration under test settings. ## Code After: import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } # django-celery. # ------------------------------------------------------------------ Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery',] BROKER_URL = 'django://' # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
import os from .base import Base as Settings class Testing(Settings): # Database Configuration. # ------------------------------------------------------------------ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test-base', } } + # django-celery. + # ------------------------------------------------------------------ + Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery',] + BROKER_URL = 'django://' + # django-haystack. # ------------------------------------------------------------------ HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, }
dcbcd7434b8b4199242a479d187d2b833ca6ffcc
polling_stations/settings/constants/councils.py
polling_stations/settings/constants/councils.py
YVM_LA_URL = "https://www.yourvotematters.co.uk/_design/nested-content/results-page2/search-voting-locations-by-districtcode?queries_distcode_query=" # noqa BOUNDARIES_URL = "https://ons-cache.s3.amazonaws.com/Local_Authority_Districts_April_2019_Boundaries_UK_BFE.geojson" EC_COUNCIL_CONTACT_DETAILS_API_URL = "" OLD_TO_NEW_MAP = {} NEW_COUNCILS = []
YVM_LA_URL = "https://www.yourvotematters.co.uk/_design/nested-content/results-page2/search-voting-locations-by-districtcode?queries_distcode_query=" # noqa BOUNDARIES_URL = "https://ons-cache.s3.amazonaws.com/Local_Authority_Districts_April_2019_Boundaries_UK_BFE.geojson" EC_COUNCIL_CONTACT_DETAILS_API_URL = ( "https://electoralcommission.org.uk/api/v1/data/local-authorities.json" ) OLD_TO_NEW_MAP = {} NEW_COUNCILS = []
Set the EC API URL
Set the EC API URL
Python
bsd-3-clause
DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
YVM_LA_URL = "https://www.yourvotematters.co.uk/_design/nested-content/results-page2/search-voting-locations-by-districtcode?queries_distcode_query=" # noqa BOUNDARIES_URL = "https://ons-cache.s3.amazonaws.com/Local_Authority_Districts_April_2019_Boundaries_UK_BFE.geojson" - EC_COUNCIL_CONTACT_DETAILS_API_URL = "" + EC_COUNCIL_CONTACT_DETAILS_API_URL = ( + "https://electoralcommission.org.uk/api/v1/data/local-authorities.json" + ) OLD_TO_NEW_MAP = {} NEW_COUNCILS = []
Set the EC API URL
## Code Before: YVM_LA_URL = "https://www.yourvotematters.co.uk/_design/nested-content/results-page2/search-voting-locations-by-districtcode?queries_distcode_query=" # noqa BOUNDARIES_URL = "https://ons-cache.s3.amazonaws.com/Local_Authority_Districts_April_2019_Boundaries_UK_BFE.geojson" EC_COUNCIL_CONTACT_DETAILS_API_URL = "" OLD_TO_NEW_MAP = {} NEW_COUNCILS = [] ## Instruction: Set the EC API URL ## Code After: YVM_LA_URL = "https://www.yourvotematters.co.uk/_design/nested-content/results-page2/search-voting-locations-by-districtcode?queries_distcode_query=" # noqa BOUNDARIES_URL = "https://ons-cache.s3.amazonaws.com/Local_Authority_Districts_April_2019_Boundaries_UK_BFE.geojson" EC_COUNCIL_CONTACT_DETAILS_API_URL = ( "https://electoralcommission.org.uk/api/v1/data/local-authorities.json" ) OLD_TO_NEW_MAP = {} NEW_COUNCILS = []
YVM_LA_URL = "https://www.yourvotematters.co.uk/_design/nested-content/results-page2/search-voting-locations-by-districtcode?queries_distcode_query=" # noqa BOUNDARIES_URL = "https://ons-cache.s3.amazonaws.com/Local_Authority_Districts_April_2019_Boundaries_UK_BFE.geojson" - EC_COUNCIL_CONTACT_DETAILS_API_URL = "" ? ^^ + EC_COUNCIL_CONTACT_DETAILS_API_URL = ( ? ^ + "https://electoralcommission.org.uk/api/v1/data/local-authorities.json" + ) OLD_TO_NEW_MAP = {} NEW_COUNCILS = []
e92339046fb47fc2275f432dfe3d998f702e40b2
pycalphad/tests/test_tdb.py
pycalphad/tests/test_tdb.py
import nose.tools from pycalphad import Database from sympy import SympifyError @nose.tools.raises(SympifyError) def test_tdb_popen_exploit(): "Prevent execution of arbitrary code using Popen." tdb_exploit_string = \ """ PARAMETER G(L12_FCC,AL,CR,NI:NI;0) 298.15 [].__class__.__base__.__subclasses__()[158]('/bin/ls'); 6000 N ! """ Database(tdb_exploit_string)
import nose.tools from pycalphad import Database @nose.tools.raises(ValueError, TypeError) def test_tdb_popen_exploit(): "Prevent execution of arbitrary code using Popen." tdb_exploit_string = \ """ PARAMETER G(L12_FCC,AL,CR,NI:NI;0) 298.15 [].__class__.__base__.__subclasses__()[158]('/bin/ls'); 6000 N ! """ Database(tdb_exploit_string)
Fix unit test for py26
Fix unit test for py26
Python
mit
tkphd/pycalphad,tkphd/pycalphad,tkphd/pycalphad
import nose.tools from pycalphad import Database - from sympy import SympifyError - @nose.tools.raises(SympifyError) + @nose.tools.raises(ValueError, TypeError) def test_tdb_popen_exploit(): "Prevent execution of arbitrary code using Popen." tdb_exploit_string = \ """ PARAMETER G(L12_FCC,AL,CR,NI:NI;0) 298.15 [].__class__.__base__.__subclasses__()[158]('/bin/ls'); 6000 N ! """ Database(tdb_exploit_string)
Fix unit test for py26
## Code Before: import nose.tools from pycalphad import Database from sympy import SympifyError @nose.tools.raises(SympifyError) def test_tdb_popen_exploit(): "Prevent execution of arbitrary code using Popen." tdb_exploit_string = \ """ PARAMETER G(L12_FCC,AL,CR,NI:NI;0) 298.15 [].__class__.__base__.__subclasses__()[158]('/bin/ls'); 6000 N ! """ Database(tdb_exploit_string) ## Instruction: Fix unit test for py26 ## Code After: import nose.tools from pycalphad import Database @nose.tools.raises(ValueError, TypeError) def test_tdb_popen_exploit(): "Prevent execution of arbitrary code using Popen." tdb_exploit_string = \ """ PARAMETER G(L12_FCC,AL,CR,NI:NI;0) 298.15 [].__class__.__base__.__subclasses__()[158]('/bin/ls'); 6000 N ! """ Database(tdb_exploit_string)
import nose.tools from pycalphad import Database - from sympy import SympifyError - @nose.tools.raises(SympifyError) + @nose.tools.raises(ValueError, TypeError) def test_tdb_popen_exploit(): "Prevent execution of arbitrary code using Popen." tdb_exploit_string = \ """ PARAMETER G(L12_FCC,AL,CR,NI:NI;0) 298.15 [].__class__.__base__.__subclasses__()[158]('/bin/ls'); 6000 N ! """ Database(tdb_exploit_string)
a4656e18539950c0de0aea08eadf88f841ef24ea
scripts/get_bump_version.py
scripts/get_bump_version.py
from __future__ import print_function import subprocess def get_version_from_git(): cmd = ["git", "describe", "--tags", "--always"] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) code = proc.wait() if code != 0: print("Failed to run: %s" % " ".join(cmd)) sys.exit(1) version = proc.stdout.read().decode('utf-8').strip() try: vers, mod = version.split("-")[:2] except ValueError: vers, mod = version, "" return vers, mod vers, mod = get_version_from_git() vals = vers.split('.') if not mod.startswith('rc'): #check for X.X and increment to X.X.1 if len(vals) < 3: new_ver = '.'.join(vals) + '.1' print(new_ver) else: new_val = int(vals[-1]) + 1 new_val = str(new_val) vals[-1] = new_val new_ver = '.'.join(vals) print(new_ver) else: new_ver = vers + '-' + mod print(new_ver)
from __future__ import print_function import subprocess import sys def get_version_from_git(): cmd = ["git", "describe", "--tags", "--always"] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) code = proc.wait() if code != 0: print("Failed to run: %s" % " ".join(cmd)) sys.exit(1) version = proc.stdout.read().decode('utf-8').strip() try: vers, mod = version.split("-")[:2] except ValueError: vers, mod = version, "" return vers, mod vers, mod = get_version_from_git() vals = vers.split('.') if not mod.startswith('rc'): #check for X.X and increment to X.X.1 if len(vals) < 3: new_ver = '.'.join(vals) + '.1' print(new_ver) else: new_val = int(vals[-1]) + 1 new_val = str(new_val) vals[-1] = new_val new_ver = '.'.join(vals) print(new_ver) else: new_ver = vers + '-' + mod print(new_ver)
Make sure sys is available for sys.exit() call on failure
Make sure sys is available for sys.exit() call on failure
Python
bsd-3-clause
dennisobrien/bokeh,stuart-knock/bokeh,mutirri/bokeh,canavandl/bokeh,daodaoliang/bokeh,abele/bokeh,jakirkham/bokeh,stonebig/bokeh,abele/bokeh,philippjfr/bokeh,rs2/bokeh,rs2/bokeh,aavanian/bokeh,birdsarah/bokeh,srinathv/bokeh,bokeh/bokeh,PythonCharmers/bokeh,paultcochrane/bokeh,gpfreitas/bokeh,draperjames/bokeh,Karel-van-de-Plassche/bokeh,rothnic/bokeh,msarahan/bokeh,gpfreitas/bokeh,aiguofer/bokeh,almarklein/bokeh,caseyclements/bokeh,evidation-health/bokeh,stuart-knock/bokeh,KasperPRasmussen/bokeh,aavanian/bokeh,eteq/bokeh,phobson/bokeh,CrazyGuo/bokeh,mutirri/bokeh,timothydmorton/bokeh,DuCorey/bokeh,mutirri/bokeh,awanke/bokeh,schoolie/bokeh,ericdill/bokeh,azjps/bokeh,ChristosChristofidis/bokeh,timsnyder/bokeh,roxyboy/bokeh,eteq/bokeh,Karel-van-de-Plassche/bokeh,deeplook/bokeh,lukebarnard1/bokeh,dennisobrien/bokeh,timsnyder/bokeh,ChinaQuants/bokeh,caseyclements/bokeh,khkaminska/bokeh,PythonCharmers/bokeh,ptitjano/bokeh,jplourenco/bokeh,paultcochrane/bokeh,phobson/bokeh,bokeh/bokeh,ericdill/bokeh,percyfal/bokeh,Karel-van-de-Plassche/bokeh,xguse/bokeh,mindriot101/bokeh,josherick/bokeh,caseyclements/bokeh,saifrahmed/bokeh,DuCorey/bokeh,KasperPRasmussen/bokeh,deeplook/bokeh,azjps/bokeh,ericmjl/bokeh,daodaoliang/bokeh,ChinaQuants/bokeh,awanke/bokeh,ericmjl/bokeh,CrazyGuo/bokeh,htygithub/bokeh,alan-unravel/bokeh,alan-unravel/bokeh,abele/bokeh,tacaswell/bokeh,saifrahmed/bokeh,alan-unravel/bokeh,jakirkham/bokeh,timothydmorton/bokeh,ptitjano/bokeh,caseyclements/bokeh,rhiever/bokeh,KasperPRasmussen/bokeh,phobson/bokeh,DuCorey/bokeh,schoolie/bokeh,percyfal/bokeh,DuCorey/bokeh,ahmadia/bokeh,schoolie/bokeh,saifrahmed/bokeh,ericdill/bokeh,justacec/bokeh,azjps/bokeh,canavandl/bokeh,laurent-george/bokeh,eteq/bokeh,htygithub/bokeh,philippjfr/bokeh,clairetang6/bokeh,roxyboy/bokeh,birdsarah/bokeh,schoolie/bokeh,percyfal/bokeh,evidation-health/bokeh,matbra/bokeh,matbra/bokeh,rs2/bokeh,htygithub/bokeh,ChinaQuants/bokeh,jplourenco/bokeh,ptitjano/bokeh,muku42/bokeh,timothydmorton/bokeh,CrazyGuo/bokeh,carlvlewis/bokeh,xguse/bokeh,Karel-van-de-Plassche/bokeh,awanke/bokeh,quasiben/bokeh,rothnic/bokeh,xguse/bokeh,muku42/bokeh,rothnic/bokeh,xguse/bokeh,jakirkham/bokeh,alan-unravel/bokeh,roxyboy/bokeh,stuart-knock/bokeh,muku42/bokeh,quasiben/bokeh,phobson/bokeh,aiguofer/bokeh,philippjfr/bokeh,satishgoda/bokeh,PythonCharmers/bokeh,deeplook/bokeh,almarklein/bokeh,dennisobrien/bokeh,bsipocz/bokeh,matbra/bokeh,akloster/bokeh,ptitjano/bokeh,ericdill/bokeh,mindriot101/bokeh,carlvlewis/bokeh,jplourenco/bokeh,khkaminska/bokeh,laurent-george/bokeh,dennisobrien/bokeh,gpfreitas/bokeh,birdsarah/bokeh,ChinaQuants/bokeh,mindriot101/bokeh,awanke/bokeh,timsnyder/bokeh,clairetang6/bokeh,bokeh/bokeh,rs2/bokeh,clairetang6/bokeh,rhiever/bokeh,josherick/bokeh,rhiever/bokeh,bsipocz/bokeh,CrazyGuo/bokeh,draperjames/bokeh,carlvlewis/bokeh,saifrahmed/bokeh,rhiever/bokeh,htygithub/bokeh,srinathv/bokeh,maxalbert/bokeh,percyfal/bokeh,mindriot101/bokeh,ericmjl/bokeh,draperjames/bokeh,maxalbert/bokeh,ericmjl/bokeh,bsipocz/bokeh,matbra/bokeh,gpfreitas/bokeh,azjps/bokeh,quasiben/bokeh,draperjames/bokeh,eteq/bokeh,draperjames/bokeh,jakirkham/bokeh,stonebig/bokeh,timothydmorton/bokeh,tacaswell/bokeh,laurent-george/bokeh,ahmadia/bokeh,Karel-van-de-Plassche/bokeh,ahmadia/bokeh,carlvlewis/bokeh,jplourenco/bokeh,maxalbert/bokeh,KasperPRasmussen/bokeh,justacec/bokeh,maxalbert/bokeh,msarahan/bokeh,birdsarah/bokeh,rothnic/bokeh,philippjfr/bokeh,mutirri/bokeh,canavandl/bokeh,abele/bokeh,khkaminska/bokeh,timsnyder/bokeh,aiguofer/bokeh,bokeh/bokeh,tacaswell/bokeh,msarahan/bokeh,josherick/bokeh,daodaoliang/bokeh,ericmjl/bokeh,aavanian/bokeh,aiguofer/bokeh,schoolie/bokeh,akloster/bokeh,lukebarnard1/bokeh,satishgoda/bokeh,canavandl/bokeh,jakirkham/bokeh,philippjfr/bokeh,aavanian/bokeh,stonebig/bokeh,msarahan/bokeh,PythonCharmers/bokeh,justacec/bokeh,phobson/bokeh,aiguofer/bokeh,dennisobrien/bokeh,ChristosChristofidis/bokeh,bokeh/bokeh,paultcochrane/bokeh,stonebig/bokeh,srinathv/bokeh,satishgoda/bokeh,evidation-health/bokeh,akloster/bokeh,ahmadia/bokeh,clairetang6/bokeh,DuCorey/bokeh,deeplook/bokeh,laurent-george/bokeh,muku42/bokeh,stuart-knock/bokeh,satishgoda/bokeh,josherick/bokeh,lukebarnard1/bokeh,daodaoliang/bokeh,khkaminska/bokeh,timsnyder/bokeh,paultcochrane/bokeh,percyfal/bokeh,rs2/bokeh,tacaswell/bokeh,akloster/bokeh,ChristosChristofidis/bokeh,aavanian/bokeh,evidation-health/bokeh,lukebarnard1/bokeh,ChristosChristofidis/bokeh,bsipocz/bokeh,justacec/bokeh,almarklein/bokeh,srinathv/bokeh,KasperPRasmussen/bokeh,ptitjano/bokeh,roxyboy/bokeh,azjps/bokeh
from __future__ import print_function import subprocess + import sys def get_version_from_git(): cmd = ["git", "describe", "--tags", "--always"] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) code = proc.wait() if code != 0: print("Failed to run: %s" % " ".join(cmd)) sys.exit(1) version = proc.stdout.read().decode('utf-8').strip() try: vers, mod = version.split("-")[:2] except ValueError: vers, mod = version, "" return vers, mod vers, mod = get_version_from_git() vals = vers.split('.') if not mod.startswith('rc'): #check for X.X and increment to X.X.1 if len(vals) < 3: new_ver = '.'.join(vals) + '.1' print(new_ver) else: new_val = int(vals[-1]) + 1 new_val = str(new_val) vals[-1] = new_val new_ver = '.'.join(vals) print(new_ver) else: new_ver = vers + '-' + mod print(new_ver)
Make sure sys is available for sys.exit() call on failure
## Code Before: from __future__ import print_function import subprocess def get_version_from_git(): cmd = ["git", "describe", "--tags", "--always"] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) code = proc.wait() if code != 0: print("Failed to run: %s" % " ".join(cmd)) sys.exit(1) version = proc.stdout.read().decode('utf-8').strip() try: vers, mod = version.split("-")[:2] except ValueError: vers, mod = version, "" return vers, mod vers, mod = get_version_from_git() vals = vers.split('.') if not mod.startswith('rc'): #check for X.X and increment to X.X.1 if len(vals) < 3: new_ver = '.'.join(vals) + '.1' print(new_ver) else: new_val = int(vals[-1]) + 1 new_val = str(new_val) vals[-1] = new_val new_ver = '.'.join(vals) print(new_ver) else: new_ver = vers + '-' + mod print(new_ver) ## Instruction: Make sure sys is available for sys.exit() call on failure ## Code After: from __future__ import print_function import subprocess import sys def get_version_from_git(): cmd = ["git", "describe", "--tags", "--always"] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) code = proc.wait() if code != 0: print("Failed to run: %s" % " ".join(cmd)) sys.exit(1) version = proc.stdout.read().decode('utf-8').strip() try: vers, mod = version.split("-")[:2] except ValueError: vers, mod = version, "" return vers, mod vers, mod = get_version_from_git() vals = vers.split('.') if not mod.startswith('rc'): #check for X.X and increment to X.X.1 if len(vals) < 3: new_ver = '.'.join(vals) + '.1' print(new_ver) else: new_val = int(vals[-1]) + 1 new_val = str(new_val) vals[-1] = new_val new_ver = '.'.join(vals) print(new_ver) else: new_ver = vers + '-' + mod print(new_ver)
from __future__ import print_function import subprocess + import sys def get_version_from_git(): cmd = ["git", "describe", "--tags", "--always"] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) code = proc.wait() if code != 0: print("Failed to run: %s" % " ".join(cmd)) sys.exit(1) version = proc.stdout.read().decode('utf-8').strip() try: vers, mod = version.split("-")[:2] except ValueError: vers, mod = version, "" return vers, mod vers, mod = get_version_from_git() vals = vers.split('.') if not mod.startswith('rc'): #check for X.X and increment to X.X.1 if len(vals) < 3: new_ver = '.'.join(vals) + '.1' print(new_ver) else: new_val = int(vals[-1]) + 1 new_val = str(new_val) vals[-1] = new_val new_ver = '.'.join(vals) print(new_ver) else: new_ver = vers + '-' + mod print(new_ver)
0a884d3c38cb1449a6fa5c650ed06cde647de4a8
settings/sqlite.py
settings/sqlite.py
from .base import * import os.path DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'dev.db'), } } SESSION_COOKIE_DOMAIN = None HAYSTACK_SOLR_URL = 'http://localhost:8983/solr'
from .base import * import os.path DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'dev.db'), } } SESSION_COOKIE_DOMAIN = None HAYSTACK_SOLR_URL = 'http://localhost:8983/solr' try: from local_settings import * except: pass
Allow local settings override as well.
Allow local settings override as well.
Python
mit
singingwolfboy/readthedocs.org,laplaceliu/readthedocs.org,kenwang76/readthedocs.org,hach-que/readthedocs.org,fujita-shintaro/readthedocs.org,rtfd/readthedocs.org,tddv/readthedocs.org,raven47git/readthedocs.org,mhils/readthedocs.org,royalwang/readthedocs.org,johncosta/private-readthedocs.org,asampat3090/readthedocs.org,safwanrahman/readthedocs.org,istresearch/readthedocs.org,espdev/readthedocs.org,VishvajitP/readthedocs.org,d0ugal/readthedocs.org,atsuyim/readthedocs.org,kdkeyser/readthedocs.org,GovReady/readthedocs.org,techtonik/readthedocs.org,agjohnson/readthedocs.org,davidfischer/readthedocs.org,fujita-shintaro/readthedocs.org,Tazer/readthedocs.org,nikolas/readthedocs.org,cgourlay/readthedocs.org,wanghaven/readthedocs.org,royalwang/readthedocs.org,sils1297/readthedocs.org,nyergler/pythonslides,agjohnson/readthedocs.org,tddv/readthedocs.org,kenshinthebattosai/readthedocs.org,atsuyim/readthedocs.org,sid-kap/readthedocs.org,soulshake/readthedocs.org,SteveViss/readthedocs.org,kenwang76/readthedocs.org,wijerasa/readthedocs.org,istresearch/readthedocs.org,KamranMackey/readthedocs.org,nyergler/pythonslides,laplaceliu/readthedocs.org,SteveViss/readthedocs.org,attakei/readthedocs-oauth,emawind84/readthedocs.org,jerel/readthedocs.org,takluyver/readthedocs.org,Tazer/readthedocs.org,titiushko/readthedocs.org,gjtorikian/readthedocs.org,emawind84/readthedocs.org,asampat3090/readthedocs.org,nikolas/readthedocs.org,kenwang76/readthedocs.org,dirn/readthedocs.org,emawind84/readthedocs.org,royalwang/readthedocs.org,takluyver/readthedocs.org,rtfd/readthedocs.org,sunnyzwh/readthedocs.org,jerel/readthedocs.org,espdev/readthedocs.org,laplaceliu/readthedocs.org,michaelmcandrew/readthedocs.org,d0ugal/readthedocs.org,techtonik/readthedocs.org,rtfd/readthedocs.org,titiushko/readthedocs.org,istresearch/readthedocs.org,Carreau/readthedocs.org,agjohnson/readthedocs.org,mrshoki/readthedocs.org,sils1297/readthedocs.org,atsuyim/readthedocs.org,ojii/readthedocs.org,clarkperkins/readthedocs.org,sils1297/readthedocs.org,laplaceliu/readthedocs.org,ojii/readthedocs.org,cgourlay/readthedocs.org,singingwolfboy/readthedocs.org,hach-que/readthedocs.org,cgourlay/readthedocs.org,singingwolfboy/readthedocs.org,pombredanne/readthedocs.org,atsuyim/readthedocs.org,sid-kap/readthedocs.org,titiushko/readthedocs.org,hach-que/readthedocs.org,johncosta/private-readthedocs.org,sils1297/readthedocs.org,mrshoki/readthedocs.org,titiushko/readthedocs.org,ojii/readthedocs.org,techtonik/readthedocs.org,techtonik/readthedocs.org,pombredanne/readthedocs.org,fujita-shintaro/readthedocs.org,SteveViss/readthedocs.org,wanghaven/readthedocs.org,stevepiercy/readthedocs.org,kdkeyser/readthedocs.org,wanghaven/readthedocs.org,ojii/readthedocs.org,CedarLogic/readthedocs.org,soulshake/readthedocs.org,kdkeyser/readthedocs.org,SteveViss/readthedocs.org,LukasBoersma/readthedocs.org,d0ugal/readthedocs.org,michaelmcandrew/readthedocs.org,gjtorikian/readthedocs.org,hach-que/readthedocs.org,wijerasa/readthedocs.org,nikolas/readthedocs.org,Carreau/readthedocs.org,raven47git/readthedocs.org,jerel/readthedocs.org,michaelmcandrew/readthedocs.org,mrshoki/readthedocs.org,nyergler/pythonslides,nikolas/readthedocs.org,clarkperkins/readthedocs.org,raven47git/readthedocs.org,mhils/readthedocs.org,stevepiercy/readthedocs.org,rtfd/readthedocs.org,LukasBoersma/readthedocs.org,davidfischer/readthedocs.org,mrshoki/readthedocs.org,tddv/readthedocs.org,CedarLogic/readthedocs.org,dirn/readthedocs.org,kdkeyser/readthedocs.org,safwanrahman/readthedocs.org,sid-kap/readthedocs.org,kenshinthebattosai/readthedocs.org,emawind84/readthedocs.org,pombredanne/readthedocs.org,VishvajitP/readthedocs.org,KamranMackey/readthedocs.org,Carreau/readthedocs.org,safwanrahman/readthedocs.org,soulshake/readthedocs.org,raven47git/readthedocs.org,singingwolfboy/readthedocs.org,KamranMackey/readthedocs.org,takluyver/readthedocs.org,gjtorikian/readthedocs.org,wijerasa/readthedocs.org,Tazer/readthedocs.org,stevepiercy/readthedocs.org,LukasBoersma/readthedocs.org,espdev/readthedocs.org,KamranMackey/readthedocs.org,johncosta/private-readthedocs.org,safwanrahman/readthedocs.org,dirn/readthedocs.org,sunnyzwh/readthedocs.org,GovReady/readthedocs.org,VishvajitP/readthedocs.org,davidfischer/readthedocs.org,GovReady/readthedocs.org,alex/readthedocs.org,sunnyzwh/readthedocs.org,istresearch/readthedocs.org,takluyver/readthedocs.org,royalwang/readthedocs.org,asampat3090/readthedocs.org,soulshake/readthedocs.org,VishvajitP/readthedocs.org,espdev/readthedocs.org,GovReady/readthedocs.org,clarkperkins/readthedocs.org,agjohnson/readthedocs.org,michaelmcandrew/readthedocs.org,mhils/readthedocs.org,alex/readthedocs.org,cgourlay/readthedocs.org,alex/readthedocs.org,jerel/readthedocs.org,davidfischer/readthedocs.org,sunnyzwh/readthedocs.org,alex/readthedocs.org,clarkperkins/readthedocs.org,Carreau/readthedocs.org,kenshinthebattosai/readthedocs.org,Tazer/readthedocs.org,d0ugal/readthedocs.org,fujita-shintaro/readthedocs.org,CedarLogic/readthedocs.org,sid-kap/readthedocs.org,kenwang76/readthedocs.org,attakei/readthedocs-oauth,asampat3090/readthedocs.org,mhils/readthedocs.org,CedarLogic/readthedocs.org,dirn/readthedocs.org,LukasBoersma/readthedocs.org,stevepiercy/readthedocs.org,attakei/readthedocs-oauth,gjtorikian/readthedocs.org,nyergler/pythonslides,wanghaven/readthedocs.org,attakei/readthedocs-oauth,wijerasa/readthedocs.org,kenshinthebattosai/readthedocs.org,espdev/readthedocs.org
from .base import * import os.path DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'dev.db'), } } SESSION_COOKIE_DOMAIN = None HAYSTACK_SOLR_URL = 'http://localhost:8983/solr' + try: + from local_settings import * + except: + pass +
Allow local settings override as well.
## Code Before: from .base import * import os.path DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'dev.db'), } } SESSION_COOKIE_DOMAIN = None HAYSTACK_SOLR_URL = 'http://localhost:8983/solr' ## Instruction: Allow local settings override as well. ## Code After: from .base import * import os.path DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'dev.db'), } } SESSION_COOKIE_DOMAIN = None HAYSTACK_SOLR_URL = 'http://localhost:8983/solr' try: from local_settings import * except: pass
from .base import * import os.path DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'dev.db'), } } SESSION_COOKIE_DOMAIN = None HAYSTACK_SOLR_URL = 'http://localhost:8983/solr' + try: + from local_settings import * + except: + pass +
c244b84def159bc4d4e281fe39ebe06886a109d2
tests/__init__.py
tests/__init__.py
from django.conf import settings from mock import Mock, patch from unittest2 import TestCase settings.configure( DEFAULT_INDEX_TABLESPACE='', ) class TestPreference(object): def __init__(self, name, value, user=None): self.name = name self.value = value self.user = user def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return '<{name}:{value}:{user}>'.format(**self.__dict__) class TestUser(object): @property def preferences(self): return Mock(all=Mock(return_value=self._preferences)) @preferences.setter def preferences(self, value): self._preferences = [ TestPreference(k, v) for k, v in value.iteritems()] class SerializerTestCase(TestCase): def patch_from_native(self): patcher = patch( 'madprops.serializers.ModelSerializer.from_native', new=lambda self, data, files: TestPreference( data['name'], data['value'], data.get('user')) ) self.patched_from_native = patcher.start() self.addCleanup(patcher.stop)
from django.conf import settings from mock import Mock, patch from unittest2 import TestCase settings.configure() class TestPreference(object): def __init__(self, name, value, user=None): self.name = name self.value = value self.user = user def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return '<{name}:{value}:{user}>'.format(**self.__dict__) class TestUser(object): @property def preferences(self): return Mock(all=Mock(return_value=self._preferences)) @preferences.setter def preferences(self, value): self._preferences = [ TestPreference(k, v) for k, v in value.iteritems()] class SerializerTestCase(TestCase): def patch_from_native(self): patcher = patch( 'madprops.serializers.ModelSerializer.from_native', new=lambda self, data, files: TestPreference( data['name'], data['value'], data.get('user')) ) self.patched_from_native = patcher.start() self.addCleanup(patcher.stop)
Simplify configure of django settings
Simplify configure of django settings
Python
mit
yola/drf-madprops
from django.conf import settings from mock import Mock, patch from unittest2 import TestCase - settings.configure( + settings.configure() - DEFAULT_INDEX_TABLESPACE='', - ) class TestPreference(object): def __init__(self, name, value, user=None): self.name = name self.value = value self.user = user def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return '<{name}:{value}:{user}>'.format(**self.__dict__) class TestUser(object): @property def preferences(self): return Mock(all=Mock(return_value=self._preferences)) @preferences.setter def preferences(self, value): self._preferences = [ TestPreference(k, v) for k, v in value.iteritems()] class SerializerTestCase(TestCase): def patch_from_native(self): patcher = patch( 'madprops.serializers.ModelSerializer.from_native', new=lambda self, data, files: TestPreference( data['name'], data['value'], data.get('user')) ) self.patched_from_native = patcher.start() self.addCleanup(patcher.stop)
Simplify configure of django settings
## Code Before: from django.conf import settings from mock import Mock, patch from unittest2 import TestCase settings.configure( DEFAULT_INDEX_TABLESPACE='', ) class TestPreference(object): def __init__(self, name, value, user=None): self.name = name self.value = value self.user = user def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return '<{name}:{value}:{user}>'.format(**self.__dict__) class TestUser(object): @property def preferences(self): return Mock(all=Mock(return_value=self._preferences)) @preferences.setter def preferences(self, value): self._preferences = [ TestPreference(k, v) for k, v in value.iteritems()] class SerializerTestCase(TestCase): def patch_from_native(self): patcher = patch( 'madprops.serializers.ModelSerializer.from_native', new=lambda self, data, files: TestPreference( data['name'], data['value'], data.get('user')) ) self.patched_from_native = patcher.start() self.addCleanup(patcher.stop) ## Instruction: Simplify configure of django settings ## Code After: from django.conf import settings from mock import Mock, patch from unittest2 import TestCase settings.configure() class TestPreference(object): def __init__(self, name, value, user=None): self.name = name self.value = value self.user = user def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return '<{name}:{value}:{user}>'.format(**self.__dict__) class TestUser(object): @property def preferences(self): return Mock(all=Mock(return_value=self._preferences)) @preferences.setter def preferences(self, value): self._preferences = [ TestPreference(k, v) for k, v in value.iteritems()] class SerializerTestCase(TestCase): def patch_from_native(self): patcher = patch( 'madprops.serializers.ModelSerializer.from_native', new=lambda self, data, files: TestPreference( data['name'], data['value'], data.get('user')) ) self.patched_from_native = patcher.start() self.addCleanup(patcher.stop)
from django.conf import settings from mock import Mock, patch from unittest2 import TestCase - settings.configure( + settings.configure() ? + - DEFAULT_INDEX_TABLESPACE='', - ) class TestPreference(object): def __init__(self, name, value, user=None): self.name = name self.value = value self.user = user def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return '<{name}:{value}:{user}>'.format(**self.__dict__) class TestUser(object): @property def preferences(self): return Mock(all=Mock(return_value=self._preferences)) @preferences.setter def preferences(self, value): self._preferences = [ TestPreference(k, v) for k, v in value.iteritems()] class SerializerTestCase(TestCase): def patch_from_native(self): patcher = patch( 'madprops.serializers.ModelSerializer.from_native', new=lambda self, data, files: TestPreference( data['name'], data['value'], data.get('user')) ) self.patched_from_native = patcher.start() self.addCleanup(patcher.stop)
cb0c4b7af5efc16d1ca5da9722d9e29cae527fec
acme/utils/signals.py
acme/utils/signals.py
"""A thin wrapper around Python's builtin signal.signal().""" import signal import types from typing import Any, Callable _Handler = Callable[[], Any] def add_handler(signo: signal.Signals, fn: _Handler): def _wrapped(signo: signal.Signals, frame: types.FrameType): del signo, frame return fn() signal.signal(signo, _wrapped)
"""A thin wrapper around Python's builtin signal.signal().""" import signal import types from typing import Any, Callable _Handler = Callable[[], Any] def add_handler(signo: signal.Signals, fn: _Handler): # The function signal.signal expects the handler to take an int rather than a # signal.Signals. def _wrapped(signo: int, frame: types.FrameType): del signo, frame return fn() signal.signal(signo.value, _wrapped)
Fix pytype issue in signal handling code.
Fix pytype issue in signal handling code. PiperOrigin-RevId: 408605103 Change-Id: If724504629a50d5cb7a099cf0263ba642e95345d
Python
apache-2.0
deepmind/acme,deepmind/acme
"""A thin wrapper around Python's builtin signal.signal().""" import signal import types from typing import Any, Callable _Handler = Callable[[], Any] def add_handler(signo: signal.Signals, fn: _Handler): + + # The function signal.signal expects the handler to take an int rather than a + # signal.Signals. - def _wrapped(signo: signal.Signals, frame: types.FrameType): + def _wrapped(signo: int, frame: types.FrameType): del signo, frame return fn() - signal.signal(signo, _wrapped) + signal.signal(signo.value, _wrapped)
Fix pytype issue in signal handling code.
## Code Before: """A thin wrapper around Python's builtin signal.signal().""" import signal import types from typing import Any, Callable _Handler = Callable[[], Any] def add_handler(signo: signal.Signals, fn: _Handler): def _wrapped(signo: signal.Signals, frame: types.FrameType): del signo, frame return fn() signal.signal(signo, _wrapped) ## Instruction: Fix pytype issue in signal handling code. ## Code After: """A thin wrapper around Python's builtin signal.signal().""" import signal import types from typing import Any, Callable _Handler = Callable[[], Any] def add_handler(signo: signal.Signals, fn: _Handler): # The function signal.signal expects the handler to take an int rather than a # signal.Signals. def _wrapped(signo: int, frame: types.FrameType): del signo, frame return fn() signal.signal(signo.value, _wrapped)
"""A thin wrapper around Python's builtin signal.signal().""" import signal import types from typing import Any, Callable _Handler = Callable[[], Any] def add_handler(signo: signal.Signals, fn: _Handler): + + # The function signal.signal expects the handler to take an int rather than a + # signal.Signals. - def _wrapped(signo: signal.Signals, frame: types.FrameType): ? - - ^^^^^^^^^^ + def _wrapped(signo: int, frame: types.FrameType): ? ^ del signo, frame return fn() - signal.signal(signo, _wrapped) + signal.signal(signo.value, _wrapped) ? ++++++
ee32b2e48acd47f1f1ff96482abf20f3d1818fc4
tests/__init__.py
tests/__init__.py
import sys import unittest sys.path.append("../pythainlp") loader = unittest.TestLoader() testSuite = loader.discover("tests") testRunner = unittest.TextTestRunner(verbosity=1) testRunner.run(testSuite)
import sys import unittest import nltk sys.path.append("../pythainlp") nltk.download('omw-1.4') # load wordnet loader = unittest.TestLoader() testSuite = loader.discover("tests") testRunner = unittest.TextTestRunner(verbosity=1) testRunner.run(testSuite)
Add load wordnet to tests
Add load wordnet to tests
Python
apache-2.0
PyThaiNLP/pythainlp
import sys import unittest + import nltk sys.path.append("../pythainlp") + + nltk.download('omw-1.4') # load wordnet loader = unittest.TestLoader() testSuite = loader.discover("tests") testRunner = unittest.TextTestRunner(verbosity=1) testRunner.run(testSuite)
Add load wordnet to tests
## Code Before: import sys import unittest sys.path.append("../pythainlp") loader = unittest.TestLoader() testSuite = loader.discover("tests") testRunner = unittest.TextTestRunner(verbosity=1) testRunner.run(testSuite) ## Instruction: Add load wordnet to tests ## Code After: import sys import unittest import nltk sys.path.append("../pythainlp") nltk.download('omw-1.4') # load wordnet loader = unittest.TestLoader() testSuite = loader.discover("tests") testRunner = unittest.TextTestRunner(verbosity=1) testRunner.run(testSuite)
import sys import unittest + import nltk sys.path.append("../pythainlp") + + nltk.download('omw-1.4') # load wordnet loader = unittest.TestLoader() testSuite = loader.discover("tests") testRunner = unittest.TextTestRunner(verbosity=1) testRunner.run(testSuite)
0dc217bd0cec8a0321dfc38b88696514179bf833
editorconfig/__init__.py
editorconfig/__init__.py
"""EditorConfig Python Core""" from editorconfig.versiontools import join_version VERSION = (0, 11, 3, "development") __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename""" handler = EditorConfigHandler(filename) return handler.get_configurations() from editorconfig.handler import EditorConfigHandler from editorconfig.exceptions import *
"""EditorConfig Python Core""" from editorconfig.versiontools import join_version VERSION = (0, 11, 3, "final") __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename""" handler = EditorConfigHandler(filename) return handler.get_configurations() from editorconfig.handler import EditorConfigHandler from editorconfig.exceptions import *
Upgrade version to 0.11.3 final
Upgrade version to 0.11.3 final
Python
bsd-2-clause
VictorBjelkholm/editorconfig-vim,johnfraney/editorconfig-vim,pocke/editorconfig-vim,pocke/editorconfig-vim,johnfraney/editorconfig-vim,benjifisher/editorconfig-vim,pocke/editorconfig-vim,johnfraney/editorconfig-vim,VictorBjelkholm/editorconfig-vim,VictorBjelkholm/editorconfig-vim,benjifisher/editorconfig-vim,benjifisher/editorconfig-vim
"""EditorConfig Python Core""" from editorconfig.versiontools import join_version - VERSION = (0, 11, 3, "development") + VERSION = (0, 11, 3, "final") __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename""" handler = EditorConfigHandler(filename) return handler.get_configurations() from editorconfig.handler import EditorConfigHandler from editorconfig.exceptions import *
Upgrade version to 0.11.3 final
## Code Before: """EditorConfig Python Core""" from editorconfig.versiontools import join_version VERSION = (0, 11, 3, "development") __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename""" handler = EditorConfigHandler(filename) return handler.get_configurations() from editorconfig.handler import EditorConfigHandler from editorconfig.exceptions import * ## Instruction: Upgrade version to 0.11.3 final ## Code After: """EditorConfig Python Core""" from editorconfig.versiontools import join_version VERSION = (0, 11, 3, "final") __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename""" handler = EditorConfigHandler(filename) return handler.get_configurations() from editorconfig.handler import EditorConfigHandler from editorconfig.exceptions import *
"""EditorConfig Python Core""" from editorconfig.versiontools import join_version - VERSION = (0, 11, 3, "development") ? ^^^^ ------ + VERSION = (0, 11, 3, "final") ? ^^^^ __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename""" handler = EditorConfigHandler(filename) return handler.get_configurations() from editorconfig.handler import EditorConfigHandler from editorconfig.exceptions import *
6c2685fd6701600950d01b8f3ac3de08c0583ec9
indico/core/extpoint/location.py
indico/core/extpoint/location.py
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 3 of the ## License, or (at your option) any later version. ## ## Indico is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Indico;if not, see <http://www.gnu.org/licenses/>. from indico.core.extpoint import IListener, IContributor class ILocationActionListener(IListener): """ Events that are related to rooms, locations, etc... """ def roomChanged(self, obj, oldLocation, newLocation): pass def locationChanged(self, obj, oldLocation, newLocation): pass def placeChanged(self, obj): """ Either the room or location changed """
from indico.core.extpoint import IListener class ILocationActionListener(IListener): """ Events that are related to rooms, locations, etc... """ def roomChanged(self, obj, oldLocation, newLocation): pass def locationChanged(self, obj, oldLocation, newLocation): pass def placeChanged(self, obj): """ Either the room or location changed """
Update header missed by the script
Update header missed by the script Really, who puts spaces in front of the comments of a file header?!
Python
mit
DirkHoffmann/indico,mic4ael/indico,DirkHoffmann/indico,ThiefMaster/indico,OmeGak/indico,indico/indico,mvidalgarcia/indico,indico/indico,DirkHoffmann/indico,mic4ael/indico,OmeGak/indico,pferreir/indico,pferreir/indico,mvidalgarcia/indico,indico/indico,indico/indico,ThiefMaster/indico,mvidalgarcia/indico,mic4ael/indico,pferreir/indico,mic4ael/indico,OmeGak/indico,DirkHoffmann/indico,OmeGak/indico,ThiefMaster/indico,ThiefMaster/indico,mvidalgarcia/indico,pferreir/indico
- # -*- coding: utf-8 -*- - ## - ## - ## This file is part of Indico. - ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). - ## - ## Indico is free software; you can redistribute it and/or - ## modify it under the terms of the GNU General Public License as - ## published by the Free Software Foundation; either version 3 of the - ## License, or (at your option) any later version. - ## - ## Indico is distributed in the hope that it will be useful, but - ## WITHOUT ANY WARRANTY; without even the implied warranty of - ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - ## General Public License for more details. - ## - ## You should have received a copy of the GNU General Public License - ## along with Indico;if not, see <http://www.gnu.org/licenses/>. - from indico.core.extpoint import IListener, IContributor + from indico.core.extpoint import IListener class ILocationActionListener(IListener): """ Events that are related to rooms, locations, etc... """ def roomChanged(self, obj, oldLocation, newLocation): pass def locationChanged(self, obj, oldLocation, newLocation): pass def placeChanged(self, obj): """ Either the room or location changed """
Update header missed by the script
## Code Before: # -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 3 of the ## License, or (at your option) any later version. ## ## Indico is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Indico;if not, see <http://www.gnu.org/licenses/>. from indico.core.extpoint import IListener, IContributor class ILocationActionListener(IListener): """ Events that are related to rooms, locations, etc... """ def roomChanged(self, obj, oldLocation, newLocation): pass def locationChanged(self, obj, oldLocation, newLocation): pass def placeChanged(self, obj): """ Either the room or location changed """ ## Instruction: Update header missed by the script ## Code After: from indico.core.extpoint import IListener class ILocationActionListener(IListener): """ Events that are related to rooms, locations, etc... """ def roomChanged(self, obj, oldLocation, newLocation): pass def locationChanged(self, obj, oldLocation, newLocation): pass def placeChanged(self, obj): """ Either the room or location changed """
- # -*- coding: utf-8 -*- - ## - ## - ## This file is part of Indico. - ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). - ## - ## Indico is free software; you can redistribute it and/or - ## modify it under the terms of the GNU General Public License as - ## published by the Free Software Foundation; either version 3 of the - ## License, or (at your option) any later version. - ## - ## Indico is distributed in the hope that it will be useful, but - ## WITHOUT ANY WARRANTY; without even the implied warranty of - ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - ## General Public License for more details. - ## - ## You should have received a copy of the GNU General Public License - ## along with Indico;if not, see <http://www.gnu.org/licenses/>. - from indico.core.extpoint import IListener, IContributor ? -------------- + from indico.core.extpoint import IListener class ILocationActionListener(IListener): """ Events that are related to rooms, locations, etc... """ def roomChanged(self, obj, oldLocation, newLocation): pass def locationChanged(self, obj, oldLocation, newLocation): pass def placeChanged(self, obj): """ Either the room or location changed """
4eecac0764e8abfc33c9e77b8eb6b700b536f1a0
pull_me.py
pull_me.py
from random import randint from time import sleep from os import system from easygui import msgbox while True: delay = randint(60, 2000) sleep(delay) system("aplay /usr/lib/libreoffice/share/gallery/sounds/kongas.wav") msgbox("Hi Dan", "Time is up")
from random import randint from time import sleep from os import system import os.path from easygui import msgbox while True: delay = randint(60, 2000) sleep(delay) if os.path.isfile("/usr/share/sounds/GNUstep/Glass.wav"): system("aplay /usr/share/sounds/GNUstep/Glass.wav") else: system("aplay /usr/lib/libreoffice/share/gallery/sounds/kongas.wav") msgbox("Hi Dan", "Time is up")
Use Glass.wav if it exists.
Use Glass.wav if it exists.
Python
apache-2.0
dnuffer/carrot_slots
from random import randint from time import sleep from os import system + import os.path from easygui import msgbox while True: delay = randint(60, 2000) sleep(delay) + if os.path.isfile("/usr/share/sounds/GNUstep/Glass.wav"): + system("aplay /usr/share/sounds/GNUstep/Glass.wav") + else: - system("aplay /usr/lib/libreoffice/share/gallery/sounds/kongas.wav") + system("aplay /usr/lib/libreoffice/share/gallery/sounds/kongas.wav") msgbox("Hi Dan", "Time is up")
Use Glass.wav if it exists.
## Code Before: from random import randint from time import sleep from os import system from easygui import msgbox while True: delay = randint(60, 2000) sleep(delay) system("aplay /usr/lib/libreoffice/share/gallery/sounds/kongas.wav") msgbox("Hi Dan", "Time is up") ## Instruction: Use Glass.wav if it exists. ## Code After: from random import randint from time import sleep from os import system import os.path from easygui import msgbox while True: delay = randint(60, 2000) sleep(delay) if os.path.isfile("/usr/share/sounds/GNUstep/Glass.wav"): system("aplay /usr/share/sounds/GNUstep/Glass.wav") else: system("aplay /usr/lib/libreoffice/share/gallery/sounds/kongas.wav") msgbox("Hi Dan", "Time is up")
from random import randint from time import sleep from os import system + import os.path from easygui import msgbox while True: delay = randint(60, 2000) sleep(delay) + if os.path.isfile("/usr/share/sounds/GNUstep/Glass.wav"): + system("aplay /usr/share/sounds/GNUstep/Glass.wav") + else: - system("aplay /usr/lib/libreoffice/share/gallery/sounds/kongas.wav") + system("aplay /usr/lib/libreoffice/share/gallery/sounds/kongas.wav") ? ++ msgbox("Hi Dan", "Time is up")
803e128b8e151c061f75051b5a4386d4c624ba56
core/settings-wni-Windows_NT.py
core/settings-wni-Windows_NT.py
from __future__ import absolute_import from qubes.storage.wni import QubesWniVmStorage def apply(system_path, vm_files, defaults): system_path['qubes_base_dir'] = 'c:\\qubes' system_path['config_template_pv'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template.xml' system_path['config_template_hvm'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template-hvm.xml' system_path['qubes_icon_dir'] = \ 'c:/program files/Invisible Things Lab/Qubes/icons' system_path['qubesdb_daemon_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qubesdb-daemon.exe' system_path['qrexec_daemon_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-daemon.exe' # Specific to WNI - normally VM have this file system_path['qrexec_agent_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-agent.exe' defaults['libvirt_uri'] = 'wni:///' defaults['storage_class'] = QubesWniVmStorage
from __future__ import absolute_import from qubes.storage.wni import QubesWniVmStorage def apply(system_path, vm_files, defaults): system_path['qubes_base_dir'] = 'c:\\qubes' system_path['config_template_pv'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template.xml' system_path['config_template_hvm'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template-hvm.xml' system_path['qubes_icon_dir'] = \ 'c:/program files/Invisible Things Lab/Qubes/icons' system_path['qubesdb_daemon_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qubesdb-daemon.exe' system_path['qrexec_daemon_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-daemon.exe' system_path['qrexec_client_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-client.exe' # Specific to WNI - normally VM have this file system_path['qrexec_agent_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-agent.exe' defaults['libvirt_uri'] = 'wni:///' defaults['storage_class'] = QubesWniVmStorage
Add qrexec-client path to WNI settings
wni: Add qrexec-client path to WNI settings
Python
lgpl-2.1
marmarek/qubes-core-admin,QubesOS/qubes-core-admin,QubesOS/qubes-core-admin,woju/qubes-core-admin,marmarek/qubes-core-admin,QubesOS/qubes-core-admin,woju/qubes-core-admin,woju/qubes-core-admin,woju/qubes-core-admin,marmarek/qubes-core-admin
from __future__ import absolute_import from qubes.storage.wni import QubesWniVmStorage def apply(system_path, vm_files, defaults): system_path['qubes_base_dir'] = 'c:\\qubes' system_path['config_template_pv'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template.xml' system_path['config_template_hvm'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template-hvm.xml' system_path['qubes_icon_dir'] = \ 'c:/program files/Invisible Things Lab/Qubes/icons' system_path['qubesdb_daemon_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qubesdb-daemon.exe' system_path['qrexec_daemon_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-daemon.exe' + system_path['qrexec_client_path'] = \ + 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-client.exe' # Specific to WNI - normally VM have this file system_path['qrexec_agent_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-agent.exe' defaults['libvirt_uri'] = 'wni:///' defaults['storage_class'] = QubesWniVmStorage
Add qrexec-client path to WNI settings
## Code Before: from __future__ import absolute_import from qubes.storage.wni import QubesWniVmStorage def apply(system_path, vm_files, defaults): system_path['qubes_base_dir'] = 'c:\\qubes' system_path['config_template_pv'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template.xml' system_path['config_template_hvm'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template-hvm.xml' system_path['qubes_icon_dir'] = \ 'c:/program files/Invisible Things Lab/Qubes/icons' system_path['qubesdb_daemon_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qubesdb-daemon.exe' system_path['qrexec_daemon_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-daemon.exe' # Specific to WNI - normally VM have this file system_path['qrexec_agent_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-agent.exe' defaults['libvirt_uri'] = 'wni:///' defaults['storage_class'] = QubesWniVmStorage ## Instruction: Add qrexec-client path to WNI settings ## Code After: from __future__ import absolute_import from qubes.storage.wni import QubesWniVmStorage def apply(system_path, vm_files, defaults): system_path['qubes_base_dir'] = 'c:\\qubes' system_path['config_template_pv'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template.xml' system_path['config_template_hvm'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template-hvm.xml' system_path['qubes_icon_dir'] = \ 'c:/program files/Invisible Things Lab/Qubes/icons' system_path['qubesdb_daemon_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qubesdb-daemon.exe' system_path['qrexec_daemon_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-daemon.exe' system_path['qrexec_client_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-client.exe' # Specific to WNI - normally VM have this file system_path['qrexec_agent_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-agent.exe' defaults['libvirt_uri'] = 'wni:///' defaults['storage_class'] = QubesWniVmStorage
from __future__ import absolute_import from qubes.storage.wni import QubesWniVmStorage def apply(system_path, vm_files, defaults): system_path['qubes_base_dir'] = 'c:\\qubes' system_path['config_template_pv'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template.xml' system_path['config_template_hvm'] = 'c:/program files/Invisible Things Lab/Qubes/vm-template-hvm.xml' system_path['qubes_icon_dir'] = \ 'c:/program files/Invisible Things Lab/Qubes/icons' system_path['qubesdb_daemon_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qubesdb-daemon.exe' system_path['qrexec_daemon_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-daemon.exe' + system_path['qrexec_client_path'] = \ + 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-client.exe' # Specific to WNI - normally VM have this file system_path['qrexec_agent_path'] = \ 'c:/program files/Invisible Things Lab/Qubes/bin/qrexec-agent.exe' defaults['libvirt_uri'] = 'wni:///' defaults['storage_class'] = QubesWniVmStorage
36998345ef900286527a3896f70cf4a85414ccf8
rohrpost/main.py
rohrpost/main.py
import json from functools import partial from . import handlers # noqa from .message import send_error from .registry import HANDLERS REQUIRED_FIELDS = ['type', 'id'] try: DECODE_ERRORS = (json.JSONDecodeError, TypeError) except AttributeError: # Python 3.3 and 3.4 raise a ValueError instead of json.JSONDecodeError DECODE_ERRORS = (ValueError, TypeError) def handle_rohrpost_message(message): """ Handling of a rohrpost message will validate the required format: A valid JSON object including at least an "id" and "type" field. It then hands off further handling to the registered handler (if any). """ _send_error = partial(send_error, message, None, None) if not message.content['text']: return _send_error('Received empty message.') try: request = json.loads(message.content['text']) except DECODE_ERRORS as e: return _send_error('Could not decode JSON message. Error: {}'.format(str(e))) if not isinstance(request, dict): return _send_error('Expected a JSON object as message.') for field in REQUIRED_FIELDS: if field not in request: return _send_error("Missing required field '{}'.".format(field)) if not request['type'] in HANDLERS: return send_error( message, request['id'], request['type'], "Unknown message type '{}'.".format(request['type']), ) HANDLERS[request['type']](message, request)
import json from functools import partial from . import handlers # noqa from .message import send_error from .registry import HANDLERS REQUIRED_FIELDS = ['type', 'id'] try: DECODE_ERRORS = (json.JSONDecodeError, TypeError) except AttributeError: # Python 3.3 and 3.4 raise a ValueError instead of json.JSONDecodeError DECODE_ERRORS = (ValueError, TypeError) def handle_rohrpost_message(message): """ Handling of a rohrpost message will validate the required format: A valid JSON object including at least an "id" and "type" field. It then hands off further handling to the registered handler (if any). """ _send_error = partial(send_error, message=message, message_id=None, handler=None) if not message.content['text']: return _send_error(error='Received empty message.') try: request = json.loads(message.content['text']) except DECODE_ERRORS as e: return _send_error(error='Could not decode JSON message. Error: {}'.format(str(e))) if not isinstance(request, dict): return _send_error(error='Expected a JSON object as message.') for field in REQUIRED_FIELDS: if field not in request: return _send_error(error="Missing required field '{}'.".format(field)) if not request['type'] in HANDLERS: return send_error( message=message, message_id=request['id'], handler=request['type'], error="Unknown message type '{}'.".format(request['type']), ) HANDLERS[request['type']](message, request)
Use keyword arguments in code
Use keyword arguments in code
Python
mit
axsemantics/rohrpost,axsemantics/rohrpost
import json from functools import partial from . import handlers # noqa from .message import send_error from .registry import HANDLERS REQUIRED_FIELDS = ['type', 'id'] try: DECODE_ERRORS = (json.JSONDecodeError, TypeError) except AttributeError: # Python 3.3 and 3.4 raise a ValueError instead of json.JSONDecodeError DECODE_ERRORS = (ValueError, TypeError) def handle_rohrpost_message(message): """ Handling of a rohrpost message will validate the required format: A valid JSON object including at least an "id" and "type" field. It then hands off further handling to the registered handler (if any). """ - _send_error = partial(send_error, message, None, None) + _send_error = partial(send_error, message=message, message_id=None, handler=None) if not message.content['text']: - return _send_error('Received empty message.') + return _send_error(error='Received empty message.') try: request = json.loads(message.content['text']) except DECODE_ERRORS as e: - return _send_error('Could not decode JSON message. Error: {}'.format(str(e))) + return _send_error(error='Could not decode JSON message. Error: {}'.format(str(e))) if not isinstance(request, dict): - return _send_error('Expected a JSON object as message.') + return _send_error(error='Expected a JSON object as message.') for field in REQUIRED_FIELDS: if field not in request: - return _send_error("Missing required field '{}'.".format(field)) + return _send_error(error="Missing required field '{}'.".format(field)) if not request['type'] in HANDLERS: return send_error( - message, request['id'], request['type'], + message=message, message_id=request['id'], handler=request['type'], - "Unknown message type '{}'.".format(request['type']), + error="Unknown message type '{}'.".format(request['type']), ) HANDLERS[request['type']](message, request)
Use keyword arguments in code
## Code Before: import json from functools import partial from . import handlers # noqa from .message import send_error from .registry import HANDLERS REQUIRED_FIELDS = ['type', 'id'] try: DECODE_ERRORS = (json.JSONDecodeError, TypeError) except AttributeError: # Python 3.3 and 3.4 raise a ValueError instead of json.JSONDecodeError DECODE_ERRORS = (ValueError, TypeError) def handle_rohrpost_message(message): """ Handling of a rohrpost message will validate the required format: A valid JSON object including at least an "id" and "type" field. It then hands off further handling to the registered handler (if any). """ _send_error = partial(send_error, message, None, None) if not message.content['text']: return _send_error('Received empty message.') try: request = json.loads(message.content['text']) except DECODE_ERRORS as e: return _send_error('Could not decode JSON message. Error: {}'.format(str(e))) if not isinstance(request, dict): return _send_error('Expected a JSON object as message.') for field in REQUIRED_FIELDS: if field not in request: return _send_error("Missing required field '{}'.".format(field)) if not request['type'] in HANDLERS: return send_error( message, request['id'], request['type'], "Unknown message type '{}'.".format(request['type']), ) HANDLERS[request['type']](message, request) ## Instruction: Use keyword arguments in code ## Code After: import json from functools import partial from . import handlers # noqa from .message import send_error from .registry import HANDLERS REQUIRED_FIELDS = ['type', 'id'] try: DECODE_ERRORS = (json.JSONDecodeError, TypeError) except AttributeError: # Python 3.3 and 3.4 raise a ValueError instead of json.JSONDecodeError DECODE_ERRORS = (ValueError, TypeError) def handle_rohrpost_message(message): """ Handling of a rohrpost message will validate the required format: A valid JSON object including at least an "id" and "type" field. It then hands off further handling to the registered handler (if any). """ _send_error = partial(send_error, message=message, message_id=None, handler=None) if not message.content['text']: return _send_error(error='Received empty message.') try: request = json.loads(message.content['text']) except DECODE_ERRORS as e: return _send_error(error='Could not decode JSON message. Error: {}'.format(str(e))) if not isinstance(request, dict): return _send_error(error='Expected a JSON object as message.') for field in REQUIRED_FIELDS: if field not in request: return _send_error(error="Missing required field '{}'.".format(field)) if not request['type'] in HANDLERS: return send_error( message=message, message_id=request['id'], handler=request['type'], error="Unknown message type '{}'.".format(request['type']), ) HANDLERS[request['type']](message, request)
import json from functools import partial from . import handlers # noqa from .message import send_error from .registry import HANDLERS REQUIRED_FIELDS = ['type', 'id'] try: DECODE_ERRORS = (json.JSONDecodeError, TypeError) except AttributeError: # Python 3.3 and 3.4 raise a ValueError instead of json.JSONDecodeError DECODE_ERRORS = (ValueError, TypeError) def handle_rohrpost_message(message): """ Handling of a rohrpost message will validate the required format: A valid JSON object including at least an "id" and "type" field. It then hands off further handling to the registered handler (if any). """ - _send_error = partial(send_error, message, None, None) + _send_error = partial(send_error, message=message, message_id=None, handler=None) ? ++++++++ +++++++++++ ++++++++ if not message.content['text']: - return _send_error('Received empty message.') + return _send_error(error='Received empty message.') ? ++++++ try: request = json.loads(message.content['text']) except DECODE_ERRORS as e: - return _send_error('Could not decode JSON message. Error: {}'.format(str(e))) + return _send_error(error='Could not decode JSON message. Error: {}'.format(str(e))) ? ++++++ if not isinstance(request, dict): - return _send_error('Expected a JSON object as message.') + return _send_error(error='Expected a JSON object as message.') ? ++++++ for field in REQUIRED_FIELDS: if field not in request: - return _send_error("Missing required field '{}'.".format(field)) + return _send_error(error="Missing required field '{}'.".format(field)) ? ++++++ if not request['type'] in HANDLERS: return send_error( - message, request['id'], request['type'], + message=message, message_id=request['id'], handler=request['type'], ? ++++++++ +++++++++++ ++++++++ - "Unknown message type '{}'.".format(request['type']), + error="Unknown message type '{}'.".format(request['type']), ? ++++++ ) HANDLERS[request['type']](message, request)
4a6f76857a626dd756675a4fe1dd3660cf63d8b7
alg_fibonacci.py
alg_fibonacci.py
from __future__ import print_function import time def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main()
from __future__ import print_function def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): import time n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main()
Move module time to main()
Move module time to main()
Python
bsd-2-clause
bowen0701/algorithms_data_structures
from __future__ import print_function - import time def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): + import time n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main()
Move module time to main()
## Code Before: from __future__ import print_function import time def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main() ## Instruction: Move module time to main() ## Code After: from __future__ import print_function def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): import time n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main()
from __future__ import print_function - import time def fibonacci(n): """Get nth number of Fibonacci series by recursion.""" if n == 0: return 0 elif n == 1 or n == 2: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) def main(): + import time n = 13 print('{}th number of Fibonacci series: {}' .format(n, fibonacci(n))) if __name__ == '__main__': main()
c713273fe145418113d750579f8b135dc513c3b8
config.py
config.py
import os if os.environ.get('DATABASE_URL') is None: SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db' else: SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
import os SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
Delete default case for SQLALCHEMY_DATABASE_URI
Delete default case for SQLALCHEMY_DATABASE_URI if user doesn't set it, he coud have some problems with SQLite
Python
mit
Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot
import os - if os.environ.get('DATABASE_URL') is None: - SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db' - else: - SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] + SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] - SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
Delete default case for SQLALCHEMY_DATABASE_URI
## Code Before: import os if os.environ.get('DATABASE_URL') is None: SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db' else: SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning ## Instruction: Delete default case for SQLALCHEMY_DATABASE_URI ## Code After: import os SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
import os - if os.environ.get('DATABASE_URL') is None: - SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db' - else: - SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] ? ---- + SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] - SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
9c0d88ba1681949c02f2cd136efc0de1c23d170d
simuvex/procedures/libc___so___6/fileno.py
simuvex/procedures/libc___so___6/fileno.py
import simuvex from simuvex.s_type import SimTypeFd import logging l = logging.getLogger("simuvex.procedures.fileno") ###################################### # memset ###################################### class fileno(simuvex.SimProcedure): #pylint:disable=arguments-differ def run(self, f): self.argument_types = {0: SimTypeFd()} self.return_type = SimTypeFd() return f
import simuvex from simuvex.s_type import SimTypeFd, SimTypeTop from . import io_file_data_for_arch import logging l = logging.getLogger("simuvex.procedures.fileno") ###################################### # fileno ###################################### class fileno(simuvex.SimProcedure): #pylint:disable=arguments-differ def run(self, f): self.argument_types = {0: self.ty_ptr(SimTypeTop())} self.return_type = SimTypeFd() # Get FILE struct io_file_data = io_file_data_for_arch(self.state.arch) # Get the file descriptor from FILE struct fd = self.state.se.any_int(self.state.memory.load(f + io_file_data['fd'], 4 * 8, # int endness=self.state.arch.memory_endness)) return fd
Add logic for grabbing file descriptor from FILE struct
Add logic for grabbing file descriptor from FILE struct
Python
bsd-2-clause
chubbymaggie/angr,angr/angr,schieb/angr,tyb0807/angr,axt/angr,f-prettyland/angr,axt/angr,iamahuman/angr,angr/angr,iamahuman/angr,axt/angr,iamahuman/angr,f-prettyland/angr,chubbymaggie/angr,schieb/angr,angr/angr,tyb0807/angr,tyb0807/angr,chubbymaggie/angr,f-prettyland/angr,angr/simuvex,schieb/angr
import simuvex - from simuvex.s_type import SimTypeFd + from simuvex.s_type import SimTypeFd, SimTypeTop + + from . import io_file_data_for_arch import logging l = logging.getLogger("simuvex.procedures.fileno") + ###################################### - # memset + # fileno ###################################### + class fileno(simuvex.SimProcedure): #pylint:disable=arguments-differ def run(self, f): - self.argument_types = {0: SimTypeFd()} + self.argument_types = {0: self.ty_ptr(SimTypeTop())} self.return_type = SimTypeFd() - return f + # Get FILE struct + io_file_data = io_file_data_for_arch(self.state.arch) + + # Get the file descriptor from FILE struct + fd = self.state.se.any_int(self.state.memory.load(f + io_file_data['fd'], + 4 * 8, # int + endness=self.state.arch.memory_endness)) + return fd +
Add logic for grabbing file descriptor from FILE struct
## Code Before: import simuvex from simuvex.s_type import SimTypeFd import logging l = logging.getLogger("simuvex.procedures.fileno") ###################################### # memset ###################################### class fileno(simuvex.SimProcedure): #pylint:disable=arguments-differ def run(self, f): self.argument_types = {0: SimTypeFd()} self.return_type = SimTypeFd() return f ## Instruction: Add logic for grabbing file descriptor from FILE struct ## Code After: import simuvex from simuvex.s_type import SimTypeFd, SimTypeTop from . import io_file_data_for_arch import logging l = logging.getLogger("simuvex.procedures.fileno") ###################################### # fileno ###################################### class fileno(simuvex.SimProcedure): #pylint:disable=arguments-differ def run(self, f): self.argument_types = {0: self.ty_ptr(SimTypeTop())} self.return_type = SimTypeFd() # Get FILE struct io_file_data = io_file_data_for_arch(self.state.arch) # Get the file descriptor from FILE struct fd = self.state.se.any_int(self.state.memory.load(f + io_file_data['fd'], 4 * 8, # int endness=self.state.arch.memory_endness)) return fd
import simuvex - from simuvex.s_type import SimTypeFd + from simuvex.s_type import SimTypeFd, SimTypeTop ? ++++++++++++ + + from . import io_file_data_for_arch import logging l = logging.getLogger("simuvex.procedures.fileno") + ###################################### - # memset + # fileno ###################################### + class fileno(simuvex.SimProcedure): #pylint:disable=arguments-differ def run(self, f): - self.argument_types = {0: SimTypeFd()} ? ^^ + self.argument_types = {0: self.ty_ptr(SimTypeTop())} ? ++++++++++++ ^^^ + self.return_type = SimTypeFd() + + # Get FILE struct + io_file_data = io_file_data_for_arch(self.state.arch) + + # Get the file descriptor from FILE struct + fd = self.state.se.any_int(self.state.memory.load(f + io_file_data['fd'], + 4 * 8, # int + endness=self.state.arch.memory_endness)) - return f + return fd ? +
3ffc101a1a8b1ec17e5f2e509a1e5182a1f6f4b9
fzn/utils.py
fzn/utils.py
import subprocess as sp import signal import threading import os SIGTERM_TIMEOUT = 1.0 class Command(object): def __init__(self, cmd, memlimit=None): self.cmd = cmd self.memlimit = memlimit self.process = None self.stdout = None self.stderr = None self.exitcode = None self.timed_out = False def run(self, timeout=None): def target(): self.process = sp.Popen(self.cmd, stdout=sp.PIPE, stderr=sp.PIPE, shell=True, preexec_fn=os.setpgrp) self.stdout, self.stderr = self.process.communicate() self.exitcode = self.process.returncode thread = threading.Thread(target=target) thread.start() thread.join(float(timeout)) if thread.is_alive(): self.timed_out = True # Send the TERM signal to all the process groups os.killpg(self.process.pid, signal.SIGTERM) thread.join(SIGTERM_TIMEOUT) if thread.is_alive(): # Send the KILL signal if the process hasn't exited by now. os.killpg(self.process.pid, signal.SIGKILL) self.process.kill() thread.join()
import subprocess as sp import signal import threading import os SIGTERM_TIMEOUT = 1.0 class Command(object): def __init__(self, cmd, memlimit=None): self.cmd = cmd self.memlimit = memlimit self.process = None self.stdout = None self.stderr = None self.exitcode = None self.timed_out = False def run(self, timeout=None): def target(): cmd = self.cmd if self.memlimit: cmd = "ulimit -v %d; %s" % (self.memlimit, cmd) self.process = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE, shell=True, preexec_fn=os.setpgrp) self.stdout, self.stderr = self.process.communicate() self.exitcode = self.process.returncode thread = threading.Thread(target=target) thread.start() thread.join(float(timeout)) if thread.is_alive(): self.timed_out = True # Send the TERM signal to all the process groups os.killpg(self.process.pid, signal.SIGTERM) thread.join(SIGTERM_TIMEOUT) if thread.is_alive(): # Send the KILL signal if the process hasn't exited by now. os.killpg(self.process.pid, signal.SIGKILL) self.process.kill() thread.join()
Enable Command to support memory limiting.
Enable Command to support memory limiting.
Python
lgpl-2.1
eomahony/Numberjack,eomahony/Numberjack,eomahony/Numberjack,JElchison/Numberjack,JElchison/Numberjack,JElchison/Numberjack,JElchison/Numberjack,JElchison/Numberjack,eomahony/Numberjack,eomahony/Numberjack
import subprocess as sp import signal import threading import os SIGTERM_TIMEOUT = 1.0 class Command(object): def __init__(self, cmd, memlimit=None): self.cmd = cmd self.memlimit = memlimit self.process = None self.stdout = None self.stderr = None self.exitcode = None self.timed_out = False def run(self, timeout=None): def target(): + cmd = self.cmd + if self.memlimit: + cmd = "ulimit -v %d; %s" % (self.memlimit, cmd) - self.process = sp.Popen(self.cmd, + self.process = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE, shell=True, preexec_fn=os.setpgrp) self.stdout, self.stderr = self.process.communicate() self.exitcode = self.process.returncode thread = threading.Thread(target=target) thread.start() thread.join(float(timeout)) if thread.is_alive(): self.timed_out = True # Send the TERM signal to all the process groups os.killpg(self.process.pid, signal.SIGTERM) thread.join(SIGTERM_TIMEOUT) if thread.is_alive(): # Send the KILL signal if the process hasn't exited by now. os.killpg(self.process.pid, signal.SIGKILL) self.process.kill() thread.join()
Enable Command to support memory limiting.
## Code Before: import subprocess as sp import signal import threading import os SIGTERM_TIMEOUT = 1.0 class Command(object): def __init__(self, cmd, memlimit=None): self.cmd = cmd self.memlimit = memlimit self.process = None self.stdout = None self.stderr = None self.exitcode = None self.timed_out = False def run(self, timeout=None): def target(): self.process = sp.Popen(self.cmd, stdout=sp.PIPE, stderr=sp.PIPE, shell=True, preexec_fn=os.setpgrp) self.stdout, self.stderr = self.process.communicate() self.exitcode = self.process.returncode thread = threading.Thread(target=target) thread.start() thread.join(float(timeout)) if thread.is_alive(): self.timed_out = True # Send the TERM signal to all the process groups os.killpg(self.process.pid, signal.SIGTERM) thread.join(SIGTERM_TIMEOUT) if thread.is_alive(): # Send the KILL signal if the process hasn't exited by now. os.killpg(self.process.pid, signal.SIGKILL) self.process.kill() thread.join() ## Instruction: Enable Command to support memory limiting. ## Code After: import subprocess as sp import signal import threading import os SIGTERM_TIMEOUT = 1.0 class Command(object): def __init__(self, cmd, memlimit=None): self.cmd = cmd self.memlimit = memlimit self.process = None self.stdout = None self.stderr = None self.exitcode = None self.timed_out = False def run(self, timeout=None): def target(): cmd = self.cmd if self.memlimit: cmd = "ulimit -v %d; %s" % (self.memlimit, cmd) self.process = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE, shell=True, preexec_fn=os.setpgrp) self.stdout, self.stderr = self.process.communicate() self.exitcode = self.process.returncode thread = threading.Thread(target=target) thread.start() thread.join(float(timeout)) if thread.is_alive(): self.timed_out = True # Send the TERM signal to all the process groups os.killpg(self.process.pid, signal.SIGTERM) thread.join(SIGTERM_TIMEOUT) if thread.is_alive(): # Send the KILL signal if the process hasn't exited by now. os.killpg(self.process.pid, signal.SIGKILL) self.process.kill() thread.join()
import subprocess as sp import signal import threading import os SIGTERM_TIMEOUT = 1.0 class Command(object): def __init__(self, cmd, memlimit=None): self.cmd = cmd self.memlimit = memlimit self.process = None self.stdout = None self.stderr = None self.exitcode = None self.timed_out = False def run(self, timeout=None): def target(): + cmd = self.cmd + if self.memlimit: + cmd = "ulimit -v %d; %s" % (self.memlimit, cmd) - self.process = sp.Popen(self.cmd, ? ----- + self.process = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE, shell=True, preexec_fn=os.setpgrp) self.stdout, self.stderr = self.process.communicate() self.exitcode = self.process.returncode thread = threading.Thread(target=target) thread.start() thread.join(float(timeout)) if thread.is_alive(): self.timed_out = True # Send the TERM signal to all the process groups os.killpg(self.process.pid, signal.SIGTERM) thread.join(SIGTERM_TIMEOUT) if thread.is_alive(): # Send the KILL signal if the process hasn't exited by now. os.killpg(self.process.pid, signal.SIGKILL) self.process.kill() thread.join()
850464de61237a7fae64219a39e9c937f7d40c01
randcat.py
randcat.py
import random random.seed() # this initializes with the Date, which I think is a novel enough seed while True: # if we're going with a mimicing of cat /dev/random, it'll pretty much just go until it's killed print(chr(random.getrandbits(8)), end='')
import calendar import time seed = calendar.timegm(time.gmtime()) # We'll use the epoch time as a seed. def random (seed): seed2 = (seed*297642 + 83782)/70000 return int(seed2) % 70000; p = seed while True: # if we're going with a mimicing of cat /dev/random, it'll pretty much just go until it's killed p = random(p) print(chr(p % 256), end="") p = p % 4000
Make it so we're using our own seed.
Make it so we're using our own seed.
Python
apache-2.0
Tombert/RandCat
- import random + import calendar + import time - random.seed() # this initializes with the Date, which I think is a novel enough seed + seed = calendar.timegm(time.gmtime()) # We'll use the epoch time as a seed. + def random (seed): + seed2 = (seed*297642 + 83782)/70000 + return int(seed2) % 70000; + + + p = seed while True: # if we're going with a mimicing of cat /dev/random, it'll pretty much just go until it's killed - print(chr(random.getrandbits(8)), end='') + p = random(p) + print(chr(p % 256), end="") + p = p % 4000
Make it so we're using our own seed.
## Code Before: import random random.seed() # this initializes with the Date, which I think is a novel enough seed while True: # if we're going with a mimicing of cat /dev/random, it'll pretty much just go until it's killed print(chr(random.getrandbits(8)), end='') ## Instruction: Make it so we're using our own seed. ## Code After: import calendar import time seed = calendar.timegm(time.gmtime()) # We'll use the epoch time as a seed. def random (seed): seed2 = (seed*297642 + 83782)/70000 return int(seed2) % 70000; p = seed while True: # if we're going with a mimicing of cat /dev/random, it'll pretty much just go until it's killed p = random(p) print(chr(p % 256), end="") p = p % 4000
- import random + import calendar + import time - random.seed() # this initializes with the Date, which I think is a novel enough seed + seed = calendar.timegm(time.gmtime()) # We'll use the epoch time as a seed. + def random (seed): + seed2 = (seed*297642 + 83782)/70000 + return int(seed2) % 70000; + + + p = seed while True: # if we're going with a mimicing of cat /dev/random, it'll pretty much just go until it's killed - print(chr(random.getrandbits(8)), end='') + p = random(p) + print(chr(p % 256), end="") + p = p % 4000
d14160537292c87f870fa8c7d99c253b61420dde
blazeweb/registry.py
blazeweb/registry.py
from paste.registry import StackedObjectProxy as PasteSOP class StackedObjectProxy(PasteSOP): # override b/c of # http://trac.pythonpaste.org/pythonpaste/ticket/482 def _pop_object(self, obj=None): """Remove a thread-local object. If ``obj`` is given, it is checked against the popped object and an error is emitted if they don't match. """ try: popped = self.____local__.objects.pop() if obj is not None and popped is not obj: raise AssertionError( 'The object popped (%s) is not the same as the object ' 'expected (%s)' % (popped, obj)) except AttributeError: raise AssertionError('No object has been registered for this thread')
from paste.registry import StackedObjectProxy as PasteSOP class StackedObjectProxy(PasteSOP): # override b/c of # http://trac.pythonpaste.org/pythonpaste/ticket/482 def _pop_object(self, obj=None): """Remove a thread-local object. If ``obj`` is given, it is checked against the popped object and an error is emitted if they don't match. """ try: popped = self.____local__.objects.pop() if obj is not None and popped is not obj: raise AssertionError( 'The object popped (%s) is not the same as the object ' 'expected (%s)' % (popped, obj)) except AttributeError: raise AssertionError('No object has been registered for this thread') def __bool__(self): return bool(self._current_obj())
Fix boolean conversion of StackedObjectProxy in Python 3
Fix boolean conversion of StackedObjectProxy in Python 3
Python
bsd-3-clause
level12/blazeweb,level12/blazeweb,level12/blazeweb
from paste.registry import StackedObjectProxy as PasteSOP class StackedObjectProxy(PasteSOP): # override b/c of # http://trac.pythonpaste.org/pythonpaste/ticket/482 def _pop_object(self, obj=None): """Remove a thread-local object. If ``obj`` is given, it is checked against the popped object and an error is emitted if they don't match. """ try: popped = self.____local__.objects.pop() if obj is not None and popped is not obj: raise AssertionError( 'The object popped (%s) is not the same as the object ' 'expected (%s)' % (popped, obj)) except AttributeError: raise AssertionError('No object has been registered for this thread') + def __bool__(self): + return bool(self._current_obj()) +
Fix boolean conversion of StackedObjectProxy in Python 3
## Code Before: from paste.registry import StackedObjectProxy as PasteSOP class StackedObjectProxy(PasteSOP): # override b/c of # http://trac.pythonpaste.org/pythonpaste/ticket/482 def _pop_object(self, obj=None): """Remove a thread-local object. If ``obj`` is given, it is checked against the popped object and an error is emitted if they don't match. """ try: popped = self.____local__.objects.pop() if obj is not None and popped is not obj: raise AssertionError( 'The object popped (%s) is not the same as the object ' 'expected (%s)' % (popped, obj)) except AttributeError: raise AssertionError('No object has been registered for this thread') ## Instruction: Fix boolean conversion of StackedObjectProxy in Python 3 ## Code After: from paste.registry import StackedObjectProxy as PasteSOP class StackedObjectProxy(PasteSOP): # override b/c of # http://trac.pythonpaste.org/pythonpaste/ticket/482 def _pop_object(self, obj=None): """Remove a thread-local object. If ``obj`` is given, it is checked against the popped object and an error is emitted if they don't match. """ try: popped = self.____local__.objects.pop() if obj is not None and popped is not obj: raise AssertionError( 'The object popped (%s) is not the same as the object ' 'expected (%s)' % (popped, obj)) except AttributeError: raise AssertionError('No object has been registered for this thread') def __bool__(self): return bool(self._current_obj())
from paste.registry import StackedObjectProxy as PasteSOP class StackedObjectProxy(PasteSOP): # override b/c of # http://trac.pythonpaste.org/pythonpaste/ticket/482 def _pop_object(self, obj=None): """Remove a thread-local object. If ``obj`` is given, it is checked against the popped object and an error is emitted if they don't match. """ try: popped = self.____local__.objects.pop() if obj is not None and popped is not obj: raise AssertionError( 'The object popped (%s) is not the same as the object ' 'expected (%s)' % (popped, obj)) except AttributeError: raise AssertionError('No object has been registered for this thread') + + def __bool__(self): + return bool(self._current_obj())
a32e61e9cdf2eababb568659766688a731b121cb
warlock/__init__.py
warlock/__init__.py
"""Public-facing Warlock API""" from warlock.core import model_factory # NOQA from warlock.exceptions import InvalidOperation # NOQA
"""Public-facing Warlock API""" from warlock.core import model_factory # noqa: F401 from warlock.exceptions import InvalidOperation # noqa: F401
Apply 'no blanket NOQA statements' fixes enforced by pre-commit hook
Apply 'no blanket NOQA statements' fixes enforced by pre-commit hook
Python
apache-2.0
bcwaldon/warlock
"""Public-facing Warlock API""" - from warlock.core import model_factory # NOQA + from warlock.core import model_factory # noqa: F401 - from warlock.exceptions import InvalidOperation # NOQA + from warlock.exceptions import InvalidOperation # noqa: F401
Apply 'no blanket NOQA statements' fixes enforced by pre-commit hook
## Code Before: """Public-facing Warlock API""" from warlock.core import model_factory # NOQA from warlock.exceptions import InvalidOperation # NOQA ## Instruction: Apply 'no blanket NOQA statements' fixes enforced by pre-commit hook ## Code After: """Public-facing Warlock API""" from warlock.core import model_factory # noqa: F401 from warlock.exceptions import InvalidOperation # noqa: F401
"""Public-facing Warlock API""" - from warlock.core import model_factory # NOQA ? ^^^^ + from warlock.core import model_factory # noqa: F401 ? ^^^^^^^^^^ - from warlock.exceptions import InvalidOperation # NOQA ? ^^^^ + from warlock.exceptions import InvalidOperation # noqa: F401 ? ^^^^^^^^^^
61bbd4e8fc0712fe56614481173eb86d409eb8d7
tests/test_linked_list.py
tests/test_linked_list.py
from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() results = [l.insert(val) for val in xrange(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...")
from builtins import range from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() results = [l.insert(val) for val in range(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...")
Fix range issue with travis
Fix range issue with travis
Python
mit
apranav19/pystructures
+ from builtins import range from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() - results = [l.insert(val) for val in xrange(10, 100, 10)] + results = [l.insert(val) for val in range(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...")
Fix range issue with travis
## Code Before: from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() results = [l.insert(val) for val in xrange(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...") ## Instruction: Fix range issue with travis ## Code After: from builtins import range from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() results = [l.insert(val) for val in range(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...")
+ from builtins import range from unittest import TestCase from pystructures.linked_lists import LinkedList, Node class TestNode(TestCase): def test_value(self): """ A simple test to check the Node's value """ node = Node(10) self.assertEqual(10, node.value) def test_improper_node(self): """ A test to check if an invalid data type is set as a node's next""" node = Node(10) with self.assertRaises(ValueError): node.next = "Hello" class TestLinkedList(TestCase): def test_insert(self): """ A simple test to check if insertion works as expected in a singly linked list """ l = LinkedList() - results = [l.insert(val) for val in xrange(10, 100, 10)] ? - + results = [l.insert(val) for val in range(10, 100, 10)] self.assertEqual(len(set(results)), 1) self.assertTrue(results[0], msg="Testing for successful insertion...") self.assertEqual(len(results), l.size, msg="Testing if # of results equal list size...")
1ff616fe4f6ff0ff295eeeaa4a817851df750e51
openslides/utils/validate.py
openslides/utils/validate.py
import bleach allowed_tags = [ "a", "img", # links and images "br", "p", "span", "blockquote", # text layout "strike", "strong", "u", "em", "sup", "sub", "pre", # text formatting "h1", "h2", "h3", "h4", "h5", "h6", # headings "ol", "ul", "li", # lists "table", "caption", "thead", "tbody", "th", "tr", "td", # tables ] allowed_attributes = { "*": ["class", "style"], "img": ["alt", "src", "title"], "a": ["href", "title"], "th": ["scope"], "ol": ["start"], } allowed_styles = [ "color", "background-color", "height", "width", "text-align", "float", "padding", "text-decoration", ] def validate_html(html: str) -> str: """ This method takes a string and escapes all non-whitelisted html entries. Every field of a model that is loaded trusted in the DOM should be validated. During copy and paste from Word maybe some tabs are spread over the html. Remove them. """ html = html.replace("\t", "") return bleach.clean( html, tags=allowed_tags, attributes=allowed_attributes, styles=allowed_styles )
import bleach allowed_tags = [ "a", "img", # links and images "br", "p", "span", "blockquote", # text layout "strike", "del", "ins", "strong", "u", "em", "sup", "sub", "pre", # text formatting "h1", "h2", "h3", "h4", "h5", "h6", # headings "ol", "ul", "li", # lists "table", "caption", "thead", "tbody", "th", "tr", "td", # tables ] allowed_attributes = { "*": ["class", "style"], "img": ["alt", "src", "title"], "a": ["href", "title"], "th": ["scope"], "ol": ["start"], } allowed_styles = [ "color", "background-color", "height", "width", "text-align", "float", "padding", "text-decoration", ] def validate_html(html: str) -> str: """ This method takes a string and escapes all non-whitelisted html entries. Every field of a model that is loaded trusted in the DOM should be validated. During copy and paste from Word maybe some tabs are spread over the html. Remove them. """ html = html.replace("\t", "") return bleach.clean( html, tags=allowed_tags, attributes=allowed_attributes, styles=allowed_styles )
Allow <del> and <ins> html tags.
Allow <del> and <ins> html tags.
Python
mit
tsiegleauq/OpenSlides,ostcar/OpenSlides,FinnStutzenstein/OpenSlides,normanjaeckel/OpenSlides,jwinzer/OpenSlides,OpenSlides/OpenSlides,tsiegleauq/OpenSlides,jwinzer/OpenSlides,FinnStutzenstein/OpenSlides,CatoTH/OpenSlides,CatoTH/OpenSlides,OpenSlides/OpenSlides,tsiegleauq/OpenSlides,CatoTH/OpenSlides,normanjaeckel/OpenSlides,ostcar/OpenSlides,ostcar/OpenSlides,FinnStutzenstein/OpenSlides,normanjaeckel/OpenSlides,jwinzer/OpenSlides,normanjaeckel/OpenSlides,FinnStutzenstein/OpenSlides,jwinzer/OpenSlides,CatoTH/OpenSlides,jwinzer/OpenSlides
import bleach allowed_tags = [ "a", "img", # links and images "br", "p", "span", "blockquote", # text layout "strike", + "del", + "ins", "strong", "u", "em", "sup", "sub", "pre", # text formatting "h1", "h2", "h3", "h4", "h5", "h6", # headings "ol", "ul", "li", # lists "table", "caption", "thead", "tbody", "th", "tr", "td", # tables ] allowed_attributes = { "*": ["class", "style"], "img": ["alt", "src", "title"], "a": ["href", "title"], "th": ["scope"], "ol": ["start"], } allowed_styles = [ "color", "background-color", "height", "width", "text-align", "float", "padding", "text-decoration", ] def validate_html(html: str) -> str: """ This method takes a string and escapes all non-whitelisted html entries. Every field of a model that is loaded trusted in the DOM should be validated. During copy and paste from Word maybe some tabs are spread over the html. Remove them. """ html = html.replace("\t", "") return bleach.clean( html, tags=allowed_tags, attributes=allowed_attributes, styles=allowed_styles )
Allow <del> and <ins> html tags.
## Code Before: import bleach allowed_tags = [ "a", "img", # links and images "br", "p", "span", "blockquote", # text layout "strike", "strong", "u", "em", "sup", "sub", "pre", # text formatting "h1", "h2", "h3", "h4", "h5", "h6", # headings "ol", "ul", "li", # lists "table", "caption", "thead", "tbody", "th", "tr", "td", # tables ] allowed_attributes = { "*": ["class", "style"], "img": ["alt", "src", "title"], "a": ["href", "title"], "th": ["scope"], "ol": ["start"], } allowed_styles = [ "color", "background-color", "height", "width", "text-align", "float", "padding", "text-decoration", ] def validate_html(html: str) -> str: """ This method takes a string and escapes all non-whitelisted html entries. Every field of a model that is loaded trusted in the DOM should be validated. During copy and paste from Word maybe some tabs are spread over the html. Remove them. """ html = html.replace("\t", "") return bleach.clean( html, tags=allowed_tags, attributes=allowed_attributes, styles=allowed_styles ) ## Instruction: Allow <del> and <ins> html tags. ## Code After: import bleach allowed_tags = [ "a", "img", # links and images "br", "p", "span", "blockquote", # text layout "strike", "del", "ins", "strong", "u", "em", "sup", "sub", "pre", # text formatting "h1", "h2", "h3", "h4", "h5", "h6", # headings "ol", "ul", "li", # lists "table", "caption", "thead", "tbody", "th", "tr", "td", # tables ] allowed_attributes = { "*": ["class", "style"], "img": ["alt", "src", "title"], "a": ["href", "title"], "th": ["scope"], "ol": ["start"], } allowed_styles = [ "color", "background-color", "height", "width", "text-align", "float", "padding", "text-decoration", ] def validate_html(html: str) -> str: """ This method takes a string and escapes all non-whitelisted html entries. Every field of a model that is loaded trusted in the DOM should be validated. During copy and paste from Word maybe some tabs are spread over the html. Remove them. """ html = html.replace("\t", "") return bleach.clean( html, tags=allowed_tags, attributes=allowed_attributes, styles=allowed_styles )
import bleach allowed_tags = [ "a", "img", # links and images "br", "p", "span", "blockquote", # text layout "strike", + "del", + "ins", "strong", "u", "em", "sup", "sub", "pre", # text formatting "h1", "h2", "h3", "h4", "h5", "h6", # headings "ol", "ul", "li", # lists "table", "caption", "thead", "tbody", "th", "tr", "td", # tables ] allowed_attributes = { "*": ["class", "style"], "img": ["alt", "src", "title"], "a": ["href", "title"], "th": ["scope"], "ol": ["start"], } allowed_styles = [ "color", "background-color", "height", "width", "text-align", "float", "padding", "text-decoration", ] def validate_html(html: str) -> str: """ This method takes a string and escapes all non-whitelisted html entries. Every field of a model that is loaded trusted in the DOM should be validated. During copy and paste from Word maybe some tabs are spread over the html. Remove them. """ html = html.replace("\t", "") return bleach.clean( html, tags=allowed_tags, attributes=allowed_attributes, styles=allowed_styles )
b58caeae59a5ab363b4b6b40cbd19004b40dd206
calvin/actorstore/systemactors/sensor/Distance.py
calvin/actorstore/systemactors/sensor/Distance.py
from calvin.actor.actor import Actor, manage, condition, stateguard class Distance(Actor): """ Measure distance. Takes the frequency of measurements, in Hz, as input. Outputs: meters : Measured distance, in meters """ @manage(['frequency']) def init(self, frequency): self.frequency = frequency self.setup() def setup(self): self.use("calvinsys.sensors.distance", shorthand="distance") self['distance'].start(self.frequency) def will_migrate(self): self['distance'].stop() def did_migrate(self): self.setup() @stateguard(lambda self: self['distance'].has_data()) @condition([], ['meters']) def measure(self): distance = self['distance'].read() return (distance,) action_priority = (measure,) requires = ['calvinsys.sensors.distance']
from calvin.actor.actor import Actor, manage, condition, stateguard class Distance(Actor): """ Measure distance. Takes the frequency of measurements, in Hz, as input. Outputs: meters : Measured distance, in meters """ @manage(['frequency']) def init(self, frequency): self.frequency = frequency self.setup() def setup(self): self.use("calvinsys.sensors.distance", shorthand="distance") self['distance'].start(self.frequency) def will_migrate(self): self['distance'].stop() def did_migrate(self): self.setup() def will_end(self): self['distance'].stop() @stateguard(lambda self: self['distance'].has_data()) @condition([], ['meters']) def measure(self): distance = self['distance'].read() return (distance,) action_priority = (measure,) requires = ['calvinsys.sensors.distance']
Fix a bug where periodic timers weren't removed when application was stopped. FIXME: Check up on the semantics of will/did_start, will_migrate, did_migrate, will_stop.
Fix a bug where periodic timers weren't removed when application was stopped. FIXME: Check up on the semantics of will/did_start, will_migrate, did_migrate, will_stop.
Python
apache-2.0
EricssonResearch/calvin-base,EricssonResearch/calvin-base,EricssonResearch/calvin-base,EricssonResearch/calvin-base
from calvin.actor.actor import Actor, manage, condition, stateguard class Distance(Actor): """ Measure distance. Takes the frequency of measurements, in Hz, as input. Outputs: meters : Measured distance, in meters """ @manage(['frequency']) def init(self, frequency): self.frequency = frequency self.setup() def setup(self): self.use("calvinsys.sensors.distance", shorthand="distance") self['distance'].start(self.frequency) def will_migrate(self): self['distance'].stop() def did_migrate(self): self.setup() + def will_end(self): + self['distance'].stop() + + @stateguard(lambda self: self['distance'].has_data()) @condition([], ['meters']) def measure(self): distance = self['distance'].read() return (distance,) action_priority = (measure,) requires = ['calvinsys.sensors.distance']
Fix a bug where periodic timers weren't removed when application was stopped. FIXME: Check up on the semantics of will/did_start, will_migrate, did_migrate, will_stop.
## Code Before: from calvin.actor.actor import Actor, manage, condition, stateguard class Distance(Actor): """ Measure distance. Takes the frequency of measurements, in Hz, as input. Outputs: meters : Measured distance, in meters """ @manage(['frequency']) def init(self, frequency): self.frequency = frequency self.setup() def setup(self): self.use("calvinsys.sensors.distance", shorthand="distance") self['distance'].start(self.frequency) def will_migrate(self): self['distance'].stop() def did_migrate(self): self.setup() @stateguard(lambda self: self['distance'].has_data()) @condition([], ['meters']) def measure(self): distance = self['distance'].read() return (distance,) action_priority = (measure,) requires = ['calvinsys.sensors.distance'] ## Instruction: Fix a bug where periodic timers weren't removed when application was stopped. FIXME: Check up on the semantics of will/did_start, will_migrate, did_migrate, will_stop. ## Code After: from calvin.actor.actor import Actor, manage, condition, stateguard class Distance(Actor): """ Measure distance. Takes the frequency of measurements, in Hz, as input. Outputs: meters : Measured distance, in meters """ @manage(['frequency']) def init(self, frequency): self.frequency = frequency self.setup() def setup(self): self.use("calvinsys.sensors.distance", shorthand="distance") self['distance'].start(self.frequency) def will_migrate(self): self['distance'].stop() def did_migrate(self): self.setup() def will_end(self): self['distance'].stop() @stateguard(lambda self: self['distance'].has_data()) @condition([], ['meters']) def measure(self): distance = self['distance'].read() return (distance,) action_priority = (measure,) requires = ['calvinsys.sensors.distance']
from calvin.actor.actor import Actor, manage, condition, stateguard class Distance(Actor): """ Measure distance. Takes the frequency of measurements, in Hz, as input. Outputs: meters : Measured distance, in meters """ @manage(['frequency']) def init(self, frequency): self.frequency = frequency self.setup() def setup(self): self.use("calvinsys.sensors.distance", shorthand="distance") self['distance'].start(self.frequency) def will_migrate(self): self['distance'].stop() def did_migrate(self): self.setup() + def will_end(self): + self['distance'].stop() + + @stateguard(lambda self: self['distance'].has_data()) @condition([], ['meters']) def measure(self): distance = self['distance'].read() return (distance,) action_priority = (measure,) requires = ['calvinsys.sensors.distance']
59d44ba76a9b2f98375fa2f893dabc0376de6f82
localeurl/models.py
localeurl/models.py
from django.conf import settings from django.core import urlresolvers from django.utils import translation from localeurl import utils def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs') or {} locale = utils.supported_language(reverse_kwargs.pop( 'locale', translation.get_language())) url = django_reverse(*args, **kwargs) _, path = utils.strip_script_prefix(url) return utils.locale_url(path, locale) django_reverse = None def patch_reverse(): """ Monkey-patches the urlresolvers.reverse function. Will not patch twice. """ global django_reverse if urlresolvers.reverse is not reverse: django_reverse = urlresolvers.reverse urlresolvers.reverse = reverse if settings.USE_I18N: patch_reverse()
from django.conf import settings from django.core import urlresolvers from django.utils import translation from django.contrib.auth import views as auth_views from localeurl import utils def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs') or {} locale = utils.supported_language(reverse_kwargs.pop( 'locale', translation.get_language())) url = django_reverse(*args, **kwargs) _, path = utils.strip_script_prefix(url) return utils.locale_url(path, locale) django_reverse = None def patch_reverse(): """ Monkey-patches the urlresolvers.reverse function. Will not patch twice. """ global django_reverse if urlresolvers.reverse is not reverse: django_reverse = urlresolvers.reverse urlresolvers.reverse = reverse def redirect_to_login(next, login_url, *args, **kwargs): if not login_url: login_url = settings.LOGIN_URL login_url = utils.locale_url(login_url, translation.get_language()) return django_redirect_to_login(next, login_url, *args, **kwargs) django_redirect_to_login = None def patch_redirect_to_login(): """ Monkey-patches the redirect_to_login function. Will not patch twice. """ global django_redirect_to_login if auth_views.redirect_to_login is not redirect_to_login: django_redirect_to_login = auth_views.redirect_to_login auth_views.redirect_to_login = redirect_to_login if settings.USE_I18N: patch_reverse() patch_redirect_to_login()
Patch redirect_to_login to maintain locale
Patch redirect_to_login to maintain locale Signed-off-by: Simon Luijk <088e16a1019277b15d58faf0541e11910eb756f6@simonluijk.com>
Python
mit
simonluijk/django-localeurl
from django.conf import settings from django.core import urlresolvers from django.utils import translation + from django.contrib.auth import views as auth_views from localeurl import utils + def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs') or {} locale = utils.supported_language(reverse_kwargs.pop( 'locale', translation.get_language())) url = django_reverse(*args, **kwargs) _, path = utils.strip_script_prefix(url) return utils.locale_url(path, locale) django_reverse = None def patch_reverse(): """ Monkey-patches the urlresolvers.reverse function. Will not patch twice. """ global django_reverse if urlresolvers.reverse is not reverse: django_reverse = urlresolvers.reverse urlresolvers.reverse = reverse + + def redirect_to_login(next, login_url, *args, **kwargs): + if not login_url: + login_url = settings.LOGIN_URL + login_url = utils.locale_url(login_url, translation.get_language()) + return django_redirect_to_login(next, login_url, *args, **kwargs) + + django_redirect_to_login = None + + def patch_redirect_to_login(): + """ + Monkey-patches the redirect_to_login function. Will not patch twice. + """ + global django_redirect_to_login + if auth_views.redirect_to_login is not redirect_to_login: + django_redirect_to_login = auth_views.redirect_to_login + auth_views.redirect_to_login = redirect_to_login + + if settings.USE_I18N: patch_reverse() + patch_redirect_to_login()
Patch redirect_to_login to maintain locale
## Code Before: from django.conf import settings from django.core import urlresolvers from django.utils import translation from localeurl import utils def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs') or {} locale = utils.supported_language(reverse_kwargs.pop( 'locale', translation.get_language())) url = django_reverse(*args, **kwargs) _, path = utils.strip_script_prefix(url) return utils.locale_url(path, locale) django_reverse = None def patch_reverse(): """ Monkey-patches the urlresolvers.reverse function. Will not patch twice. """ global django_reverse if urlresolvers.reverse is not reverse: django_reverse = urlresolvers.reverse urlresolvers.reverse = reverse if settings.USE_I18N: patch_reverse() ## Instruction: Patch redirect_to_login to maintain locale ## Code After: from django.conf import settings from django.core import urlresolvers from django.utils import translation from django.contrib.auth import views as auth_views from localeurl import utils def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs') or {} locale = utils.supported_language(reverse_kwargs.pop( 'locale', translation.get_language())) url = django_reverse(*args, **kwargs) _, path = utils.strip_script_prefix(url) return utils.locale_url(path, locale) django_reverse = None def patch_reverse(): """ Monkey-patches the urlresolvers.reverse function. Will not patch twice. """ global django_reverse if urlresolvers.reverse is not reverse: django_reverse = urlresolvers.reverse urlresolvers.reverse = reverse def redirect_to_login(next, login_url, *args, **kwargs): if not login_url: login_url = settings.LOGIN_URL login_url = utils.locale_url(login_url, translation.get_language()) return django_redirect_to_login(next, login_url, *args, **kwargs) django_redirect_to_login = None def patch_redirect_to_login(): """ Monkey-patches the redirect_to_login function. Will not patch twice. """ global django_redirect_to_login if auth_views.redirect_to_login is not redirect_to_login: django_redirect_to_login = auth_views.redirect_to_login auth_views.redirect_to_login = redirect_to_login if settings.USE_I18N: patch_reverse() patch_redirect_to_login()
from django.conf import settings from django.core import urlresolvers from django.utils import translation + from django.contrib.auth import views as auth_views from localeurl import utils + def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs') or {} locale = utils.supported_language(reverse_kwargs.pop( 'locale', translation.get_language())) url = django_reverse(*args, **kwargs) _, path = utils.strip_script_prefix(url) return utils.locale_url(path, locale) django_reverse = None def patch_reverse(): """ Monkey-patches the urlresolvers.reverse function. Will not patch twice. """ global django_reverse if urlresolvers.reverse is not reverse: django_reverse = urlresolvers.reverse urlresolvers.reverse = reverse + + def redirect_to_login(next, login_url, *args, **kwargs): + if not login_url: + login_url = settings.LOGIN_URL + login_url = utils.locale_url(login_url, translation.get_language()) + return django_redirect_to_login(next, login_url, *args, **kwargs) + + django_redirect_to_login = None + + def patch_redirect_to_login(): + """ + Monkey-patches the redirect_to_login function. Will not patch twice. + """ + global django_redirect_to_login + if auth_views.redirect_to_login is not redirect_to_login: + django_redirect_to_login = auth_views.redirect_to_login + auth_views.redirect_to_login = redirect_to_login + + if settings.USE_I18N: patch_reverse() + patch_redirect_to_login()
68b5484cfb0910b3ed68e99520decc6aca08bb2d
flask_webapi/__init__.py
flask_webapi/__init__.py
from marshmallow import pre_load, pre_dump, post_load, post_dump, Schema, ValidationError, validates_schema from marshmallow.utils import missing from .api import WebAPI from .decorators import authenticator, permissions, content_negotiator, renderer, serializer, route from .views import ViewBase
from marshmallow import pre_load, pre_dump, post_load, post_dump, Schema, ValidationError, validates_schema from marshmallow.utils import missing from .api import WebAPI from .errors import APIError from .decorators import authenticator, permissions, content_negotiator, renderer, serializer, route from .views import ViewBase
Add import for APIError to make it easy to import by users
Add import for APIError to make it easy to import by users
Python
mit
viniciuschiele/flask-webapi
from marshmallow import pre_load, pre_dump, post_load, post_dump, Schema, ValidationError, validates_schema from marshmallow.utils import missing from .api import WebAPI + from .errors import APIError from .decorators import authenticator, permissions, content_negotiator, renderer, serializer, route from .views import ViewBase
Add import for APIError to make it easy to import by users
## Code Before: from marshmallow import pre_load, pre_dump, post_load, post_dump, Schema, ValidationError, validates_schema from marshmallow.utils import missing from .api import WebAPI from .decorators import authenticator, permissions, content_negotiator, renderer, serializer, route from .views import ViewBase ## Instruction: Add import for APIError to make it easy to import by users ## Code After: from marshmallow import pre_load, pre_dump, post_load, post_dump, Schema, ValidationError, validates_schema from marshmallow.utils import missing from .api import WebAPI from .errors import APIError from .decorators import authenticator, permissions, content_negotiator, renderer, serializer, route from .views import ViewBase
from marshmallow import pre_load, pre_dump, post_load, post_dump, Schema, ValidationError, validates_schema from marshmallow.utils import missing from .api import WebAPI + from .errors import APIError from .decorators import authenticator, permissions, content_negotiator, renderer, serializer, route from .views import ViewBase
8d0b9da511d55191609ffbd88a8b11afd6ff0367
remedy/radremedy.py
remedy/radremedy.py
from flask import Flask, url_for, request, abort from flask.ext.script import Manager from flask.ext.migrate import Migrate, MigrateCommand from rad.models import db, Resource def create_app(config, models=()): from remedyblueprint import remedy, url_for_other_page app = Flask(__name__) app.config.from_object(config) app.register_blueprint(remedy) # searching configurations app.jinja_env.trim_blocks = True # Register the paging helper method with Jinja2 app.jinja_env.globals['url_for_other_page'] = url_for_other_page db.init_app(app) Migrate(app, db, directory=app.config['MIGRATIONS_DIR']) manager = Manager(app) manager.add_command('db', MigrateCommand) # turning API off for now # from api_manager import init_api_manager # api_manager = init_api_manager(app, db) # map(lambda m: api_manager.create_api(m), models) return app, manager if __name__ == '__main__': app, manager = create_app('config.BaseConfig', (Resource, )) with app.app_context(): manager.run()
from flask import Flask, url_for, request, abort from flask.ext.script import Manager from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.login import current_user from rad.models import db, Resource def create_app(config, models=()): app = Flask(__name__) app.config.from_object(config) from remedyblueprint import remedy, url_for_other_page app.register_blueprint(remedy) from auth.user_auth import auth, login_manager app.register_blueprint(auth) login_manager.init_app(app) # searching configurations app.jinja_env.trim_blocks = True # Register the paging helper method with Jinja2 app.jinja_env.globals['url_for_other_page'] = url_for_other_page app.jinja_env.globals['logged_in'] = lambda : not current_user.is_anonymous() db.init_app(app) Migrate(app, db, directory=app.config['MIGRATIONS_DIR']) manager = Manager(app) manager.add_command('db', MigrateCommand) # turning API off for now # from api_manager import init_api_manager # api_manager = init_api_manager(app, db) # map(lambda m: api_manager.create_api(m), models) return app, manager if __name__ == '__main__': application, manager = create_app('config.BaseConfig', (Resource, )) with application.app_context(): manager.run()
Move around imports and not shadow app
Move around imports and not shadow app
Python
mpl-2.0
radioprotector/radremedy,radioprotector/radremedy,radioprotector/radremedy,AllieDeford/radremedy,AllieDeford/radremedy,radremedy/radremedy,radremedy/radremedy,radremedy/radremedy,AllieDeford/radremedy,radioprotector/radremedy,radremedy/radremedy
from flask import Flask, url_for, request, abort from flask.ext.script import Manager from flask.ext.migrate import Migrate, MigrateCommand + from flask.ext.login import current_user from rad.models import db, Resource def create_app(config, models=()): - from remedyblueprint import remedy, url_for_other_page - app = Flask(__name__) app.config.from_object(config) + from remedyblueprint import remedy, url_for_other_page app.register_blueprint(remedy) + + from auth.user_auth import auth, login_manager + app.register_blueprint(auth) + login_manager.init_app(app) # searching configurations app.jinja_env.trim_blocks = True # Register the paging helper method with Jinja2 app.jinja_env.globals['url_for_other_page'] = url_for_other_page + app.jinja_env.globals['logged_in'] = lambda : not current_user.is_anonymous() db.init_app(app) Migrate(app, db, directory=app.config['MIGRATIONS_DIR']) manager = Manager(app) manager.add_command('db', MigrateCommand) # turning API off for now # from api_manager import init_api_manager # api_manager = init_api_manager(app, db) # map(lambda m: api_manager.create_api(m), models) return app, manager if __name__ == '__main__': - app, manager = create_app('config.BaseConfig', (Resource, )) + application, manager = create_app('config.BaseConfig', (Resource, )) - with app.app_context(): + with application.app_context(): manager.run()
Move around imports and not shadow app
## Code Before: from flask import Flask, url_for, request, abort from flask.ext.script import Manager from flask.ext.migrate import Migrate, MigrateCommand from rad.models import db, Resource def create_app(config, models=()): from remedyblueprint import remedy, url_for_other_page app = Flask(__name__) app.config.from_object(config) app.register_blueprint(remedy) # searching configurations app.jinja_env.trim_blocks = True # Register the paging helper method with Jinja2 app.jinja_env.globals['url_for_other_page'] = url_for_other_page db.init_app(app) Migrate(app, db, directory=app.config['MIGRATIONS_DIR']) manager = Manager(app) manager.add_command('db', MigrateCommand) # turning API off for now # from api_manager import init_api_manager # api_manager = init_api_manager(app, db) # map(lambda m: api_manager.create_api(m), models) return app, manager if __name__ == '__main__': app, manager = create_app('config.BaseConfig', (Resource, )) with app.app_context(): manager.run() ## Instruction: Move around imports and not shadow app ## Code After: from flask import Flask, url_for, request, abort from flask.ext.script import Manager from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.login import current_user from rad.models import db, Resource def create_app(config, models=()): app = Flask(__name__) app.config.from_object(config) from remedyblueprint import remedy, url_for_other_page app.register_blueprint(remedy) from auth.user_auth import auth, login_manager app.register_blueprint(auth) login_manager.init_app(app) # searching configurations app.jinja_env.trim_blocks = True # Register the paging helper method with Jinja2 app.jinja_env.globals['url_for_other_page'] = url_for_other_page app.jinja_env.globals['logged_in'] = lambda : not current_user.is_anonymous() db.init_app(app) Migrate(app, db, directory=app.config['MIGRATIONS_DIR']) manager = Manager(app) manager.add_command('db', MigrateCommand) # turning API off for now # from api_manager import init_api_manager # api_manager = init_api_manager(app, db) # map(lambda m: api_manager.create_api(m), models) return app, manager if __name__ == '__main__': application, manager = create_app('config.BaseConfig', (Resource, )) with application.app_context(): manager.run()
from flask import Flask, url_for, request, abort from flask.ext.script import Manager from flask.ext.migrate import Migrate, MigrateCommand + from flask.ext.login import current_user from rad.models import db, Resource def create_app(config, models=()): - from remedyblueprint import remedy, url_for_other_page - app = Flask(__name__) app.config.from_object(config) + from remedyblueprint import remedy, url_for_other_page app.register_blueprint(remedy) + + from auth.user_auth import auth, login_manager + app.register_blueprint(auth) + login_manager.init_app(app) # searching configurations app.jinja_env.trim_blocks = True # Register the paging helper method with Jinja2 app.jinja_env.globals['url_for_other_page'] = url_for_other_page + app.jinja_env.globals['logged_in'] = lambda : not current_user.is_anonymous() db.init_app(app) Migrate(app, db, directory=app.config['MIGRATIONS_DIR']) manager = Manager(app) manager.add_command('db', MigrateCommand) # turning API off for now # from api_manager import init_api_manager # api_manager = init_api_manager(app, db) # map(lambda m: api_manager.create_api(m), models) return app, manager if __name__ == '__main__': - app, manager = create_app('config.BaseConfig', (Resource, )) + application, manager = create_app('config.BaseConfig', (Resource, )) ? ++++++++ - with app.app_context(): + with application.app_context(): ? ++++++++ manager.run()
0fd7b771823b97cb5fb7789c981d4ab3befcd28e
bluebottle/homepage/models.py
bluebottle/homepage/models.py
from bluebottle.quotes.models import Quote from bluebottle.slides.models import Slide from bluebottle.statistics.models import Statistic from bluebottle.projects.models import Project class HomePage(object): """ Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object """ def get(self, language): self.id = language self.quotes = Quote.objects.published().filter(language=language) self.slides = Slide.objects.published().filter(language=language) self.statistics = Statistic.objects.filter(active=True, language=language).all() projects = Project.objects.filter(is_campaign=True, status__viewable=True) if language == 'en': projects = projects.filter(language__code=language) projects = projects.order_by('?') if len(projects) > 4: self.projects = projects[0:4] elif len(projects) > 0: self.projects = projects[0:len(projects)] else: self.projects = None return self
from bluebottle.quotes.models import Quote from bluebottle.slides.models import Slide from bluebottle.statistics.models import Statistic from bluebottle.projects.models import Project class HomePage(object): """ Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object """ def get(self, language): self.id = language self.quotes = Quote.objects.published().filter(language=language) self.slides = Slide.objects.published().filter(language=language) self.statistics = Statistic.objects.filter(active=True, language=language).all() projects = Project.objects.filter(is_campaign=True, status__viewable=True) if language == 'en': projects = projects.filter(language__code=language) projects = projects.order_by('?') if len(projects) > 4: self.projects = projects[0:4] elif len(projects) > 0: self.projects = projects[0:len(projects)] else: self.projects = Project.objects.none() return self
Send an empty list instead of None if no projects
Send an empty list instead of None if no projects selected for homepage.
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
from bluebottle.quotes.models import Quote from bluebottle.slides.models import Slide from bluebottle.statistics.models import Statistic from bluebottle.projects.models import Project class HomePage(object): """ Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object """ def get(self, language): self.id = language self.quotes = Quote.objects.published().filter(language=language) self.slides = Slide.objects.published().filter(language=language) self.statistics = Statistic.objects.filter(active=True, language=language).all() projects = Project.objects.filter(is_campaign=True, status__viewable=True) if language == 'en': projects = projects.filter(language__code=language) projects = projects.order_by('?') if len(projects) > 4: self.projects = projects[0:4] elif len(projects) > 0: self.projects = projects[0:len(projects)] else: - self.projects = None + self.projects = Project.objects.none() return self
Send an empty list instead of None if no projects
## Code Before: from bluebottle.quotes.models import Quote from bluebottle.slides.models import Slide from bluebottle.statistics.models import Statistic from bluebottle.projects.models import Project class HomePage(object): """ Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object """ def get(self, language): self.id = language self.quotes = Quote.objects.published().filter(language=language) self.slides = Slide.objects.published().filter(language=language) self.statistics = Statistic.objects.filter(active=True, language=language).all() projects = Project.objects.filter(is_campaign=True, status__viewable=True) if language == 'en': projects = projects.filter(language__code=language) projects = projects.order_by('?') if len(projects) > 4: self.projects = projects[0:4] elif len(projects) > 0: self.projects = projects[0:len(projects)] else: self.projects = None return self ## Instruction: Send an empty list instead of None if no projects ## Code After: from bluebottle.quotes.models import Quote from bluebottle.slides.models import Slide from bluebottle.statistics.models import Statistic from bluebottle.projects.models import Project class HomePage(object): """ Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object """ def get(self, language): self.id = language self.quotes = Quote.objects.published().filter(language=language) self.slides = Slide.objects.published().filter(language=language) self.statistics = Statistic.objects.filter(active=True, language=language).all() projects = Project.objects.filter(is_campaign=True, status__viewable=True) if language == 'en': projects = projects.filter(language__code=language) projects = projects.order_by('?') if len(projects) > 4: self.projects = projects[0:4] elif len(projects) > 0: self.projects = projects[0:len(projects)] else: self.projects = Project.objects.none() return self
from bluebottle.quotes.models import Quote from bluebottle.slides.models import Slide from bluebottle.statistics.models import Statistic from bluebottle.projects.models import Project class HomePage(object): """ Instead of serving all the objects separately we combine Slide, Quote and Stats into a dummy object """ def get(self, language): self.id = language self.quotes = Quote.objects.published().filter(language=language) self.slides = Slide.objects.published().filter(language=language) self.statistics = Statistic.objects.filter(active=True, language=language).all() projects = Project.objects.filter(is_campaign=True, status__viewable=True) if language == 'en': projects = projects.filter(language__code=language) projects = projects.order_by('?') if len(projects) > 4: self.projects = projects[0:4] elif len(projects) > 0: self.projects = projects[0:len(projects)] else: - self.projects = None ? ^ + self.projects = Project.objects.none() ? ^^^^^^^^^^^^^^^^^ ++ return self
749219a1282a347133ba73127ed7cc8d8009897d
anchore_engine/clients/syft_wrapper.py
anchore_engine/clients/syft_wrapper.py
import json import os import shlex from anchore_engine.utils import run_check def run_syft(image): proc_env = os.environ.copy() syft_env = { "SYFT_CHECK_FOR_APP_UPDATE": "0", "SYFT_LOG_STRUCTURED": "1", } proc_env.update(syft_env) cmd = "syft -vv -o json oci-dir:{image}".format(image=image) stdout, _ = run_check(shlex.split(cmd), env=proc_env) return json.loads(stdout)
import json import os import shlex from anchore_engine.utils import run_check def run_syft(image): proc_env = os.environ.copy() syft_env = { "SYFT_CHECK_FOR_APP_UPDATE": "0", "SYFT_LOG_STRUCTURED": "1", } proc_env.update(syft_env) cmd = "syft -vv -o json oci-dir:{image}".format(image=image) stdout, _ = run_check(shlex.split(cmd), env=proc_env, log_level="spew") return json.loads(stdout)
Make the syft invocation only log the full output at spew level instead of debug.
Make the syft invocation only log the full output at spew level instead of debug. The syft json output for very large images can be 100s of MB and cause the analyzer to be unusable due to the logging itself. This changes that call to only dump output at "spew" level logging. Signed-off-by: Zach Hill <9de8c4480303b5335cd2a33eefe814615ba3612a@anchore.com>
Python
apache-2.0
anchore/anchore-engine,anchore/anchore-engine,anchore/anchore-engine
import json import os import shlex from anchore_engine.utils import run_check def run_syft(image): proc_env = os.environ.copy() syft_env = { "SYFT_CHECK_FOR_APP_UPDATE": "0", "SYFT_LOG_STRUCTURED": "1", } proc_env.update(syft_env) cmd = "syft -vv -o json oci-dir:{image}".format(image=image) - stdout, _ = run_check(shlex.split(cmd), env=proc_env) + stdout, _ = run_check(shlex.split(cmd), env=proc_env, log_level="spew") return json.loads(stdout)
Make the syft invocation only log the full output at spew level instead of debug.
## Code Before: import json import os import shlex from anchore_engine.utils import run_check def run_syft(image): proc_env = os.environ.copy() syft_env = { "SYFT_CHECK_FOR_APP_UPDATE": "0", "SYFT_LOG_STRUCTURED": "1", } proc_env.update(syft_env) cmd = "syft -vv -o json oci-dir:{image}".format(image=image) stdout, _ = run_check(shlex.split(cmd), env=proc_env) return json.loads(stdout) ## Instruction: Make the syft invocation only log the full output at spew level instead of debug. ## Code After: import json import os import shlex from anchore_engine.utils import run_check def run_syft(image): proc_env = os.environ.copy() syft_env = { "SYFT_CHECK_FOR_APP_UPDATE": "0", "SYFT_LOG_STRUCTURED": "1", } proc_env.update(syft_env) cmd = "syft -vv -o json oci-dir:{image}".format(image=image) stdout, _ = run_check(shlex.split(cmd), env=proc_env, log_level="spew") return json.loads(stdout)
import json import os import shlex from anchore_engine.utils import run_check def run_syft(image): proc_env = os.environ.copy() syft_env = { "SYFT_CHECK_FOR_APP_UPDATE": "0", "SYFT_LOG_STRUCTURED": "1", } proc_env.update(syft_env) cmd = "syft -vv -o json oci-dir:{image}".format(image=image) - stdout, _ = run_check(shlex.split(cmd), env=proc_env) + stdout, _ = run_check(shlex.split(cmd), env=proc_env, log_level="spew") ? ++++++++++++++++++ return json.loads(stdout)
c73d24259a6aa198d749fba097999ba2c18bd6da
website/addons/figshare/settings/defaults.py
website/addons/figshare/settings/defaults.py
API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
CLIENT_ID = None CLIENT_SECRET = None API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
Add figshare CLIENT_ID and CLIENT_SECRET back into default settings.
Add figshare CLIENT_ID and CLIENT_SECRET back into default settings. [skip ci]
Python
apache-2.0
mattclark/osf.io,brandonPurvis/osf.io,TomBaxter/osf.io,jnayak1/osf.io,SSJohns/osf.io,revanthkolli/osf.io,kch8qx/osf.io,amyshi188/osf.io,GaryKriebel/osf.io,fabianvf/osf.io,revanthkolli/osf.io,jinluyuan/osf.io,cldershem/osf.io,KAsante95/osf.io,lamdnhan/osf.io,caseyrygt/osf.io,leb2dg/osf.io,HarryRybacki/osf.io,caneruguz/osf.io,haoyuchen1992/osf.io,rdhyee/osf.io,zachjanicki/osf.io,emetsger/osf.io,ckc6cz/osf.io,kwierman/osf.io,GageGaskins/osf.io,KAsante95/osf.io,DanielSBrown/osf.io,adlius/osf.io,hmoco/osf.io,erinspace/osf.io,bdyetton/prettychart,ticklemepierce/osf.io,baylee-d/osf.io,mluke93/osf.io,ckc6cz/osf.io,cslzchen/osf.io,TomHeatwole/osf.io,CenterForOpenScience/osf.io,alexschiller/osf.io,GageGaskins/osf.io,HalcyonChimera/osf.io,RomanZWang/osf.io,crcresearch/osf.io,haoyuchen1992/osf.io,lamdnhan/osf.io,SSJohns/osf.io,reinaH/osf.io,himanshuo/osf.io,petermalcolm/osf.io,ZobairAlijan/osf.io,dplorimer/osf,Ghalko/osf.io,mluke93/osf.io,GaryKriebel/osf.io,asanfilippo7/osf.io,pattisdr/osf.io,leb2dg/osf.io,acshi/osf.io,chrisseto/osf.io,alexschiller/osf.io,mluo613/osf.io,mluo613/osf.io,arpitar/osf.io,amyshi188/osf.io,caseyrygt/osf.io,lamdnhan/osf.io,Ghalko/osf.io,barbour-em/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,Nesiehr/osf.io,rdhyee/osf.io,petermalcolm/osf.io,cosenal/osf.io,crcresearch/osf.io,felliott/osf.io,zkraime/osf.io,ticklemepierce/osf.io,barbour-em/osf.io,zkraime/osf.io,mluke93/osf.io,emetsger/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,Nesiehr/osf.io,reinaH/osf.io,aaxelb/osf.io,danielneis/osf.io,mluke93/osf.io,bdyetton/prettychart,emetsger/osf.io,fabianvf/osf.io,amyshi188/osf.io,dplorimer/osf,acshi/osf.io,KAsante95/osf.io,bdyetton/prettychart,brandonPurvis/osf.io,danielneis/osf.io,asanfilippo7/osf.io,jolene-esposito/osf.io,felliott/osf.io,baylee-d/osf.io,billyhunt/osf.io,Nesiehr/osf.io,mluo613/osf.io,sloria/osf.io,RomanZWang/osf.io,icereval/osf.io,doublebits/osf.io,SSJohns/osf.io,kwierman/osf.io,cslzchen/osf.io,TomHeatwole/osf.io,chrisseto/osf.io,chrisseto/osf.io,himanshuo/osf.io,arpitar/osf.io,jnayak1/osf.io,barbour-em/osf.io,monikagrabowska/osf.io,jinluyuan/osf.io,Johnetordoff/osf.io,jeffreyliu3230/osf.io,brianjgeiger/osf.io,zachjanicki/osf.io,MerlinZhang/osf.io,ZobairAlijan/osf.io,monikagrabowska/osf.io,alexschiller/osf.io,petermalcolm/osf.io,acshi/osf.io,dplorimer/osf,erinspace/osf.io,jolene-esposito/osf.io,billyhunt/osf.io,bdyetton/prettychart,zkraime/osf.io,saradbowman/osf.io,abought/osf.io,abought/osf.io,zamattiac/osf.io,GageGaskins/osf.io,kushG/osf.io,sbt9uc/osf.io,reinaH/osf.io,ckc6cz/osf.io,adlius/osf.io,icereval/osf.io,lyndsysimon/osf.io,caseyrygt/osf.io,cosenal/osf.io,billyhunt/osf.io,sloria/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,jeffreyliu3230/osf.io,kch8qx/osf.io,pattisdr/osf.io,wearpants/osf.io,brandonPurvis/osf.io,CenterForOpenScience/osf.io,HalcyonChimera/osf.io,SSJohns/osf.io,caneruguz/osf.io,wearpants/osf.io,MerlinZhang/osf.io,himanshuo/osf.io,laurenrevere/osf.io,monikagrabowska/osf.io,doublebits/osf.io,doublebits/osf.io,samanehsan/osf.io,mluo613/osf.io,jmcarp/osf.io,zamattiac/osf.io,hmoco/osf.io,samchrisinger/osf.io,chennan47/osf.io,sbt9uc/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,lamdnhan/osf.io,jolene-esposito/osf.io,hmoco/osf.io,revanthkolli/osf.io,himanshuo/osf.io,ticklemepierce/osf.io,HalcyonChimera/osf.io,TomHeatwole/osf.io,zachjanicki/osf.io,brandonPurvis/osf.io,lyndsysimon/osf.io,arpitar/osf.io,samanehsan/osf.io,abought/osf.io,jinluyuan/osf.io,binoculars/osf.io,reinaH/osf.io,DanielSBrown/osf.io,jnayak1/osf.io,jmcarp/osf.io,cldershem/osf.io,ZobairAlijan/osf.io,kushG/osf.io,caneruguz/osf.io,laurenrevere/osf.io,cldershem/osf.io,mattclark/osf.io,HarryRybacki/osf.io,GageGaskins/osf.io,HalcyonChimera/osf.io,samanehsan/osf.io,rdhyee/osf.io,cldershem/osf.io,mfraezz/osf.io,aaxelb/osf.io,mfraezz/osf.io,saradbowman/osf.io,emetsger/osf.io,acshi/osf.io,caseyrygt/osf.io,kushG/osf.io,kch8qx/osf.io,asanfilippo7/osf.io,HarryRybacki/osf.io,Nesiehr/osf.io,leb2dg/osf.io,billyhunt/osf.io,baylee-d/osf.io,Ghalko/osf.io,RomanZWang/osf.io,sbt9uc/osf.io,leb2dg/osf.io,mattclark/osf.io,chennan47/osf.io,jmcarp/osf.io,cwisecarver/osf.io,petermalcolm/osf.io,jnayak1/osf.io,zamattiac/osf.io,amyshi188/osf.io,alexschiller/osf.io,Johnetordoff/osf.io,sloria/osf.io,lyndsysimon/osf.io,hmoco/osf.io,DanielSBrown/osf.io,aaxelb/osf.io,haoyuchen1992/osf.io,KAsante95/osf.io,sbt9uc/osf.io,dplorimer/osf,lyndsysimon/osf.io,arpitar/osf.io,mfraezz/osf.io,kch8qx/osf.io,samchrisinger/osf.io,brandonPurvis/osf.io,binoculars/osf.io,ckc6cz/osf.io,njantrania/osf.io,fabianvf/osf.io,pattisdr/osf.io,caseyrollins/osf.io,kushG/osf.io,zachjanicki/osf.io,TomBaxter/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,cwisecarver/osf.io,chrisseto/osf.io,mfraezz/osf.io,jinluyuan/osf.io,jeffreyliu3230/osf.io,TomBaxter/osf.io,samchrisinger/osf.io,laurenrevere/osf.io,doublebits/osf.io,crcresearch/osf.io,rdhyee/osf.io,GaryKriebel/osf.io,binoculars/osf.io,felliott/osf.io,GaryKriebel/osf.io,HarryRybacki/osf.io,caseyrollins/osf.io,monikagrabowska/osf.io,samchrisinger/osf.io,jeffreyliu3230/osf.io,kwierman/osf.io,asanfilippo7/osf.io,abought/osf.io,MerlinZhang/osf.io,samanehsan/osf.io,wearpants/osf.io,acshi/osf.io,fabianvf/osf.io,alexschiller/osf.io,cslzchen/osf.io,MerlinZhang/osf.io,kwierman/osf.io,wearpants/osf.io,adlius/osf.io,revanthkolli/osf.io,RomanZWang/osf.io,RomanZWang/osf.io,mluo613/osf.io,caneruguz/osf.io,felliott/osf.io,caseyrollins/osf.io,zamattiac/osf.io,zkraime/osf.io,kch8qx/osf.io,doublebits/osf.io,jmcarp/osf.io,Ghalko/osf.io,barbour-em/osf.io,Johnetordoff/osf.io,DanielSBrown/osf.io,cosenal/osf.io,cosenal/osf.io,TomHeatwole/osf.io,njantrania/osf.io,adlius/osf.io,GageGaskins/osf.io,njantrania/osf.io,chennan47/osf.io,haoyuchen1992/osf.io,danielneis/osf.io,icereval/osf.io,billyhunt/osf.io,ticklemepierce/osf.io,danielneis/osf.io,KAsante95/osf.io,njantrania/osf.io,jolene-esposito/osf.io,ZobairAlijan/osf.io
+ CLIENT_ID = None + CLIENT_SECRET = None + API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
Add figshare CLIENT_ID and CLIENT_SECRET back into default settings.
## Code Before: API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000 ## Instruction: Add figshare CLIENT_ID and CLIENT_SECRET back into default settings. ## Code After: CLIENT_ID = None CLIENT_SECRET = None API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
+ CLIENT_ID = None + CLIENT_SECRET = None + API_URL = 'http://api.figshare.com/v1/' API_OAUTH_URL = API_URL + 'my_data/' MAX_RENDER_SIZE = 1000
3af22fd5583ee110f731b9e1ebecba67ebee2bd4
sendwithus/exceptions.py
sendwithus/exceptions.py
class SendwithusError(Exception): """Base class for Sendwithus API errors""" class AuthenticationError(SendwithusError): """API Authentication Failed""" class APIError(SendwithusError): """4xx - Invalid Request (Client error)""" class ServerError(SendwithusError): """5xx - Failed Request (Server error)"""
class SendwithusError(Exception): """Base class for Sendwithus API errors""" def __init__(self, content=None): self.content = content class AuthenticationError(SendwithusError): """API Authentication Failed""" class APIError(SendwithusError): """4xx - Invalid Request (Client error)""" class ServerError(SendwithusError): """5xx - Failed Request (Server error)"""
Add a constructor to SendwithusError that stores content
Add a constructor to SendwithusError that stores content
Python
apache-2.0
sendwithus/sendwithus_python
class SendwithusError(Exception): """Base class for Sendwithus API errors""" + + def __init__(self, content=None): + self.content = content class AuthenticationError(SendwithusError): """API Authentication Failed""" class APIError(SendwithusError): """4xx - Invalid Request (Client error)""" class ServerError(SendwithusError): """5xx - Failed Request (Server error)"""
Add a constructor to SendwithusError that stores content
## Code Before: class SendwithusError(Exception): """Base class for Sendwithus API errors""" class AuthenticationError(SendwithusError): """API Authentication Failed""" class APIError(SendwithusError): """4xx - Invalid Request (Client error)""" class ServerError(SendwithusError): """5xx - Failed Request (Server error)""" ## Instruction: Add a constructor to SendwithusError that stores content ## Code After: class SendwithusError(Exception): """Base class for Sendwithus API errors""" def __init__(self, content=None): self.content = content class AuthenticationError(SendwithusError): """API Authentication Failed""" class APIError(SendwithusError): """4xx - Invalid Request (Client error)""" class ServerError(SendwithusError): """5xx - Failed Request (Server error)"""
class SendwithusError(Exception): """Base class for Sendwithus API errors""" + + def __init__(self, content=None): + self.content = content class AuthenticationError(SendwithusError): """API Authentication Failed""" class APIError(SendwithusError): """4xx - Invalid Request (Client error)""" class ServerError(SendwithusError): """5xx - Failed Request (Server error)"""
6cc1e7ca79b8730cfd5e0db71dd19aae9848e3d2
mownfish/db/api.py
mownfish/db/api.py
from tornado.options import define, options import tornadoasyncmemcache define("db_addr_list", type=list, default=['192.168.0.176:19803']) class MemcachedClient(object): @staticmethod def instance(): if not hasattr(MemcachedClient, "_instance"): MemcachedClient._instance = \ tornadoasyncmemcache.ClientPool(options.db_addr_list, maxclients=100) return MemcachedClient._instance def get(key, callback): MemcachedClient.instance().get(key, callback=callback)
from tornado.options import define, options import tornadoasyncmemcache define("db_addr_list", type=list, default=['192.168.0.176:19803']) class MemcachedClient(object): def __new__(cls): if not hasattr(cls, '_instance'): cls._instance = \ tornadoasyncmemcache.ClientPool(options.db_addr_list, maxclients=100) return cls._instance def get_memcached(key, callback): MemcachedClient.instance().get(key, callback=callback)
Modify db client to __new__
Modify db client to __new__ change db singlton from instance() staticmethod to __new__()
Python
apache-2.0
Ethan-Zhang/mownfish
from tornado.options import define, options import tornadoasyncmemcache define("db_addr_list", type=list, default=['192.168.0.176:19803']) class MemcachedClient(object): + def __new__(cls): - @staticmethod - def instance(): - if not hasattr(MemcachedClient, "_instance"): + if not hasattr(cls, '_instance'): - MemcachedClient._instance = \ + cls._instance = \ - tornadoasyncmemcache.ClientPool(options.db_addr_list, + tornadoasyncmemcache.ClientPool(options.db_addr_list, maxclients=100) - return MemcachedClient._instance + return cls._instance - - def get(key, callback): + def get_memcached(key, callback): MemcachedClient.instance().get(key, callback=callback)
Modify db client to __new__
## Code Before: from tornado.options import define, options import tornadoasyncmemcache define("db_addr_list", type=list, default=['192.168.0.176:19803']) class MemcachedClient(object): @staticmethod def instance(): if not hasattr(MemcachedClient, "_instance"): MemcachedClient._instance = \ tornadoasyncmemcache.ClientPool(options.db_addr_list, maxclients=100) return MemcachedClient._instance def get(key, callback): MemcachedClient.instance().get(key, callback=callback) ## Instruction: Modify db client to __new__ ## Code After: from tornado.options import define, options import tornadoasyncmemcache define("db_addr_list", type=list, default=['192.168.0.176:19803']) class MemcachedClient(object): def __new__(cls): if not hasattr(cls, '_instance'): cls._instance = \ tornadoasyncmemcache.ClientPool(options.db_addr_list, maxclients=100) return cls._instance def get_memcached(key, callback): MemcachedClient.instance().get(key, callback=callback)
from tornado.options import define, options import tornadoasyncmemcache define("db_addr_list", type=list, default=['192.168.0.176:19803']) class MemcachedClient(object): + def __new__(cls): - @staticmethod - def instance(): - if not hasattr(MemcachedClient, "_instance"): ? --- ------ ^^^^ ^ ^ + if not hasattr(cls, '_instance'): ? ^ ^ ^ - MemcachedClient._instance = \ ? --- ------ ^^^^ + cls._instance = \ ? ^ - tornadoasyncmemcache.ClientPool(options.db_addr_list, ? - + tornadoasyncmemcache.ClientPool(options.db_addr_list, maxclients=100) - return MemcachedClient._instance ? --- ------ ^^^^ + return cls._instance ? ^ - - def get(key, callback): + def get_memcached(key, callback): ? ++++++++++ MemcachedClient.instance().get(key, callback=callback)
8a9f707960c3b39488c9bbee6ce7f22c6fbfc853
web/config/local_settings.py
web/config/local_settings.py
import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now())
import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): MEMCACHE_HOSTS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now())
Fix memcache hosts setting from env
Fix memcache hosts setting from env Before this fix if one had set OS env vars for both CLUSTER_SERVERS and MEMCACHE_HOSTS the value of later would override the former and the graphite web application fails to show any metrics.
Python
apache-2.0
Banno/graphite-setup,Banno/graphite-setup,Banno/graphite-setup
import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): - CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') + MEMCACHE_HOSTS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now())
Fix memcache hosts setting from env
## Code Before: import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now()) ## Instruction: Fix memcache hosts setting from env ## Code After: import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): MEMCACHE_HOSTS = os.getenv("MEMCACHE_HOSTS").split(',') if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now())
import os from datetime import datetime LOG_DIR = '/var/log/graphite' if os.getenv("CARBONLINK_HOSTS"): CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',') if os.getenv("CLUSTER_SERVERS"): CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',') if os.getenv("MEMCACHE_HOSTS"): - CLUSTER_SERVERS = os.getenv("MEMCACHE_HOSTS").split(',') ? ^^ --------- + MEMCACHE_HOSTS = os.getenv("MEMCACHE_HOSTS").split(',') ? +++ ^^^^^^^ if os.getenv("WHISPER_DIR"): WHISPER_DIR = os.getenv("WHISPER_DIR") SECRET_KEY = str(datetime.now())
4b8fbe2914aec5ddcf7f63c6b7ca2244ec022084
tests/test_crossbuild.py
tests/test_crossbuild.py
from mock import patch from unittest import TestCase from crossbuild import ( main, ) class CrossBuildTestCase(TestCase): def test_main_setup(self): with patch('crossbuild.setup_cross_building') as mock: main(['-d', '-v', 'setup', '--build-dir', './foo']) args, kwargs = mock.call_args self.assertEqual(('./foo', ), args) self.assertEqual({'dry_run': True, 'verbose': True}, kwargs) def test_main_win_client(self): with patch('crossbuild.build_win_client') as mock: main(['win-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) args, kwargs = mock.call_args self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) self.assertEqual({'dry_run': False, 'verbose': False}, kwargs)
from mock import patch from unittest import TestCase from crossbuild import ( main, ) class CrossBuildTestCase(TestCase): def test_main_setup(self): with patch('crossbuild.setup_cross_building') as mock: main(['-d', '-v', 'setup', '--build-dir', './foo']) args, kwargs = mock.call_args self.assertEqual(('./foo', ), args) self.assertEqual({'dry_run': True, 'verbose': True}, kwargs) def test_main_osx_clientt(self): with patch('crossbuild.build_osx_client') as mock: main(['osx-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) args, kwargs = mock.call_args self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) self.assertEqual({'dry_run': False, 'verbose': False}, kwargs) def test_main_win_client(self): with patch('crossbuild.build_win_client') as mock: main(['win-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) args, kwargs = mock.call_args self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) self.assertEqual({'dry_run': False, 'verbose': False}, kwargs) def test_main_win_agent(self): with patch('crossbuild.build_win_agent') as mock: main(['win-agent', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) args, kwargs = mock.call_args self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) self.assertEqual({'dry_run': False, 'verbose': False}, kwargs)
Add main osx-client command test.
Add main osx-client command test.
Python
agpl-3.0
mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju
from mock import patch from unittest import TestCase from crossbuild import ( main, ) class CrossBuildTestCase(TestCase): def test_main_setup(self): with patch('crossbuild.setup_cross_building') as mock: main(['-d', '-v', 'setup', '--build-dir', './foo']) args, kwargs = mock.call_args self.assertEqual(('./foo', ), args) self.assertEqual({'dry_run': True, 'verbose': True}, kwargs) + def test_main_osx_clientt(self): + with patch('crossbuild.build_osx_client') as mock: + main(['osx-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) + args, kwargs = mock.call_args + self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) + self.assertEqual({'dry_run': False, 'verbose': False}, kwargs) + def test_main_win_client(self): with patch('crossbuild.build_win_client') as mock: main(['win-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) args, kwargs = mock.call_args self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) self.assertEqual({'dry_run': False, 'verbose': False}, kwargs) + def test_main_win_agent(self): + with patch('crossbuild.build_win_agent') as mock: + main(['win-agent', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) + args, kwargs = mock.call_args + self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) + self.assertEqual({'dry_run': False, 'verbose': False}, kwargs) +
Add main osx-client command test.
## Code Before: from mock import patch from unittest import TestCase from crossbuild import ( main, ) class CrossBuildTestCase(TestCase): def test_main_setup(self): with patch('crossbuild.setup_cross_building') as mock: main(['-d', '-v', 'setup', '--build-dir', './foo']) args, kwargs = mock.call_args self.assertEqual(('./foo', ), args) self.assertEqual({'dry_run': True, 'verbose': True}, kwargs) def test_main_win_client(self): with patch('crossbuild.build_win_client') as mock: main(['win-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) args, kwargs = mock.call_args self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) self.assertEqual({'dry_run': False, 'verbose': False}, kwargs) ## Instruction: Add main osx-client command test. ## Code After: from mock import patch from unittest import TestCase from crossbuild import ( main, ) class CrossBuildTestCase(TestCase): def test_main_setup(self): with patch('crossbuild.setup_cross_building') as mock: main(['-d', '-v', 'setup', '--build-dir', './foo']) args, kwargs = mock.call_args self.assertEqual(('./foo', ), args) self.assertEqual({'dry_run': True, 'verbose': True}, kwargs) def test_main_osx_clientt(self): with patch('crossbuild.build_osx_client') as mock: main(['osx-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) args, kwargs = mock.call_args self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) self.assertEqual({'dry_run': False, 'verbose': False}, kwargs) def test_main_win_client(self): with patch('crossbuild.build_win_client') as mock: main(['win-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) args, kwargs = mock.call_args self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) self.assertEqual({'dry_run': False, 'verbose': False}, kwargs) def test_main_win_agent(self): with patch('crossbuild.build_win_agent') as mock: main(['win-agent', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) args, kwargs = mock.call_args self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) self.assertEqual({'dry_run': False, 'verbose': False}, kwargs)
from mock import patch from unittest import TestCase from crossbuild import ( main, ) class CrossBuildTestCase(TestCase): def test_main_setup(self): with patch('crossbuild.setup_cross_building') as mock: main(['-d', '-v', 'setup', '--build-dir', './foo']) args, kwargs = mock.call_args self.assertEqual(('./foo', ), args) self.assertEqual({'dry_run': True, 'verbose': True}, kwargs) + def test_main_osx_clientt(self): + with patch('crossbuild.build_osx_client') as mock: + main(['osx-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) + args, kwargs = mock.call_args + self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) + self.assertEqual({'dry_run': False, 'verbose': False}, kwargs) + def test_main_win_client(self): with patch('crossbuild.build_win_client') as mock: main(['win-client', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) args, kwargs = mock.call_args self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) self.assertEqual({'dry_run': False, 'verbose': False}, kwargs) + + def test_main_win_agent(self): + with patch('crossbuild.build_win_agent') as mock: + main(['win-agent', '--build-dir', './foo', 'bar.1.2.3.tar.gz']) + args, kwargs = mock.call_args + self.assertEqual(('bar.1.2.3.tar.gz', './foo'), args) + self.assertEqual({'dry_run': False, 'verbose': False}, kwargs)
aed18a3f9cbaf1eae1d7066b438437446513d912
sphinxcontrib/traceables/__init__.py
sphinxcontrib/traceables/__init__.py
import infrastructure import display import traceables import matrix import graph # ========================================================================== # Setup and register extension def setup(app): # Perform import within this function to avoid an import circle. from sphinxcontrib import traceables # Allow extension parts to set themselves up. traceables.infrastructure.setup(app) traceables.traceables.setup(app) traceables.matrix.setup(app) traceables.graph.setup(app) # Register business logic of extension parts. This is done explicitly # here to ensure correct ordering during processing. traceables.infrastructure.ProcessorManager.register_processor_classes([ traceables.traceables.RelationshipsProcessor, traceables.display.TraceableDisplayProcessor, traceables.traceables.XrefProcessor, traceables.matrix.ListProcessor, traceables.matrix.MatrixProcessor, traceables.graph.GraphProcessor, ]) return {"version": "0.0"}
import infrastructure import display import traceables import matrix import graph # ========================================================================== # Setup and register extension def setup(app): # Perform import within this function to avoid an import circle. from sphinxcontrib import traceables # Allow extension parts to set themselves up. traceables.infrastructure.setup(app) traceables.display.setup(app) traceables.traceables.setup(app) traceables.matrix.setup(app) traceables.graph.setup(app) # Register business logic of extension parts. This is done explicitly # here to ensure correct ordering during processing. traceables.infrastructure.ProcessorManager.register_processor_classes([ traceables.traceables.RelationshipsProcessor, traceables.display.TraceableDisplayProcessor, traceables.traceables.XrefProcessor, traceables.matrix.ListProcessor, traceables.matrix.MatrixProcessor, traceables.graph.GraphProcessor, ]) return {"version": "0.0"}
Fix missing call to display.setup()
Fix missing call to display.setup()
Python
apache-2.0
t4ngo/sphinxcontrib-traceables
import infrastructure import display import traceables import matrix import graph # ========================================================================== # Setup and register extension def setup(app): # Perform import within this function to avoid an import circle. from sphinxcontrib import traceables # Allow extension parts to set themselves up. traceables.infrastructure.setup(app) + traceables.display.setup(app) traceables.traceables.setup(app) traceables.matrix.setup(app) traceables.graph.setup(app) # Register business logic of extension parts. This is done explicitly # here to ensure correct ordering during processing. traceables.infrastructure.ProcessorManager.register_processor_classes([ traceables.traceables.RelationshipsProcessor, traceables.display.TraceableDisplayProcessor, traceables.traceables.XrefProcessor, traceables.matrix.ListProcessor, traceables.matrix.MatrixProcessor, traceables.graph.GraphProcessor, ]) return {"version": "0.0"}
Fix missing call to display.setup()
## Code Before: import infrastructure import display import traceables import matrix import graph # ========================================================================== # Setup and register extension def setup(app): # Perform import within this function to avoid an import circle. from sphinxcontrib import traceables # Allow extension parts to set themselves up. traceables.infrastructure.setup(app) traceables.traceables.setup(app) traceables.matrix.setup(app) traceables.graph.setup(app) # Register business logic of extension parts. This is done explicitly # here to ensure correct ordering during processing. traceables.infrastructure.ProcessorManager.register_processor_classes([ traceables.traceables.RelationshipsProcessor, traceables.display.TraceableDisplayProcessor, traceables.traceables.XrefProcessor, traceables.matrix.ListProcessor, traceables.matrix.MatrixProcessor, traceables.graph.GraphProcessor, ]) return {"version": "0.0"} ## Instruction: Fix missing call to display.setup() ## Code After: import infrastructure import display import traceables import matrix import graph # ========================================================================== # Setup and register extension def setup(app): # Perform import within this function to avoid an import circle. from sphinxcontrib import traceables # Allow extension parts to set themselves up. traceables.infrastructure.setup(app) traceables.display.setup(app) traceables.traceables.setup(app) traceables.matrix.setup(app) traceables.graph.setup(app) # Register business logic of extension parts. This is done explicitly # here to ensure correct ordering during processing. traceables.infrastructure.ProcessorManager.register_processor_classes([ traceables.traceables.RelationshipsProcessor, traceables.display.TraceableDisplayProcessor, traceables.traceables.XrefProcessor, traceables.matrix.ListProcessor, traceables.matrix.MatrixProcessor, traceables.graph.GraphProcessor, ]) return {"version": "0.0"}
import infrastructure import display import traceables import matrix import graph # ========================================================================== # Setup and register extension def setup(app): # Perform import within this function to avoid an import circle. from sphinxcontrib import traceables # Allow extension parts to set themselves up. traceables.infrastructure.setup(app) + traceables.display.setup(app) traceables.traceables.setup(app) traceables.matrix.setup(app) traceables.graph.setup(app) # Register business logic of extension parts. This is done explicitly # here to ensure correct ordering during processing. traceables.infrastructure.ProcessorManager.register_processor_classes([ traceables.traceables.RelationshipsProcessor, traceables.display.TraceableDisplayProcessor, traceables.traceables.XrefProcessor, traceables.matrix.ListProcessor, traceables.matrix.MatrixProcessor, traceables.graph.GraphProcessor, ]) return {"version": "0.0"}
c062ae638a4c864e978a4adfcd7d8d830b99abc2
opentreemap/treemap/lib/dates.py
opentreemap/treemap/lib/dates.py
from datetime import datetime from django.utils import timezone import calendar import pytz DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' DATE_FORMAT = '%Y-%m-%d' def parse_date_string_with_or_without_time(date_string): try: return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S') except ValueError: # If the time is not included, try again with date only return datetime.strptime(date_string.strip(), '%Y-%m-%d') def unix_timestamp(d=None): if d is None: d = timezone.now() return calendar.timegm(d.utctimetuple()) else: return calendar.timegm(d.timetuple()) def datesafe_eq(obj1, obj2): """ If two objects are dates, but don't both have the same timezone awareness status, compare them in a timezone-safe way. Otherwise, compare them with regular equality. """ if isinstance(obj1, datetime) and not timezone.is_aware(obj1): obj1 = timezone.make_aware(obj1, pytz.UTC) if isinstance(obj2, datetime) and not timezone.is_aware(obj2): obj2 = timezone.make_aware(obj2, pytz.UTC) return obj1 == obj2
from datetime import datetime from django.utils import timezone import calendar import pytz DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' DATE_FORMAT = '%Y-%m-%d' def parse_date_string_with_or_without_time(date_string): try: return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S') except ValueError: # If the time is not included, try again with date only return datetime.strptime(date_string.strip(), '%Y-%m-%d') def unix_timestamp(d=None): if d is None: d = timezone.now() return calendar.timegm(d.utctimetuple()) else: return calendar.timegm(d.timetuple()) def datesafe_eq(obj1, obj2): """ If two objects are dates, but don't both have the same timezone awareness status, compare them in a timezone-safe way. Otherwise, compare them with regular equality. """ if isinstance(obj1, datetime) and not timezone.is_aware(obj1): obj1 = timezone.make_aware(obj1, pytz.UTC) if isinstance(obj2, datetime) and not timezone.is_aware(obj2): obj2 = timezone.make_aware(obj2, pytz.UTC) return obj1 == obj2 def make_aware(value): if value is None or timezone.is_aware(value): return value else: return timezone.make_aware(value, timezone.utc)
Add function for nullsafe, tzsafe comparison
Add function for nullsafe, tzsafe comparison
Python
agpl-3.0
clever-crow-consulting/otm-core,recklessromeo/otm-core,maurizi/otm-core,recklessromeo/otm-core,maurizi/otm-core,RickMohr/otm-core,RickMohr/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,recklessromeo/otm-core,maurizi/otm-core,clever-crow-consulting/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,maurizi/otm-core
from datetime import datetime from django.utils import timezone import calendar import pytz DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' DATE_FORMAT = '%Y-%m-%d' def parse_date_string_with_or_without_time(date_string): try: return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S') except ValueError: # If the time is not included, try again with date only return datetime.strptime(date_string.strip(), '%Y-%m-%d') def unix_timestamp(d=None): if d is None: d = timezone.now() return calendar.timegm(d.utctimetuple()) else: return calendar.timegm(d.timetuple()) def datesafe_eq(obj1, obj2): """ If two objects are dates, but don't both have the same timezone awareness status, compare them in a timezone-safe way. Otherwise, compare them with regular equality. """ if isinstance(obj1, datetime) and not timezone.is_aware(obj1): obj1 = timezone.make_aware(obj1, pytz.UTC) if isinstance(obj2, datetime) and not timezone.is_aware(obj2): obj2 = timezone.make_aware(obj2, pytz.UTC) return obj1 == obj2 + + def make_aware(value): + if value is None or timezone.is_aware(value): + return value + else: + return timezone.make_aware(value, timezone.utc) +
Add function for nullsafe, tzsafe comparison
## Code Before: from datetime import datetime from django.utils import timezone import calendar import pytz DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' DATE_FORMAT = '%Y-%m-%d' def parse_date_string_with_or_without_time(date_string): try: return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S') except ValueError: # If the time is not included, try again with date only return datetime.strptime(date_string.strip(), '%Y-%m-%d') def unix_timestamp(d=None): if d is None: d = timezone.now() return calendar.timegm(d.utctimetuple()) else: return calendar.timegm(d.timetuple()) def datesafe_eq(obj1, obj2): """ If two objects are dates, but don't both have the same timezone awareness status, compare them in a timezone-safe way. Otherwise, compare them with regular equality. """ if isinstance(obj1, datetime) and not timezone.is_aware(obj1): obj1 = timezone.make_aware(obj1, pytz.UTC) if isinstance(obj2, datetime) and not timezone.is_aware(obj2): obj2 = timezone.make_aware(obj2, pytz.UTC) return obj1 == obj2 ## Instruction: Add function for nullsafe, tzsafe comparison ## Code After: from datetime import datetime from django.utils import timezone import calendar import pytz DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' DATE_FORMAT = '%Y-%m-%d' def parse_date_string_with_or_without_time(date_string): try: return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S') except ValueError: # If the time is not included, try again with date only return datetime.strptime(date_string.strip(), '%Y-%m-%d') def unix_timestamp(d=None): if d is None: d = timezone.now() return calendar.timegm(d.utctimetuple()) else: return calendar.timegm(d.timetuple()) def datesafe_eq(obj1, obj2): """ If two objects are dates, but don't both have the same timezone awareness status, compare them in a timezone-safe way. Otherwise, compare them with regular equality. """ if isinstance(obj1, datetime) and not timezone.is_aware(obj1): obj1 = timezone.make_aware(obj1, pytz.UTC) if isinstance(obj2, datetime) and not timezone.is_aware(obj2): obj2 = timezone.make_aware(obj2, pytz.UTC) return obj1 == obj2 def make_aware(value): if value is None or timezone.is_aware(value): return value else: return timezone.make_aware(value, timezone.utc)
from datetime import datetime from django.utils import timezone import calendar import pytz DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' DATE_FORMAT = '%Y-%m-%d' def parse_date_string_with_or_without_time(date_string): try: return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S') except ValueError: # If the time is not included, try again with date only return datetime.strptime(date_string.strip(), '%Y-%m-%d') def unix_timestamp(d=None): if d is None: d = timezone.now() return calendar.timegm(d.utctimetuple()) else: return calendar.timegm(d.timetuple()) def datesafe_eq(obj1, obj2): """ If two objects are dates, but don't both have the same timezone awareness status, compare them in a timezone-safe way. Otherwise, compare them with regular equality. """ if isinstance(obj1, datetime) and not timezone.is_aware(obj1): obj1 = timezone.make_aware(obj1, pytz.UTC) if isinstance(obj2, datetime) and not timezone.is_aware(obj2): obj2 = timezone.make_aware(obj2, pytz.UTC) return obj1 == obj2 + + + def make_aware(value): + if value is None or timezone.is_aware(value): + return value + else: + return timezone.make_aware(value, timezone.utc)
f68139ce9114f260487048716d7430fcb1b3173b
froide/helper/tasks.py
froide/helper/tasks.py
from django.conf import settings from django.utils import translation from celery.task import task from haystack import site @task def delayed_update(instance_pk, model): """ Only index stuff that is known to be public """ translation.activate(settings.LANGUAGE_CODE) try: instance = model.published.get(pk=instance_pk) except (model.DoesNotExist, AttributeError): return site.update_object(instance) @task def delayed_remove(instance_pk, model): translation.activate(settings.LANGUAGE_CODE) # Fake an instance (real one is already gone from the DB) fake_instance = model() fake_instance.pk = instance_pk site.remove_object(fake_instance)
import logging from django.conf import settings from django.utils import translation from celery.task import task from celery.signals import task_failure from haystack import site from sentry.client.handlers import SentryHandler # Hook up sentry to celery's logging # Based on http://www.colinhowe.co.uk/2011/02/08/celery-and-sentry-recording-errors/ logger = logging.getLogger('task') logger.addHandler(SentryHandler()) def process_failure_signal(exception, traceback, sender, task_id, signal, args, kwargs, einfo, **kw): exc_info = (type(exception), exception, traceback) logger.error( 'Celery job exception: %s(%s)' % (exception.__class__.__name__, exception), exc_info=exc_info, extra={ 'data': { 'task_id': task_id, 'sender': sender, 'args': args, 'kwargs': kwargs, } } ) task_failure.connect(process_failure_signal) @task def delayed_update(instance_pk, model): """ Only index stuff that is known to be public """ translation.activate(settings.LANGUAGE_CODE) try: instance = model.published.get(pk=instance_pk) except (model.DoesNotExist, AttributeError): return site.update_object(instance) @task def delayed_remove(instance_pk, model): translation.activate(settings.LANGUAGE_CODE) # Fake an instance (real one is already gone from the DB) fake_instance = model() fake_instance.pk = instance_pk site.remove_object(fake_instance)
Add celery task failure sentry tracking
Add celery task failure sentry tracking
Python
mit
catcosmo/froide,okfse/froide,ryankanno/froide,LilithWittmann/froide,CodeforHawaii/froide,ryankanno/froide,LilithWittmann/froide,LilithWittmann/froide,catcosmo/froide,ryankanno/froide,CodeforHawaii/froide,catcosmo/froide,stefanw/froide,LilithWittmann/froide,CodeforHawaii/froide,CodeforHawaii/froide,ryankanno/froide,okfse/froide,stefanw/froide,CodeforHawaii/froide,ryankanno/froide,stefanw/froide,stefanw/froide,okfse/froide,LilithWittmann/froide,fin/froide,fin/froide,catcosmo/froide,fin/froide,fin/froide,stefanw/froide,okfse/froide,okfse/froide,catcosmo/froide
+ import logging + from django.conf import settings from django.utils import translation from celery.task import task + from celery.signals import task_failure from haystack import site + from sentry.client.handlers import SentryHandler + + + # Hook up sentry to celery's logging + # Based on http://www.colinhowe.co.uk/2011/02/08/celery-and-sentry-recording-errors/ + + logger = logging.getLogger('task') + logger.addHandler(SentryHandler()) + def process_failure_signal(exception, traceback, sender, task_id, + signal, args, kwargs, einfo, **kw): + exc_info = (type(exception), exception, traceback) + logger.error( + 'Celery job exception: %s(%s)' % (exception.__class__.__name__, exception), + exc_info=exc_info, + extra={ + 'data': { + 'task_id': task_id, + 'sender': sender, + 'args': args, + 'kwargs': kwargs, + } + } + ) + task_failure.connect(process_failure_signal) @task def delayed_update(instance_pk, model): """ Only index stuff that is known to be public """ translation.activate(settings.LANGUAGE_CODE) try: instance = model.published.get(pk=instance_pk) except (model.DoesNotExist, AttributeError): return site.update_object(instance) @task def delayed_remove(instance_pk, model): translation.activate(settings.LANGUAGE_CODE) # Fake an instance (real one is already gone from the DB) fake_instance = model() fake_instance.pk = instance_pk site.remove_object(fake_instance) +
Add celery task failure sentry tracking
## Code Before: from django.conf import settings from django.utils import translation from celery.task import task from haystack import site @task def delayed_update(instance_pk, model): """ Only index stuff that is known to be public """ translation.activate(settings.LANGUAGE_CODE) try: instance = model.published.get(pk=instance_pk) except (model.DoesNotExist, AttributeError): return site.update_object(instance) @task def delayed_remove(instance_pk, model): translation.activate(settings.LANGUAGE_CODE) # Fake an instance (real one is already gone from the DB) fake_instance = model() fake_instance.pk = instance_pk site.remove_object(fake_instance) ## Instruction: Add celery task failure sentry tracking ## Code After: import logging from django.conf import settings from django.utils import translation from celery.task import task from celery.signals import task_failure from haystack import site from sentry.client.handlers import SentryHandler # Hook up sentry to celery's logging # Based on http://www.colinhowe.co.uk/2011/02/08/celery-and-sentry-recording-errors/ logger = logging.getLogger('task') logger.addHandler(SentryHandler()) def process_failure_signal(exception, traceback, sender, task_id, signal, args, kwargs, einfo, **kw): exc_info = (type(exception), exception, traceback) logger.error( 'Celery job exception: %s(%s)' % (exception.__class__.__name__, exception), exc_info=exc_info, extra={ 'data': { 'task_id': task_id, 'sender': sender, 'args': args, 'kwargs': kwargs, } } ) task_failure.connect(process_failure_signal) @task def delayed_update(instance_pk, model): """ Only index stuff that is known to be public """ translation.activate(settings.LANGUAGE_CODE) try: instance = model.published.get(pk=instance_pk) except (model.DoesNotExist, AttributeError): return site.update_object(instance) @task def delayed_remove(instance_pk, model): translation.activate(settings.LANGUAGE_CODE) # Fake an instance (real one is already gone from the DB) fake_instance = model() fake_instance.pk = instance_pk site.remove_object(fake_instance)
+ import logging + from django.conf import settings from django.utils import translation from celery.task import task + from celery.signals import task_failure from haystack import site + from sentry.client.handlers import SentryHandler + + + # Hook up sentry to celery's logging + # Based on http://www.colinhowe.co.uk/2011/02/08/celery-and-sentry-recording-errors/ + + logger = logging.getLogger('task') + logger.addHandler(SentryHandler()) + def process_failure_signal(exception, traceback, sender, task_id, + signal, args, kwargs, einfo, **kw): + exc_info = (type(exception), exception, traceback) + logger.error( + 'Celery job exception: %s(%s)' % (exception.__class__.__name__, exception), + exc_info=exc_info, + extra={ + 'data': { + 'task_id': task_id, + 'sender': sender, + 'args': args, + 'kwargs': kwargs, + } + } + ) + task_failure.connect(process_failure_signal) @task def delayed_update(instance_pk, model): """ Only index stuff that is known to be public """ translation.activate(settings.LANGUAGE_CODE) try: instance = model.published.get(pk=instance_pk) except (model.DoesNotExist, AttributeError): return site.update_object(instance) @task def delayed_remove(instance_pk, model): translation.activate(settings.LANGUAGE_CODE) # Fake an instance (real one is already gone from the DB) fake_instance = model() fake_instance.pk = instance_pk site.remove_object(fake_instance) +
595419eaa5b5f411e477357872c7dd28067c9210
src/books/models.py
src/books/models.py
from django.db import models from datetime import date from django.utils import timezone # Create your models here. class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) year = models.DateTimeField('year published', help_text="Please use the following format: <em>YYYY-MM-DD</em>.") pages = models.IntegerField(default=0) isbn_10 = models.IntegerField(default=0) isbn_13 = models.IntegerField(default=0) description = models.TextField() cover_image = models.ImageField('Cover Image', upload_to='cover_pics/%Y-%m-%d/', null=True, blank=True) add_date = models.DateTimeField('date added', default=datetime.now) def __str__(self): return self.title + " by " + self.author def was_added_recently(self): return self.add_date >= timezone.now() - datetime.timedelta(days=30)
from django.db import models from datetime import datetime from django.utils import timezone # Create your models here. class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) year = models.DateTimeField('year published', help_text="Please use the following format: <em>YYYY-MM-DD</em>.") pages = models.IntegerField(default=0) isbn_10 = models.IntegerField(default=0) isbn_13 = models.IntegerField(default=0) description = models.TextField() cover_image = models.ImageField('cover Image', upload_to='cover_pics/%Y-%m-%d/', null=True, blank=True) date_added = models.DateTimeField(default=datetime.now) def __str__(self): return self.title + " by " + self.author def was_added_recently(self): return self.date_added >= timezone.now() - datetime.timedelta(days=30)
Fix date error in books model
Fix date error in books model Fix typos and the auto addition of date to the date_added field.
Python
mit
melkisedek/sen_project,melkisedek/sen_project,melkisedek/sen_project
from django.db import models - from datetime import date + from datetime import datetime from django.utils import timezone # Create your models here. class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) year = models.DateTimeField('year published', help_text="Please use the following format: <em>YYYY-MM-DD</em>.") pages = models.IntegerField(default=0) isbn_10 = models.IntegerField(default=0) isbn_13 = models.IntegerField(default=0) description = models.TextField() - cover_image = models.ImageField('Cover Image', + cover_image = models.ImageField('cover Image', upload_to='cover_pics/%Y-%m-%d/', null=True, blank=True) - add_date = models.DateTimeField('date added', default=datetime.now) + date_added = models.DateTimeField(default=datetime.now) def __str__(self): return self.title + " by " + self.author def was_added_recently(self): - return self.add_date >= timezone.now() - datetime.timedelta(days=30) + return self.date_added >= timezone.now() - datetime.timedelta(days=30)
Fix date error in books model
## Code Before: from django.db import models from datetime import date from django.utils import timezone # Create your models here. class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) year = models.DateTimeField('year published', help_text="Please use the following format: <em>YYYY-MM-DD</em>.") pages = models.IntegerField(default=0) isbn_10 = models.IntegerField(default=0) isbn_13 = models.IntegerField(default=0) description = models.TextField() cover_image = models.ImageField('Cover Image', upload_to='cover_pics/%Y-%m-%d/', null=True, blank=True) add_date = models.DateTimeField('date added', default=datetime.now) def __str__(self): return self.title + " by " + self.author def was_added_recently(self): return self.add_date >= timezone.now() - datetime.timedelta(days=30) ## Instruction: Fix date error in books model ## Code After: from django.db import models from datetime import datetime from django.utils import timezone # Create your models here. class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) year = models.DateTimeField('year published', help_text="Please use the following format: <em>YYYY-MM-DD</em>.") pages = models.IntegerField(default=0) isbn_10 = models.IntegerField(default=0) isbn_13 = models.IntegerField(default=0) description = models.TextField() cover_image = models.ImageField('cover Image', upload_to='cover_pics/%Y-%m-%d/', null=True, blank=True) date_added = models.DateTimeField(default=datetime.now) def __str__(self): return self.title + " by " + self.author def was_added_recently(self): return self.date_added >= timezone.now() - datetime.timedelta(days=30)
from django.db import models - from datetime import date + from datetime import datetime ? ++++ from django.utils import timezone # Create your models here. class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) year = models.DateTimeField('year published', help_text="Please use the following format: <em>YYYY-MM-DD</em>.") pages = models.IntegerField(default=0) isbn_10 = models.IntegerField(default=0) isbn_13 = models.IntegerField(default=0) description = models.TextField() - cover_image = models.ImageField('Cover Image', ? ^ + cover_image = models.ImageField('cover Image', ? ^ upload_to='cover_pics/%Y-%m-%d/', null=True, blank=True) - add_date = models.DateTimeField('date added', default=datetime.now) ? ---- -------------- + date_added = models.DateTimeField(default=datetime.now) ? ++++++ def __str__(self): return self.title + " by " + self.author def was_added_recently(self): - return self.add_date >= timezone.now() - datetime.timedelta(days=30) ? ---- + return self.date_added >= timezone.now() - datetime.timedelta(days=30) ? ++++++
9a58d241e61301b9390b17e391e4b65a3ea85071
squadron/libraries/apt/__init__.py
squadron/libraries/apt/__init__.py
import os import subprocess from string import find def run_command(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return out,err def schema(): """ This returns """ return { 'title': 'apt schema', 'type': 'string' } def verify(inputhashes): """ """ failed = [] for package in inputhashes: out = run_command(['dpkg-query', '-W', package])[0] #We expect the output to contain the version #Any error doesn't get captured, so out will be empty (yes this is weird) if(find(out, package) == -1): failed.append(package) return failed def apply(inputhashes, dry_run=True): failed = [] for package in inputhashes: out = run_command(['apt-get', 'install', '-y', package]) if(find(out[1], 'Permission denied') != -1): failed.append(package) #Install failed because we're not root if(find(out[0], ('Setting up ' + package)) != -1 and find(out[0], (package + ' already the newest version')) != -1): #Something else happened, we weren't installed and we didn't get installed failed.append(package) print out return failed
import os import subprocess from string import find def run_command(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return out,err def schema(): """ This returns """ return { 'title': 'apt schema', 'type': 'string' } def verify(inputhashes): """ """ failed = [] for package in inputhashes: out = run_command(['dpkg-query', '-W', package])[0] #We expect the output to contain the version #Any error doesn't get captured, so out will be empty (yes this is weird) if(find(out, package) == -1): failed.append(package) return failed def apply(inputhashes, dry_run=True): failed = [] for package in inputhashes: out = run_command(['apt-get', 'install', '-y', package]) if(find(out[1], 'Permission denied') != -1): failed.append(package) # Install failed because we're not root if(find(out[0], ('Setting up ' + package)) != -1 and find(out[0], (package + ' already the newest version')) != -1): # Something else happened, we weren't installed and we didn't get installed failed.append(package) return failed
Remove extra print in apt
Remove extra print in apt
Python
mit
gosquadron/squadron,gosquadron/squadron
import os import subprocess from string import find def run_command(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return out,err def schema(): """ This returns """ return { 'title': 'apt schema', 'type': 'string' } def verify(inputhashes): """ """ failed = [] for package in inputhashes: out = run_command(['dpkg-query', '-W', package])[0] #We expect the output to contain the version #Any error doesn't get captured, so out will be empty (yes this is weird) if(find(out, package) == -1): failed.append(package) return failed def apply(inputhashes, dry_run=True): failed = [] for package in inputhashes: out = run_command(['apt-get', 'install', '-y', package]) if(find(out[1], 'Permission denied') != -1): - failed.append(package) #Install failed because we're not root + failed.append(package) # Install failed because we're not root if(find(out[0], ('Setting up ' + package)) != -1 and find(out[0], (package + ' already the newest version')) != -1): - #Something else happened, we weren't installed and we didn't get installed + # Something else happened, we weren't installed and we didn't get installed failed.append(package) - print out return failed
Remove extra print in apt
## Code Before: import os import subprocess from string import find def run_command(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return out,err def schema(): """ This returns """ return { 'title': 'apt schema', 'type': 'string' } def verify(inputhashes): """ """ failed = [] for package in inputhashes: out = run_command(['dpkg-query', '-W', package])[0] #We expect the output to contain the version #Any error doesn't get captured, so out will be empty (yes this is weird) if(find(out, package) == -1): failed.append(package) return failed def apply(inputhashes, dry_run=True): failed = [] for package in inputhashes: out = run_command(['apt-get', 'install', '-y', package]) if(find(out[1], 'Permission denied') != -1): failed.append(package) #Install failed because we're not root if(find(out[0], ('Setting up ' + package)) != -1 and find(out[0], (package + ' already the newest version')) != -1): #Something else happened, we weren't installed and we didn't get installed failed.append(package) print out return failed ## Instruction: Remove extra print in apt ## Code After: import os import subprocess from string import find def run_command(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return out,err def schema(): """ This returns """ return { 'title': 'apt schema', 'type': 'string' } def verify(inputhashes): """ """ failed = [] for package in inputhashes: out = run_command(['dpkg-query', '-W', package])[0] #We expect the output to contain the version #Any error doesn't get captured, so out will be empty (yes this is weird) if(find(out, package) == -1): failed.append(package) return failed def apply(inputhashes, dry_run=True): failed = [] for package in inputhashes: out = run_command(['apt-get', 'install', '-y', package]) if(find(out[1], 'Permission denied') != -1): failed.append(package) # Install failed because we're not root if(find(out[0], ('Setting up ' + package)) != -1 and find(out[0], (package + ' already the newest version')) != -1): # Something else happened, we weren't installed and we didn't get installed failed.append(package) return failed
import os import subprocess from string import find def run_command(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return out,err def schema(): """ This returns """ return { 'title': 'apt schema', 'type': 'string' } def verify(inputhashes): """ """ failed = [] for package in inputhashes: out = run_command(['dpkg-query', '-W', package])[0] #We expect the output to contain the version #Any error doesn't get captured, so out will be empty (yes this is weird) if(find(out, package) == -1): failed.append(package) return failed def apply(inputhashes, dry_run=True): failed = [] for package in inputhashes: out = run_command(['apt-get', 'install', '-y', package]) if(find(out[1], 'Permission denied') != -1): - failed.append(package) #Install failed because we're not root + failed.append(package) # Install failed because we're not root ? + if(find(out[0], ('Setting up ' + package)) != -1 and find(out[0], (package + ' already the newest version')) != -1): - #Something else happened, we weren't installed and we didn't get installed + # Something else happened, we weren't installed and we didn't get installed ? + failed.append(package) - print out return failed
16ad5a3f17fdb96f2660019fabbd7bb787ae4ffb
pywsd/baseline.py
pywsd/baseline.py
import random custom_random = random.Random(0) def random_sense(ambiguous_word, pos=None): """ Returns a random sense. """ if pos is None: return custom_random.choice(wn.synsets(ambiguous_word)) else: return custom_random.choice(wn.synsets(ambiguous_word, pos)) def first_sense(ambiguous_word, pos=None): """ Returns the first sense. """ if pos is None: return wn.synsets(ambiguous_word)[0] else: return wn.synsets(ambiguous_word, pos)[0] def max_lemma_count(ambiguous_word): """ Returns the sense with the highest lemma_name count. The max_lemma_count() can be treated as a rough gauge for the Most Frequent Sense (MFS), if no other sense annotated corpus is available. NOTE: The lemma counts are from the Brown Corpus """ sense2lemmacounts = {} for i in wn.synsets(ambiguous_word): sense2lemmacounts[i] = sum(j.count() for j in i.lemmas()) return max(sense2lemmacounts, key=sense2lemmacounts.get)
import random custom_random = random.Random(0) def random_sense(ambiguous_word, pos=None): """ Returns a random sense. """ if pos is None: return custom_random.choice(wn.synsets(ambiguous_word)) else: return custom_random.choice(wn.synsets(ambiguous_word, pos)) def first_sense(ambiguous_word, pos=None): """ Returns the first sense. """ if pos is None: return wn.synsets(ambiguous_word)[0] else: return wn.synsets(ambiguous_word, pos)[0] def max_lemma_count(ambiguous_word, pos=None): """ Returns the sense with the highest lemma_name count. The max_lemma_count() can be treated as a rough gauge for the Most Frequent Sense (MFS), if no other sense annotated corpus is available. NOTE: The lemma counts are from the Brown Corpus """ sense2lemmacounts = {} for i in wn.synsets(ambiguous_word, pos=None): sense2lemmacounts[i] = sum(j.count() for j in i.lemmas()) return max(sense2lemmacounts, key=sense2lemmacounts.get)
Add pos for max_lemma_count also
Add pos for max_lemma_count also
Python
mit
alvations/pywsd,alvations/pywsd
import random custom_random = random.Random(0) def random_sense(ambiguous_word, pos=None): """ Returns a random sense. """ if pos is None: return custom_random.choice(wn.synsets(ambiguous_word)) else: return custom_random.choice(wn.synsets(ambiguous_word, pos)) def first_sense(ambiguous_word, pos=None): """ Returns the first sense. """ if pos is None: return wn.synsets(ambiguous_word)[0] else: return wn.synsets(ambiguous_word, pos)[0] - def max_lemma_count(ambiguous_word): + def max_lemma_count(ambiguous_word, pos=None): """ Returns the sense with the highest lemma_name count. The max_lemma_count() can be treated as a rough gauge for the Most Frequent Sense (MFS), if no other sense annotated corpus is available. NOTE: The lemma counts are from the Brown Corpus """ sense2lemmacounts = {} - for i in wn.synsets(ambiguous_word): + for i in wn.synsets(ambiguous_word, pos=None): sense2lemmacounts[i] = sum(j.count() for j in i.lemmas()) return max(sense2lemmacounts, key=sense2lemmacounts.get)
Add pos for max_lemma_count also
## Code Before: import random custom_random = random.Random(0) def random_sense(ambiguous_word, pos=None): """ Returns a random sense. """ if pos is None: return custom_random.choice(wn.synsets(ambiguous_word)) else: return custom_random.choice(wn.synsets(ambiguous_word, pos)) def first_sense(ambiguous_word, pos=None): """ Returns the first sense. """ if pos is None: return wn.synsets(ambiguous_word)[0] else: return wn.synsets(ambiguous_word, pos)[0] def max_lemma_count(ambiguous_word): """ Returns the sense with the highest lemma_name count. The max_lemma_count() can be treated as a rough gauge for the Most Frequent Sense (MFS), if no other sense annotated corpus is available. NOTE: The lemma counts are from the Brown Corpus """ sense2lemmacounts = {} for i in wn.synsets(ambiguous_word): sense2lemmacounts[i] = sum(j.count() for j in i.lemmas()) return max(sense2lemmacounts, key=sense2lemmacounts.get) ## Instruction: Add pos for max_lemma_count also ## Code After: import random custom_random = random.Random(0) def random_sense(ambiguous_word, pos=None): """ Returns a random sense. """ if pos is None: return custom_random.choice(wn.synsets(ambiguous_word)) else: return custom_random.choice(wn.synsets(ambiguous_word, pos)) def first_sense(ambiguous_word, pos=None): """ Returns the first sense. """ if pos is None: return wn.synsets(ambiguous_word)[0] else: return wn.synsets(ambiguous_word, pos)[0] def max_lemma_count(ambiguous_word, pos=None): """ Returns the sense with the highest lemma_name count. The max_lemma_count() can be treated as a rough gauge for the Most Frequent Sense (MFS), if no other sense annotated corpus is available. NOTE: The lemma counts are from the Brown Corpus """ sense2lemmacounts = {} for i in wn.synsets(ambiguous_word, pos=None): sense2lemmacounts[i] = sum(j.count() for j in i.lemmas()) return max(sense2lemmacounts, key=sense2lemmacounts.get)
import random custom_random = random.Random(0) def random_sense(ambiguous_word, pos=None): """ Returns a random sense. """ if pos is None: return custom_random.choice(wn.synsets(ambiguous_word)) else: return custom_random.choice(wn.synsets(ambiguous_word, pos)) def first_sense(ambiguous_word, pos=None): """ Returns the first sense. """ if pos is None: return wn.synsets(ambiguous_word)[0] else: return wn.synsets(ambiguous_word, pos)[0] - def max_lemma_count(ambiguous_word): + def max_lemma_count(ambiguous_word, pos=None): ? ++++++++++ """ Returns the sense with the highest lemma_name count. The max_lemma_count() can be treated as a rough gauge for the Most Frequent Sense (MFS), if no other sense annotated corpus is available. NOTE: The lemma counts are from the Brown Corpus """ sense2lemmacounts = {} - for i in wn.synsets(ambiguous_word): + for i in wn.synsets(ambiguous_word, pos=None): ? ++++++++++ sense2lemmacounts[i] = sum(j.count() for j in i.lemmas()) return max(sense2lemmacounts, key=sense2lemmacounts.get)
eff3195097e9599b87f5cec9bbae744b91ae16cf
buses/utils.py
buses/utils.py
import re def minify(template_source): template_source = re.sub(r'(\n *)+', '\n', template_source) template_source = re.sub(r'({%.+%})\n+', r'\1', template_source) return template_source
import re from haystack.utils import default_get_identifier def minify(template_source): template_source = re.sub(r'(\n *)+', '\n', template_source) template_source = re.sub(r'({%.+%})\n+', r'\1', template_source) return template_source def get_identifier(obj_or_string): if isinstance(obj_or_string, basestring): return obj_or_string return default_get_identifier(obj_or_string)
Add custom Hastack get_identifier function
Add custom Hastack get_identifier function
Python
mpl-2.0
jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk
import re + from haystack.utils import default_get_identifier def minify(template_source): template_source = re.sub(r'(\n *)+', '\n', template_source) template_source = re.sub(r'({%.+%})\n+', r'\1', template_source) return template_source + def get_identifier(obj_or_string): + if isinstance(obj_or_string, basestring): + return obj_or_string + return default_get_identifier(obj_or_string) +
Add custom Hastack get_identifier function
## Code Before: import re def minify(template_source): template_source = re.sub(r'(\n *)+', '\n', template_source) template_source = re.sub(r'({%.+%})\n+', r'\1', template_source) return template_source ## Instruction: Add custom Hastack get_identifier function ## Code After: import re from haystack.utils import default_get_identifier def minify(template_source): template_source = re.sub(r'(\n *)+', '\n', template_source) template_source = re.sub(r'({%.+%})\n+', r'\1', template_source) return template_source def get_identifier(obj_or_string): if isinstance(obj_or_string, basestring): return obj_or_string return default_get_identifier(obj_or_string)
import re + from haystack.utils import default_get_identifier def minify(template_source): template_source = re.sub(r'(\n *)+', '\n', template_source) template_source = re.sub(r'({%.+%})\n+', r'\1', template_source) return template_source + + def get_identifier(obj_or_string): + if isinstance(obj_or_string, basestring): + return obj_or_string + return default_get_identifier(obj_or_string)
ef5d3c61acdb7538b4338351b8902802142e03a5
tests/bindings/python/scoring/test-scoring_result.py
tests/bindings/python/scoring/test-scoring_result.py
def test_import(): try: import vistk.pipeline_util.bake except: test_error("Failed to import the bake module") def test_api_calls(): from vistk.scoring import scoring_result result = scoring_result.ScoringResult(1, 1, 1) result.hit_count result.miss_count result.truth_count result.percent_detection() result.precision() result + result def main(testname): if testname == 'import': test_import() elif testname == 'api_calls': test_api_calls() else: test_error("No such test '%s'" % testname) if __name__ == '__main__': import os import sys if not len(sys.argv) == 4: test_error("Expected three arguments") sys.exit(1) testname = sys.argv[1] os.chdir(sys.argv[2]) sys.path.append(sys.argv[3]) from vistk.test.test import * try: main(testname) except BaseException as e: test_error("Unexpected exception: %s" % str(e))
def test_import(): try: import vistk.pipeline_util.bake except: test_error("Failed to import the bake module") def test_api_calls(): from vistk.scoring import scoring_result result = scoring_result.ScoringResult(1, 1, 1) result.true_positives result.false_positives result.total_trues result.total_possible result.percent_detection() result.precision() result.specificity() result + result def main(testname): if testname == 'import': test_import() elif testname == 'api_calls': test_api_calls() else: test_error("No such test '%s'" % testname) if __name__ == '__main__': import os import sys if not len(sys.argv) == 4: test_error("Expected three arguments") sys.exit(1) testname = sys.argv[1] os.chdir(sys.argv[2]) sys.path.append(sys.argv[3]) from vistk.test.test import * try: main(testname) except BaseException as e: test_error("Unexpected exception: %s" % str(e))
Update Python tests for scoring_result
Update Python tests for scoring_result
Python
bsd-3-clause
linus-sherrill/sprokit,mathstuf/sprokit,Kitware/sprokit,linus-sherrill/sprokit,linus-sherrill/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,Kitware/sprokit,Kitware/sprokit,Kitware/sprokit,mathstuf/sprokit,mathstuf/sprokit
def test_import(): try: import vistk.pipeline_util.bake except: test_error("Failed to import the bake module") def test_api_calls(): from vistk.scoring import scoring_result result = scoring_result.ScoringResult(1, 1, 1) - result.hit_count - result.miss_count - result.truth_count + result.true_positives + result.false_positives + result.total_trues + result.total_possible result.percent_detection() result.precision() + result.specificity() result + result def main(testname): if testname == 'import': test_import() elif testname == 'api_calls': test_api_calls() else: test_error("No such test '%s'" % testname) if __name__ == '__main__': import os import sys if not len(sys.argv) == 4: test_error("Expected three arguments") sys.exit(1) testname = sys.argv[1] os.chdir(sys.argv[2]) sys.path.append(sys.argv[3]) from vistk.test.test import * try: main(testname) except BaseException as e: test_error("Unexpected exception: %s" % str(e))
Update Python tests for scoring_result
## Code Before: def test_import(): try: import vistk.pipeline_util.bake except: test_error("Failed to import the bake module") def test_api_calls(): from vistk.scoring import scoring_result result = scoring_result.ScoringResult(1, 1, 1) result.hit_count result.miss_count result.truth_count result.percent_detection() result.precision() result + result def main(testname): if testname == 'import': test_import() elif testname == 'api_calls': test_api_calls() else: test_error("No such test '%s'" % testname) if __name__ == '__main__': import os import sys if not len(sys.argv) == 4: test_error("Expected three arguments") sys.exit(1) testname = sys.argv[1] os.chdir(sys.argv[2]) sys.path.append(sys.argv[3]) from vistk.test.test import * try: main(testname) except BaseException as e: test_error("Unexpected exception: %s" % str(e)) ## Instruction: Update Python tests for scoring_result ## Code After: def test_import(): try: import vistk.pipeline_util.bake except: test_error("Failed to import the bake module") def test_api_calls(): from vistk.scoring import scoring_result result = scoring_result.ScoringResult(1, 1, 1) result.true_positives result.false_positives result.total_trues result.total_possible result.percent_detection() result.precision() result.specificity() result + result def main(testname): if testname == 'import': test_import() elif testname == 'api_calls': test_api_calls() else: test_error("No such test '%s'" % testname) if __name__ == '__main__': import os import sys if not len(sys.argv) == 4: test_error("Expected three arguments") sys.exit(1) testname = sys.argv[1] os.chdir(sys.argv[2]) sys.path.append(sys.argv[3]) from vistk.test.test import * try: main(testname) except BaseException as e: test_error("Unexpected exception: %s" % str(e))
def test_import(): try: import vistk.pipeline_util.bake except: test_error("Failed to import the bake module") def test_api_calls(): from vistk.scoring import scoring_result result = scoring_result.ScoringResult(1, 1, 1) - result.hit_count - result.miss_count - result.truth_count + result.true_positives + result.false_positives + result.total_trues + result.total_possible result.percent_detection() result.precision() + result.specificity() result + result def main(testname): if testname == 'import': test_import() elif testname == 'api_calls': test_api_calls() else: test_error("No such test '%s'" % testname) if __name__ == '__main__': import os import sys if not len(sys.argv) == 4: test_error("Expected three arguments") sys.exit(1) testname = sys.argv[1] os.chdir(sys.argv[2]) sys.path.append(sys.argv[3]) from vistk.test.test import * try: main(testname) except BaseException as e: test_error("Unexpected exception: %s" % str(e))
a10ffe519c50bd248bd9bfcde648f66e15fb6fd3
node_bridge.py
node_bridge.py
import os import platform import subprocess IS_OSX = platform.system() == 'Darwin' IS_WINDOWS = platform.system() == 'Windows' def node_bridge(data, bin, args=[]): env = None startupinfo = None if IS_OSX: # GUI apps in OS X doesn't contain .bashrc/.zshrc set paths env = os.environ.copy() env['PATH'] += ':/usr/local/bin' if IS_WINDOWS: startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW try: p = subprocess.Popen(['node', bin] + args, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, env=env, startupinfo=startupinfo) except OSError: raise Exception('Couldn\'t find Node.js. Make sure it\'s in your $PATH by running `node -v` in your command-line.') stdout, stderr = p.communicate(input=data.encode('utf-8')) stdout = stdout.decode('utf-8') stderr = stderr.decode('utf-8') if stderr: raise Exception('Error: %s' % stderr) else: return stdout
import os import platform import subprocess IS_OSX = platform.system() == 'Darwin' IS_WINDOWS = platform.system() == 'Windows' def node_bridge(data, bin, args=[]): env = None startupinfo = None if IS_OSX: # GUI apps in OS X doesn't contain .bashrc/.zshrc set paths env = os.environ.copy() env['PATH'] += os.path.expanduser('~/n/bin') env['PATH'] += ':/usr/local/bin' if IS_WINDOWS: startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW try: p = subprocess.Popen(['node', bin] + args, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, env=env, startupinfo=startupinfo) except OSError: raise Exception('Couldn\'t find Node.js. Make sure it\'s in your $PATH by running `node -v` in your command-line.') stdout, stderr = p.communicate(input=data.encode('utf-8')) stdout = stdout.decode('utf-8') stderr = stderr.decode('utf-8') if stderr: raise Exception('Error: %s' % stderr) else: return stdout
Add support for `n` Node.js version manager
Add support for `n` Node.js version manager
Python
mit
hudochenkov/sublime-postcss-sorting,hudochenkov/sublime-postcss-sorting
import os import platform import subprocess IS_OSX = platform.system() == 'Darwin' IS_WINDOWS = platform.system() == 'Windows' def node_bridge(data, bin, args=[]): env = None startupinfo = None if IS_OSX: # GUI apps in OS X doesn't contain .bashrc/.zshrc set paths env = os.environ.copy() + env['PATH'] += os.path.expanduser('~/n/bin') env['PATH'] += ':/usr/local/bin' if IS_WINDOWS: startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW try: p = subprocess.Popen(['node', bin] + args, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, env=env, startupinfo=startupinfo) except OSError: raise Exception('Couldn\'t find Node.js. Make sure it\'s in your $PATH by running `node -v` in your command-line.') stdout, stderr = p.communicate(input=data.encode('utf-8')) stdout = stdout.decode('utf-8') stderr = stderr.decode('utf-8') if stderr: raise Exception('Error: %s' % stderr) else: return stdout
Add support for `n` Node.js version manager
## Code Before: import os import platform import subprocess IS_OSX = platform.system() == 'Darwin' IS_WINDOWS = platform.system() == 'Windows' def node_bridge(data, bin, args=[]): env = None startupinfo = None if IS_OSX: # GUI apps in OS X doesn't contain .bashrc/.zshrc set paths env = os.environ.copy() env['PATH'] += ':/usr/local/bin' if IS_WINDOWS: startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW try: p = subprocess.Popen(['node', bin] + args, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, env=env, startupinfo=startupinfo) except OSError: raise Exception('Couldn\'t find Node.js. Make sure it\'s in your $PATH by running `node -v` in your command-line.') stdout, stderr = p.communicate(input=data.encode('utf-8')) stdout = stdout.decode('utf-8') stderr = stderr.decode('utf-8') if stderr: raise Exception('Error: %s' % stderr) else: return stdout ## Instruction: Add support for `n` Node.js version manager ## Code After: import os import platform import subprocess IS_OSX = platform.system() == 'Darwin' IS_WINDOWS = platform.system() == 'Windows' def node_bridge(data, bin, args=[]): env = None startupinfo = None if IS_OSX: # GUI apps in OS X doesn't contain .bashrc/.zshrc set paths env = os.environ.copy() env['PATH'] += os.path.expanduser('~/n/bin') env['PATH'] += ':/usr/local/bin' if IS_WINDOWS: startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW try: p = subprocess.Popen(['node', bin] + args, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, env=env, startupinfo=startupinfo) except OSError: raise Exception('Couldn\'t find Node.js. Make sure it\'s in your $PATH by running `node -v` in your command-line.') stdout, stderr = p.communicate(input=data.encode('utf-8')) stdout = stdout.decode('utf-8') stderr = stderr.decode('utf-8') if stderr: raise Exception('Error: %s' % stderr) else: return stdout
import os import platform import subprocess IS_OSX = platform.system() == 'Darwin' IS_WINDOWS = platform.system() == 'Windows' def node_bridge(data, bin, args=[]): env = None startupinfo = None if IS_OSX: # GUI apps in OS X doesn't contain .bashrc/.zshrc set paths env = os.environ.copy() + env['PATH'] += os.path.expanduser('~/n/bin') env['PATH'] += ':/usr/local/bin' if IS_WINDOWS: startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW try: p = subprocess.Popen(['node', bin] + args, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, env=env, startupinfo=startupinfo) except OSError: raise Exception('Couldn\'t find Node.js. Make sure it\'s in your $PATH by running `node -v` in your command-line.') stdout, stderr = p.communicate(input=data.encode('utf-8')) stdout = stdout.decode('utf-8') stderr = stderr.decode('utf-8') if stderr: raise Exception('Error: %s' % stderr) else: return stdout
9ec35300975a141162749cba015cedbe900f97eb
idiotscript/Collector.py
idiotscript/Collector.py
class Collector(object): def __init__(self): self._groups = [] self._current_group = None def add_input(self, new_input): if self._current_group is None: self._current_group = [] self._current_group.append(new_input) def finalise_group(self): self._groups.append(self._current_group) self._current_group = None @property def groups(self): return self._groups @property def current_group(self): return self._current_group def __str__(self): temp = "" for group in self._groups: for text in group: temp += text + "\n" temp += "\n" return temp
class Collector(object): def __init__(self): self._groups = [] self._current_group = None def add_input(self, new_input): if self._current_group is None: self._current_group = [] self._groups.append(self._current_group) self._current_group.append(new_input) def finalise_group(self): self._current_group = None @property def groups(self): return self._groups @property def current_group(self): return self._current_group def __str__(self): temp = "" for group in self._groups: for text in group: temp += text + "\n" temp += "\n" return temp
Fix bug with collector losing last group of input
Fix bug with collector losing last group of input This means the script runner doesn't have to manually finalise the last input, which was always a bit silly. In fact, the whole metaphor is rather silly. I should change it to be "start new group" instead.
Python
unlicense
djmattyg007/IdiotScript
class Collector(object): def __init__(self): self._groups = [] self._current_group = None def add_input(self, new_input): if self._current_group is None: self._current_group = [] + self._groups.append(self._current_group) self._current_group.append(new_input) def finalise_group(self): - self._groups.append(self._current_group) self._current_group = None @property def groups(self): return self._groups @property def current_group(self): return self._current_group def __str__(self): temp = "" for group in self._groups: for text in group: temp += text + "\n" temp += "\n" return temp
Fix bug with collector losing last group of input
## Code Before: class Collector(object): def __init__(self): self._groups = [] self._current_group = None def add_input(self, new_input): if self._current_group is None: self._current_group = [] self._current_group.append(new_input) def finalise_group(self): self._groups.append(self._current_group) self._current_group = None @property def groups(self): return self._groups @property def current_group(self): return self._current_group def __str__(self): temp = "" for group in self._groups: for text in group: temp += text + "\n" temp += "\n" return temp ## Instruction: Fix bug with collector losing last group of input ## Code After: class Collector(object): def __init__(self): self._groups = [] self._current_group = None def add_input(self, new_input): if self._current_group is None: self._current_group = [] self._groups.append(self._current_group) self._current_group.append(new_input) def finalise_group(self): self._current_group = None @property def groups(self): return self._groups @property def current_group(self): return self._current_group def __str__(self): temp = "" for group in self._groups: for text in group: temp += text + "\n" temp += "\n" return temp
class Collector(object): def __init__(self): self._groups = [] self._current_group = None def add_input(self, new_input): if self._current_group is None: self._current_group = [] + self._groups.append(self._current_group) self._current_group.append(new_input) def finalise_group(self): - self._groups.append(self._current_group) self._current_group = None @property def groups(self): return self._groups @property def current_group(self): return self._current_group def __str__(self): temp = "" for group in self._groups: for text in group: temp += text + "\n" temp += "\n" return temp
4daefdb0a4def961572fc22d0fe01a394b11fad9
tests/test_httpclient.py
tests/test_httpclient.py
try: import unittest2 as unittest except ImportError: import unittest import sys sys.path.append('..') from pyrabbit import http class TestHTTPClient(unittest.TestCase): """ Except for the init test, these are largely functional tests that require a RabbitMQ management API to be available on localhost:55672 """ def setUp(self): self.c = http.HTTPClient('localhost:55672', 'guest', 'guest') def test_client_init(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest') self.assertIsInstance(c, http.HTTPClient) def test_client_init_sets_default_timeout(self): self.assertEqual(self.c.client.timeout, 1) def test_client_init_with_timeout(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest', 5) self.assertEqual(c.client.timeout, 5)
try: import unittest2 as unittest except ImportError: import unittest import sys sys.path.append('..') from pyrabbit import http class TestHTTPClient(unittest.TestCase): """ Except for the init test, these are largely functional tests that require a RabbitMQ management API to be available on localhost:55672 """ def setUp(self): self.c = http.HTTPClient('localhost:55672', 'guest', 'guest') def test_client_init(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest') self.assertIsInstance(c, http.HTTPClient) def test_client_init_sets_credentials(self): domain = '' expected_credentials = [(domain, 'guest', 'guest')] self.assertEqual( self.c.client.credentials.credentials, expected_credentials) def test_client_init_sets_default_timeout(self): self.assertEqual(self.c.client.timeout, 1) def test_client_init_with_timeout(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest', 5) self.assertEqual(c.client.timeout, 5)
Test creation of HTTP credentials
tests.http: Test creation of HTTP credentials
Python
bsd-3-clause
ranjithlav/pyrabbit,bkjones/pyrabbit,NeCTAR-RC/pyrabbit,chaos95/pyrabbit,switchtower/pyrabbit
try: import unittest2 as unittest except ImportError: import unittest import sys sys.path.append('..') from pyrabbit import http class TestHTTPClient(unittest.TestCase): """ Except for the init test, these are largely functional tests that require a RabbitMQ management API to be available on localhost:55672 """ def setUp(self): self.c = http.HTTPClient('localhost:55672', 'guest', 'guest') def test_client_init(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest') self.assertIsInstance(c, http.HTTPClient) + def test_client_init_sets_credentials(self): + domain = '' + expected_credentials = [(domain, 'guest', 'guest')] + self.assertEqual( + self.c.client.credentials.credentials, expected_credentials) + def test_client_init_sets_default_timeout(self): self.assertEqual(self.c.client.timeout, 1) def test_client_init_with_timeout(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest', 5) self.assertEqual(c.client.timeout, 5)
Test creation of HTTP credentials
## Code Before: try: import unittest2 as unittest except ImportError: import unittest import sys sys.path.append('..') from pyrabbit import http class TestHTTPClient(unittest.TestCase): """ Except for the init test, these are largely functional tests that require a RabbitMQ management API to be available on localhost:55672 """ def setUp(self): self.c = http.HTTPClient('localhost:55672', 'guest', 'guest') def test_client_init(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest') self.assertIsInstance(c, http.HTTPClient) def test_client_init_sets_default_timeout(self): self.assertEqual(self.c.client.timeout, 1) def test_client_init_with_timeout(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest', 5) self.assertEqual(c.client.timeout, 5) ## Instruction: Test creation of HTTP credentials ## Code After: try: import unittest2 as unittest except ImportError: import unittest import sys sys.path.append('..') from pyrabbit import http class TestHTTPClient(unittest.TestCase): """ Except for the init test, these are largely functional tests that require a RabbitMQ management API to be available on localhost:55672 """ def setUp(self): self.c = http.HTTPClient('localhost:55672', 'guest', 'guest') def test_client_init(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest') self.assertIsInstance(c, http.HTTPClient) def test_client_init_sets_credentials(self): domain = '' expected_credentials = [(domain, 'guest', 'guest')] self.assertEqual( self.c.client.credentials.credentials, expected_credentials) def test_client_init_sets_default_timeout(self): self.assertEqual(self.c.client.timeout, 1) def test_client_init_with_timeout(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest', 5) self.assertEqual(c.client.timeout, 5)
try: import unittest2 as unittest except ImportError: import unittest import sys sys.path.append('..') from pyrabbit import http class TestHTTPClient(unittest.TestCase): """ Except for the init test, these are largely functional tests that require a RabbitMQ management API to be available on localhost:55672 """ def setUp(self): self.c = http.HTTPClient('localhost:55672', 'guest', 'guest') def test_client_init(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest') self.assertIsInstance(c, http.HTTPClient) + def test_client_init_sets_credentials(self): + domain = '' + expected_credentials = [(domain, 'guest', 'guest')] + self.assertEqual( + self.c.client.credentials.credentials, expected_credentials) + def test_client_init_sets_default_timeout(self): self.assertEqual(self.c.client.timeout, 1) def test_client_init_with_timeout(self): c = http.HTTPClient('localhost:55672', 'guest', 'guest', 5) self.assertEqual(c.client.timeout, 5)
18bd0bcc0d892aef4ea9babfc6ec2af6e40cea62
manager/urls.py
manager/urls.py
from django.conf.urls import url from manager import views urlpatterns = [ url(r'^$', views.package_list, name='package_list'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/$', views.package_detail, name='package_detail'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/build/$', views.package_build, name='package_build'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/(?P<build_number>\d+)/$', views.build_detail, name='build_detail') ]
from django.conf.urls import url from manager import views urlpatterns = [ url(r'^$', views.package_list, name='package_list'), url(r'^packages/$', views.package_list, name='package_list'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/$', views.package_detail, name='package_detail'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/build/$', views.package_build, name='package_build'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/(?P<build_number>\d+)/$', views.build_detail, name='build_detail') ]
Add alternative package list url
Add alternative package list url
Python
mit
colajam93/aurpackager,colajam93/aurpackager,colajam93/aurpackager,colajam93/aurpackager
from django.conf.urls import url from manager import views urlpatterns = [ url(r'^$', views.package_list, name='package_list'), + url(r'^packages/$', views.package_list, name='package_list'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/$', views.package_detail, name='package_detail'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/build/$', views.package_build, name='package_build'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/(?P<build_number>\d+)/$', views.build_detail, name='build_detail') ]
Add alternative package list url
## Code Before: from django.conf.urls import url from manager import views urlpatterns = [ url(r'^$', views.package_list, name='package_list'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/$', views.package_detail, name='package_detail'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/build/$', views.package_build, name='package_build'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/(?P<build_number>\d+)/$', views.build_detail, name='build_detail') ] ## Instruction: Add alternative package list url ## Code After: from django.conf.urls import url from manager import views urlpatterns = [ url(r'^$', views.package_list, name='package_list'), url(r'^packages/$', views.package_list, name='package_list'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/$', views.package_detail, name='package_detail'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/build/$', views.package_build, name='package_build'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/(?P<build_number>\d+)/$', views.build_detail, name='build_detail') ]
from django.conf.urls import url from manager import views urlpatterns = [ url(r'^$', views.package_list, name='package_list'), + url(r'^packages/$', views.package_list, name='package_list'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/$', views.package_detail, name='package_detail'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/build/$', views.package_build, name='package_build'), url(r'^packages/(?P<package_name>[a-zA-Z0-9_+-]+)/(?P<build_number>\d+)/$', views.build_detail, name='build_detail') ]
a03eb91088943a4b3ed0ae5fc87b104562a4a645
location_field/urls.py
location_field/urls.py
try: from django.conf.urls import patterns # Django>=1.6 except ImportError: from django.conf.urls.defaults import patterns # Django<1.6 import os app_dir = os.path.dirname(__file__) urlpatterns = patterns( '', (r'^media/(.*)$', 'django.views.static.serve', { 'document_root': '%s/media' % app_dir}), )
from django.conf.urls import patterns import os app_dir = os.path.dirname(__file__) urlpatterns = patterns( '', (r'^media/(.*)$', 'django.views.static.serve', { 'document_root': '%s/media' % app_dir}), )
Drop support for Django 1.6
Drop support for Django 1.6
Python
mit
Mixser/django-location-field,recklessromeo/django-location-field,Mixser/django-location-field,voodmania/django-location-field,recklessromeo/django-location-field,undernewmanagement/django-location-field,voodmania/django-location-field,caioariede/django-location-field,caioariede/django-location-field,undernewmanagement/django-location-field,Mixser/django-location-field,undernewmanagement/django-location-field,caioariede/django-location-field,recklessromeo/django-location-field,voodmania/django-location-field
- try: - from django.conf.urls import patterns # Django>=1.6 + from django.conf.urls import patterns - except ImportError: - from django.conf.urls.defaults import patterns # Django<1.6 import os app_dir = os.path.dirname(__file__) urlpatterns = patterns( '', (r'^media/(.*)$', 'django.views.static.serve', { 'document_root': '%s/media' % app_dir}), )
Drop support for Django 1.6
## Code Before: try: from django.conf.urls import patterns # Django>=1.6 except ImportError: from django.conf.urls.defaults import patterns # Django<1.6 import os app_dir = os.path.dirname(__file__) urlpatterns = patterns( '', (r'^media/(.*)$', 'django.views.static.serve', { 'document_root': '%s/media' % app_dir}), ) ## Instruction: Drop support for Django 1.6 ## Code After: from django.conf.urls import patterns import os app_dir = os.path.dirname(__file__) urlpatterns = patterns( '', (r'^media/(.*)$', 'django.views.static.serve', { 'document_root': '%s/media' % app_dir}), )
- try: - from django.conf.urls import patterns # Django>=1.6 ? ---- --------------- + from django.conf.urls import patterns - except ImportError: - from django.conf.urls.defaults import patterns # Django<1.6 import os app_dir = os.path.dirname(__file__) urlpatterns = patterns( '', (r'^media/(.*)$', 'django.views.static.serve', { 'document_root': '%s/media' % app_dir}), )
ecac9283bc831a6879f21e80e1b98818683ff6a4
atlas/prodtask/management/commands/pthealthcheck.py
atlas/prodtask/management/commands/pthealthcheck.py
from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e)
from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: self.stdout.write(f'Start celery beat health check {timezone.now()}') try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e)
Add logging for health check
Add logging for health check
Python
apache-2.0
PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas
from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: + self.stdout.write(f'Start celery beat health check {timezone.now()}') + try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e)
Add logging for health check
## Code Before: from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e) ## Instruction: Add logging for health check ## Code After: from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: self.stdout.write(f'Start celery beat health check {timezone.now()}') try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e)
from django.core.management.base import BaseCommand, CommandError import time from django_celery_beat.models import PeriodicTask from django.utils import timezone from datetime import timedelta from atlas.prodtask.views import send_alarm_message class Command(BaseCommand): args = 'None' help = 'Check celery beat health' def handle(self, *args, **options): if not args: + self.stdout.write(f'Start celery beat health check {timezone.now()}') + try: try: last_executed_task = PeriodicTask.objects.all().order_by('-last_run_at')[0] except Exception as e: send_alarm_message('Alarm: the celery beat health check problem', f'Celery beat health check problem {e}') raise e if (timezone.now() - last_executed_task.last_run_at) > timedelta(hours=3): send_alarm_message('Alarm: the celery beat is stuck', f'Celery beat last updated {last_executed_task.last_run_at}') except Exception as e: raise CommandError('Some problem during alarm mail sending check: %s'%e)
5eb67411a44366ed90a6078f29f1977013c1a39c
awx/main/migrations/0017_v300_prompting_migrations.py
awx/main/migrations/0017_v300_prompting_migrations.py
from __future__ import unicode_literals from awx.main.migrations import _ask_for_variables as ask_for_variables from awx.main.migrations import _migration_utils as migration_utils from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0016_v300_prompting_changes'), ] operations = [ migrations.RunPython(migration_utils.set_current_apps_for_migrations), migrations.RunPython(ask_for_variables.migrate_credential), ]
from __future__ import unicode_literals from awx.main.migrations import _rbac as rbac from awx.main.migrations import _ask_for_variables as ask_for_variables from awx.main.migrations import _migration_utils as migration_utils from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0016_v300_prompting_changes'), ] operations = [ migrations.RunPython(migration_utils.set_current_apps_for_migrations), migrations.RunPython(ask_for_variables.migrate_credential), migrations.RunPython(rbac.rebuild_role_hierarchy), ]
Rebuild role hierarchy after making changes in migrations
Rebuild role hierarchy after making changes in migrations Signals don't fire in migrations, so gotta do this step manually
Python
apache-2.0
snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx
from __future__ import unicode_literals + from awx.main.migrations import _rbac as rbac from awx.main.migrations import _ask_for_variables as ask_for_variables from awx.main.migrations import _migration_utils as migration_utils from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0016_v300_prompting_changes'), ] operations = [ migrations.RunPython(migration_utils.set_current_apps_for_migrations), migrations.RunPython(ask_for_variables.migrate_credential), + migrations.RunPython(rbac.rebuild_role_hierarchy), ]
Rebuild role hierarchy after making changes in migrations
## Code Before: from __future__ import unicode_literals from awx.main.migrations import _ask_for_variables as ask_for_variables from awx.main.migrations import _migration_utils as migration_utils from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0016_v300_prompting_changes'), ] operations = [ migrations.RunPython(migration_utils.set_current_apps_for_migrations), migrations.RunPython(ask_for_variables.migrate_credential), ] ## Instruction: Rebuild role hierarchy after making changes in migrations ## Code After: from __future__ import unicode_literals from awx.main.migrations import _rbac as rbac from awx.main.migrations import _ask_for_variables as ask_for_variables from awx.main.migrations import _migration_utils as migration_utils from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0016_v300_prompting_changes'), ] operations = [ migrations.RunPython(migration_utils.set_current_apps_for_migrations), migrations.RunPython(ask_for_variables.migrate_credential), migrations.RunPython(rbac.rebuild_role_hierarchy), ]
from __future__ import unicode_literals + from awx.main.migrations import _rbac as rbac from awx.main.migrations import _ask_for_variables as ask_for_variables from awx.main.migrations import _migration_utils as migration_utils from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0016_v300_prompting_changes'), ] operations = [ migrations.RunPython(migration_utils.set_current_apps_for_migrations), migrations.RunPython(ask_for_variables.migrate_credential), + migrations.RunPython(rbac.rebuild_role_hierarchy), ]
9293a72faf8cd41dc68bb1f2220e10459bbe09ff
pycom/oslo_i18n.py
pycom/oslo_i18n.py
import oslo_i18n def reset_i18n(domain="app", localedir=None): global _translators, _, _C, _P, _LI, _LW, _LE, _LC # Enable lazy translation oslo_i18n.enable_lazy() _translators = oslo_i18n.TranslatorFactory(domain=domain, localedir=localedir) # The primary translation function using the well-known name "_" _ = _translators.primary # The contextual translation function using the name "_C" _C = _translators.contextual_form # The plural translation function using the name "_P" _P = _translators.plural_form # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical _translators, _, _C, _P, _LI, _LW, _LE, _LC = None reset_i18n()
import oslo_i18n def reset_i18n(domain="app", localedir=None, lazy=True): global _translators, _, _C, _P, _LI, _LW, _LE, _LC # Enable lazy translation if lazy: oslo_i18n.enable_lazy() _translators = oslo_i18n.TranslatorFactory(domain=domain, localedir=localedir) # The primary translation function using the well-known name "_" _ = _translators.primary # The contextual translation function using the name "_C" _C = _translators.contextual_form # The plural translation function using the name "_P" _P = _translators.plural_form # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical _translators = _ = _C = _P = _LI = _LW = _LE = _LC = None reset_i18n()
Add a argument and fix a error.
Add a argument and fix a error.
Python
mit
xgfone/pycom,xgfone/xutils
import oslo_i18n - def reset_i18n(domain="app", localedir=None): + def reset_i18n(domain="app", localedir=None, lazy=True): global _translators, _, _C, _P, _LI, _LW, _LE, _LC # Enable lazy translation + if lazy: - oslo_i18n.enable_lazy() + oslo_i18n.enable_lazy() _translators = oslo_i18n.TranslatorFactory(domain=domain, localedir=localedir) # The primary translation function using the well-known name "_" _ = _translators.primary # The contextual translation function using the name "_C" _C = _translators.contextual_form # The plural translation function using the name "_P" _P = _translators.plural_form # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical - _translators, _, _C, _P, _LI, _LW, _LE, _LC = None + _translators = _ = _C = _P = _LI = _LW = _LE = _LC = None reset_i18n()
Add a argument and fix a error.
## Code Before: import oslo_i18n def reset_i18n(domain="app", localedir=None): global _translators, _, _C, _P, _LI, _LW, _LE, _LC # Enable lazy translation oslo_i18n.enable_lazy() _translators = oslo_i18n.TranslatorFactory(domain=domain, localedir=localedir) # The primary translation function using the well-known name "_" _ = _translators.primary # The contextual translation function using the name "_C" _C = _translators.contextual_form # The plural translation function using the name "_P" _P = _translators.plural_form # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical _translators, _, _C, _P, _LI, _LW, _LE, _LC = None reset_i18n() ## Instruction: Add a argument and fix a error. ## Code After: import oslo_i18n def reset_i18n(domain="app", localedir=None, lazy=True): global _translators, _, _C, _P, _LI, _LW, _LE, _LC # Enable lazy translation if lazy: oslo_i18n.enable_lazy() _translators = oslo_i18n.TranslatorFactory(domain=domain, localedir=localedir) # The primary translation function using the well-known name "_" _ = _translators.primary # The contextual translation function using the name "_C" _C = _translators.contextual_form # The plural translation function using the name "_P" _P = _translators.plural_form # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical _translators = _ = _C = _P = _LI = _LW = _LE = _LC = None reset_i18n()
import oslo_i18n - def reset_i18n(domain="app", localedir=None): + def reset_i18n(domain="app", localedir=None, lazy=True): ? +++++++++++ global _translators, _, _C, _P, _LI, _LW, _LE, _LC # Enable lazy translation + if lazy: - oslo_i18n.enable_lazy() + oslo_i18n.enable_lazy() ? ++++ _translators = oslo_i18n.TranslatorFactory(domain=domain, localedir=localedir) # The primary translation function using the well-known name "_" _ = _translators.primary # The contextual translation function using the name "_C" _C = _translators.contextual_form # The plural translation function using the name "_P" _P = _translators.plural_form # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical - _translators, _, _C, _P, _LI, _LW, _LE, _LC = None ? ^ ^ ^ ^ ^ ^ ^ + _translators = _ = _C = _P = _LI = _LW = _LE = _LC = None ? ^^ ^^ ^^ ^^ ^^ ^^ ^^ reset_i18n()
24ff6aa99c7ee78d58200aad03c50722563cb1a0
purchase_product_usage/models/account_move.py
purchase_product_usage/models/account_move.py
from odoo import api, models class AccountMoveLine(models.Model): _inherit = "account.move.line" @api.onchange( "amount_currency", "currency_id", "debit", "credit", "tax_ids", "account_id", "analytic_account_id", "analytic_tag_ids", ) def _onchange_mark_recompute_taxes(self): for line in self: if line.purchase_line_id.usage_id.account_id: account = line.purchase_line_id.usage_id.account_id else: account = line._get_computed_account() line.account_id = account return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
from odoo import api, models class AccountMoveLine(models.Model): _inherit = "account.move.line" @api.onchange( "amount_currency", "currency_id", "debit", "credit", "tax_ids", "account_id", "analytic_account_id", "analytic_tag_ids", ) def _onchange_mark_recompute_taxes(self): for line in self: if line.purchase_line_id.usage_id.account_id: line.account_id = line.purchase_line_id.usage_id.account_id return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
Change only account if usage is defined in POL
[13.0][FIX] purchase_product_usage: Change only account if usage is defined in POL
Python
agpl-3.0
OCA/purchase-workflow,OCA/purchase-workflow
from odoo import api, models class AccountMoveLine(models.Model): _inherit = "account.move.line" @api.onchange( "amount_currency", "currency_id", "debit", "credit", "tax_ids", "account_id", "analytic_account_id", "analytic_tag_ids", ) def _onchange_mark_recompute_taxes(self): for line in self: if line.purchase_line_id.usage_id.account_id: - account = line.purchase_line_id.usage_id.account_id + line.account_id = line.purchase_line_id.usage_id.account_id - else: - account = line._get_computed_account() - line.account_id = account return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
Change only account if usage is defined in POL
## Code Before: from odoo import api, models class AccountMoveLine(models.Model): _inherit = "account.move.line" @api.onchange( "amount_currency", "currency_id", "debit", "credit", "tax_ids", "account_id", "analytic_account_id", "analytic_tag_ids", ) def _onchange_mark_recompute_taxes(self): for line in self: if line.purchase_line_id.usage_id.account_id: account = line.purchase_line_id.usage_id.account_id else: account = line._get_computed_account() line.account_id = account return super(AccountMoveLine, self)._onchange_mark_recompute_taxes() ## Instruction: Change only account if usage is defined in POL ## Code After: from odoo import api, models class AccountMoveLine(models.Model): _inherit = "account.move.line" @api.onchange( "amount_currency", "currency_id", "debit", "credit", "tax_ids", "account_id", "analytic_account_id", "analytic_tag_ids", ) def _onchange_mark_recompute_taxes(self): for line in self: if line.purchase_line_id.usage_id.account_id: line.account_id = line.purchase_line_id.usage_id.account_id return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
from odoo import api, models class AccountMoveLine(models.Model): _inherit = "account.move.line" @api.onchange( "amount_currency", "currency_id", "debit", "credit", "tax_ids", "account_id", "analytic_account_id", "analytic_tag_ids", ) def _onchange_mark_recompute_taxes(self): for line in self: if line.purchase_line_id.usage_id.account_id: - account = line.purchase_line_id.usage_id.account_id + line.account_id = line.purchase_line_id.usage_id.account_id ? +++++ +++ - else: - account = line._get_computed_account() - line.account_id = account return super(AccountMoveLine, self)._onchange_mark_recompute_taxes()
8fe8717b4e2afe6329d2dd25210371df3eab2b4f
test/test_stdlib.py
test/test_stdlib.py
import pep543.stdlib from .backend_tests import SimpleNegotiation class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND
import pep543 import pep543.stdlib import pytest from .backend_tests import SimpleNegotiation CONTEXTS = ( pep543.stdlib.STDLIB_BACKEND.client_context, pep543.stdlib.STDLIB_BACKEND.server_context ) def assert_wrap_fails(context, exception): """ A convenient helper that calls wrap_buffers with the appropriate number of arugments and asserts that it raises the appropriate error. """ if isinstance(context, pep543.stdlib.STDLIB_BACKEND.client_context): with pytest.raises(exception): context.wrap_buffers(server_hostname=None) else: with pytest.raises(exception): context.wrap_buffers() class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND class TestStdlibErrorHandling(object): """ Validate that the stdlib backend can do sensible error handling in specific situations that it cannot handle. """ @pytest.mark.parametrize( 'lowest,highest', ( (object(), None), (None, object()), (object(), object()) ) ) @pytest.mark.parametrize('context', CONTEXTS) def test_bad_values_for_versions_client(self, lowest, highest, context): """ Using TLSConfiguration objects with a bad value for their minimum version raises a TLSError with Client contexts. """ config = pep543.TLSConfiguration( validate_certificates=False, lowest_supported_version=lowest, highest_supported_version=highest ) ctx = context(config) assert_wrap_fails(ctx, pep543.TLSError)
Test that we reject bad TLS versions
Test that we reject bad TLS versions
Python
mit
python-hyper/pep543
+ import pep543 import pep543.stdlib + import pytest + from .backend_tests import SimpleNegotiation + + + CONTEXTS = ( + pep543.stdlib.STDLIB_BACKEND.client_context, + pep543.stdlib.STDLIB_BACKEND.server_context + ) + + + def assert_wrap_fails(context, exception): + """ + A convenient helper that calls wrap_buffers with the appropriate number of + arugments and asserts that it raises the appropriate error. + """ + if isinstance(context, pep543.stdlib.STDLIB_BACKEND.client_context): + with pytest.raises(exception): + context.wrap_buffers(server_hostname=None) + else: + with pytest.raises(exception): + context.wrap_buffers() class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND + + class TestStdlibErrorHandling(object): + """ + Validate that the stdlib backend can do sensible error handling in specific + situations that it cannot handle. + """ + @pytest.mark.parametrize( + 'lowest,highest', ( + (object(), None), (None, object()), (object(), object()) + ) + ) + @pytest.mark.parametrize('context', CONTEXTS) + def test_bad_values_for_versions_client(self, lowest, highest, context): + """ + Using TLSConfiguration objects with a bad value for their minimum + version raises a TLSError with Client contexts. + """ + config = pep543.TLSConfiguration( + validate_certificates=False, + lowest_supported_version=lowest, + highest_supported_version=highest + ) + ctx = context(config) + assert_wrap_fails(ctx, pep543.TLSError) +
Test that we reject bad TLS versions
## Code Before: import pep543.stdlib from .backend_tests import SimpleNegotiation class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND ## Instruction: Test that we reject bad TLS versions ## Code After: import pep543 import pep543.stdlib import pytest from .backend_tests import SimpleNegotiation CONTEXTS = ( pep543.stdlib.STDLIB_BACKEND.client_context, pep543.stdlib.STDLIB_BACKEND.server_context ) def assert_wrap_fails(context, exception): """ A convenient helper that calls wrap_buffers with the appropriate number of arugments and asserts that it raises the appropriate error. """ if isinstance(context, pep543.stdlib.STDLIB_BACKEND.client_context): with pytest.raises(exception): context.wrap_buffers(server_hostname=None) else: with pytest.raises(exception): context.wrap_buffers() class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND class TestStdlibErrorHandling(object): """ Validate that the stdlib backend can do sensible error handling in specific situations that it cannot handle. """ @pytest.mark.parametrize( 'lowest,highest', ( (object(), None), (None, object()), (object(), object()) ) ) @pytest.mark.parametrize('context', CONTEXTS) def test_bad_values_for_versions_client(self, lowest, highest, context): """ Using TLSConfiguration objects with a bad value for their minimum version raises a TLSError with Client contexts. """ config = pep543.TLSConfiguration( validate_certificates=False, lowest_supported_version=lowest, highest_supported_version=highest ) ctx = context(config) assert_wrap_fails(ctx, pep543.TLSError)
+ import pep543 import pep543.stdlib + + import pytest from .backend_tests import SimpleNegotiation + CONTEXTS = ( + pep543.stdlib.STDLIB_BACKEND.client_context, + pep543.stdlib.STDLIB_BACKEND.server_context + ) + + + def assert_wrap_fails(context, exception): + """ + A convenient helper that calls wrap_buffers with the appropriate number of + arugments and asserts that it raises the appropriate error. + """ + if isinstance(context, pep543.stdlib.STDLIB_BACKEND.client_context): + with pytest.raises(exception): + context.wrap_buffers(server_hostname=None) + else: + with pytest.raises(exception): + context.wrap_buffers() + + class TestSimpleNegotiationStdlib(SimpleNegotiation): BACKEND = pep543.stdlib.STDLIB_BACKEND + + + class TestStdlibErrorHandling(object): + """ + Validate that the stdlib backend can do sensible error handling in specific + situations that it cannot handle. + """ + @pytest.mark.parametrize( + 'lowest,highest', ( + (object(), None), (None, object()), (object(), object()) + ) + ) + @pytest.mark.parametrize('context', CONTEXTS) + def test_bad_values_for_versions_client(self, lowest, highest, context): + """ + Using TLSConfiguration objects with a bad value for their minimum + version raises a TLSError with Client contexts. + """ + config = pep543.TLSConfiguration( + validate_certificates=False, + lowest_supported_version=lowest, + highest_supported_version=highest + ) + ctx = context(config) + assert_wrap_fails(ctx, pep543.TLSError)
332452cf7ccd6d3ee583be9a6aac27b14771263f
source/services/omdb_service.py
source/services/omdb_service.py
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() ratings = [] ratings.append(movie_info['tomatoMeter']) ratings.append(movie_info['tomatoUserMeter']) return RTRating(ratings)
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() scores = [] scores.append(movie_info['tomatoMeter']) scores.append(movie_info['tomatoUserMeter']) rt_rating = RTRating(scores) rt_rating.link = movie_info['tomatoURL'] return rt_rating
Add url to RTRating object
Add url to RTRating object
Python
mit
jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() - ratings = [] + scores = [] - ratings.append(movie_info['tomatoMeter']) + scores.append(movie_info['tomatoMeter']) - ratings.append(movie_info['tomatoUserMeter']) + scores.append(movie_info['tomatoUserMeter']) - return RTRating(ratings) + rt_rating = RTRating(scores) + rt_rating.link = movie_info['tomatoURL'] + return rt_rating +
Add url to RTRating object
## Code Before: import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() ratings = [] ratings.append(movie_info['tomatoMeter']) ratings.append(movie_info['tomatoUserMeter']) return RTRating(ratings) ## Instruction: Add url to RTRating object ## Code After: import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() scores = [] scores.append(movie_info['tomatoMeter']) scores.append(movie_info['tomatoUserMeter']) rt_rating = RTRating(scores) rt_rating.link = movie_info['tomatoURL'] return rt_rating
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class OmdbService: __API_URL = 'http://www.omdbapi.com/?' def __init__(self, movie_id): self.id = movie_id def get_rt_rating(self): payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'} response = requests.post(self.__API_URL, params=payload) movie_info = response.json() - ratings = [] ? ^^^^^ + scores = [] ? +++ ^ - ratings.append(movie_info['tomatoMeter']) ? ^^^^^ + scores.append(movie_info['tomatoMeter']) ? +++ ^ - ratings.append(movie_info['tomatoUserMeter']) ? ^^^^^ + scores.append(movie_info['tomatoUserMeter']) ? +++ ^ + rt_rating = RTRating(scores) + rt_rating.link = movie_info['tomatoURL'] + - return RTRating(ratings) ? ^^^^ ^^^^ -- + return rt_rating ? ^ ^
849a4e5daf2eb845213ea76179d7a8143148f39a
lib/mixins.py
lib/mixins.py
class Countable(object): @classmethod def count(cls, options={}): return int(cls.get("count", **options)) class Metafields(object): def metafields(self): return Metafield.find(resource=self.__class__.plural, resource_id=self.id) def add_metafield(self, metafield): if self.is_new(): raise ValueError("You can only add metafields to a resource that has been saved") metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id) metafield.save() return metafield class Events(object): def events(self): return Event.find(resource=self.__class__.plural, resource_id=self.id)
class Countable(object): @classmethod def count(cls, _options=None, **kwargs): if _options is None: _options = kwargs return int(cls.get("count", **_options)) class Metafields(object): def metafields(self): return Metafield.find(resource=self.__class__.plural, resource_id=self.id) def add_metafield(self, metafield): if self.is_new(): raise ValueError("You can only add metafields to a resource that has been saved") metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id) metafield.save() return metafield class Events(object): def events(self): return Event.find(resource=self.__class__.plural, resource_id=self.id)
Allow count method to be used the same way as find.
Allow count method to be used the same way as find.
Python
mit
varesa/shopify_python_api,metric-collective/shopify_python_api,gavinballard/shopify_python_api,asiviero/shopify_python_api,ifnull/shopify_python_api,Shopify/shopify_python_api,SmileyJames/shopify_python_api
class Countable(object): @classmethod - def count(cls, options={}): + def count(cls, _options=None, **kwargs): + if _options is None: + _options = kwargs - return int(cls.get("count", **options)) + return int(cls.get("count", **_options)) class Metafields(object): def metafields(self): return Metafield.find(resource=self.__class__.plural, resource_id=self.id) def add_metafield(self, metafield): if self.is_new(): raise ValueError("You can only add metafields to a resource that has been saved") metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id) metafield.save() return metafield class Events(object): def events(self): return Event.find(resource=self.__class__.plural, resource_id=self.id)
Allow count method to be used the same way as find.
## Code Before: class Countable(object): @classmethod def count(cls, options={}): return int(cls.get("count", **options)) class Metafields(object): def metafields(self): return Metafield.find(resource=self.__class__.plural, resource_id=self.id) def add_metafield(self, metafield): if self.is_new(): raise ValueError("You can only add metafields to a resource that has been saved") metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id) metafield.save() return metafield class Events(object): def events(self): return Event.find(resource=self.__class__.plural, resource_id=self.id) ## Instruction: Allow count method to be used the same way as find. ## Code After: class Countable(object): @classmethod def count(cls, _options=None, **kwargs): if _options is None: _options = kwargs return int(cls.get("count", **_options)) class Metafields(object): def metafields(self): return Metafield.find(resource=self.__class__.plural, resource_id=self.id) def add_metafield(self, metafield): if self.is_new(): raise ValueError("You can only add metafields to a resource that has been saved") metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id) metafield.save() return metafield class Events(object): def events(self): return Event.find(resource=self.__class__.plural, resource_id=self.id)
class Countable(object): @classmethod - def count(cls, options={}): ? ^^ + def count(cls, _options=None, **kwargs): ? + ^^^^^^^^^^^^^^ + if _options is None: + _options = kwargs - return int(cls.get("count", **options)) + return int(cls.get("count", **_options)) ? + class Metafields(object): def metafields(self): return Metafield.find(resource=self.__class__.plural, resource_id=self.id) def add_metafield(self, metafield): if self.is_new(): raise ValueError("You can only add metafields to a resource that has been saved") metafield._prefix_options = dict(resource=self.__class__.plural, resource_id=self.id) metafield.save() return metafield class Events(object): def events(self): return Event.find(resource=self.__class__.plural, resource_id=self.id)
63f650855dfc707c6850add17d9171ba003bebcb
ckeditor_demo/urls.py
ckeditor_demo/urls.py
from __future__ import absolute_import import django from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles import views from .demo_application.views import ckeditor_form_view if django.VERSION >= (1, 8): urlpatterns = [ url(r'^$', ckeditor_form_view, name='ckeditor-form'), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor.urls')), url(r'^static/(?P<path>.*)$', views.serve), ] else: from django.conf.urls import patterns admin.autodiscover() urlpatterns = patterns( '', url(r'^$', ckeditor_form_view, name='ckeditor-form'), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor.urls')), url(r'^static/(?P<path>.*)$', views.serve), ) urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from __future__ import absolute_import import django from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles import views from .demo_application.views import ckeditor_form_view if django.VERSION >= (1, 8): urlpatterns = [ url(r'^$', ckeditor_form_view, name='ckeditor-form'), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor.urls')), url(r'^static/(?P<path>.*)$', views.serve), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), ] else: from django.conf.urls import patterns admin.autodiscover() urlpatterns = patterns( '', url(r'^$', ckeditor_form_view, name='ckeditor-form'), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor.urls')), url(r'^static/(?P<path>.*)$', views.serve), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), )
Fix media handling in demo application.
Fix media handling in demo application.
Python
bsd-3-clause
MarcJoan/django-ckeditor,gushedaoren/django-ckeditor,luzfcb/django-ckeditor,luzfcb/django-ckeditor,luzfcb/django-ckeditor,gushedaoren/django-ckeditor,zatarus/django-ckeditor,zatarus/django-ckeditor,Josephpaik/django-ckeditor,MarcJoan/django-ckeditor,gushedaoren/django-ckeditor,zatarus/django-ckeditor,MarcJoan/django-ckeditor,Josephpaik/django-ckeditor,Josephpaik/django-ckeditor
from __future__ import absolute_import import django from django.conf import settings from django.conf.urls import include, url - from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles import views from .demo_application.views import ckeditor_form_view if django.VERSION >= (1, 8): urlpatterns = [ url(r'^$', ckeditor_form_view, name='ckeditor-form'), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor.urls')), url(r'^static/(?P<path>.*)$', views.serve), + url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { + 'document_root': settings.MEDIA_ROOT, + }), ] else: from django.conf.urls import patterns admin.autodiscover() urlpatterns = patterns( '', url(r'^$', ckeditor_form_view, name='ckeditor-form'), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor.urls')), url(r'^static/(?P<path>.*)$', views.serve), + url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { + 'document_root': settings.MEDIA_ROOT, + }), ) - urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Fix media handling in demo application.
## Code Before: from __future__ import absolute_import import django from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles import views from .demo_application.views import ckeditor_form_view if django.VERSION >= (1, 8): urlpatterns = [ url(r'^$', ckeditor_form_view, name='ckeditor-form'), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor.urls')), url(r'^static/(?P<path>.*)$', views.serve), ] else: from django.conf.urls import patterns admin.autodiscover() urlpatterns = patterns( '', url(r'^$', ckeditor_form_view, name='ckeditor-form'), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor.urls')), url(r'^static/(?P<path>.*)$', views.serve), ) urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ## Instruction: Fix media handling in demo application. ## Code After: from __future__ import absolute_import import django from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles import views from .demo_application.views import ckeditor_form_view if django.VERSION >= (1, 8): urlpatterns = [ url(r'^$', ckeditor_form_view, name='ckeditor-form'), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor.urls')), url(r'^static/(?P<path>.*)$', views.serve), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), ] else: from django.conf.urls import patterns admin.autodiscover() urlpatterns = patterns( '', url(r'^$', ckeditor_form_view, name='ckeditor-form'), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor.urls')), url(r'^static/(?P<path>.*)$', views.serve), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), )
from __future__ import absolute_import import django from django.conf import settings from django.conf.urls import include, url - from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles import views from .demo_application.views import ckeditor_form_view if django.VERSION >= (1, 8): urlpatterns = [ url(r'^$', ckeditor_form_view, name='ckeditor-form'), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor.urls')), url(r'^static/(?P<path>.*)$', views.serve), + url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { + 'document_root': settings.MEDIA_ROOT, + }), ] else: from django.conf.urls import patterns admin.autodiscover() urlpatterns = patterns( '', url(r'^$', ckeditor_form_view, name='ckeditor-form'), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor.urls')), url(r'^static/(?P<path>.*)$', views.serve), + url(r'^media/(?P<path>.*)$', 'django.views.static.serve', { + 'document_root': settings.MEDIA_ROOT, + }), ) - - urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
2a37edaef3be06ab97bb1561b51d7977909e4abe
feed_sources/CTTransit.py
feed_sources/CTTransit.py
"""Fetch CT Transit (Connecticut) feeds.""" import logging from FeedSource import FeedSource LOG = logging.getLogger(__name__) BASE_URL = 'http://www.cttransit.com/uploads_GTFS/' SHORELINE_EAST_URL = 'http://www.shorelineeast.com/google_transit.zip' class CTTransit(FeedSource): """Fetch PATH feed.""" def __init__(self): super(CTTransit, self).__init__() # feeds for Hartford, New Haven, Stamford, Waterbury, New Britain, Meridien, # and Shore Line East. Shore Line East has its own URL. ct_suffixes = {'Hartford': 'ha', 'New Haven': 'nh', 'Stamford': 'stam', 'Waterbury': 'wat', 'New Britain': 'nb', 'Meridien': 'me'} urls = {} for sfx in ct_suffixes: url = '%sgoogle%s_transit.zip' % (BASE_URL, ct_suffixes[sfx]) filename = 'ct_%s.zip' % ct_suffixes[sfx] urls[filename] = url urls['ct_shoreline_east.zip'] = SHORELINE_EAST_URL self.urls = urls
"""Fetch CT Transit (Connecticut) feeds.""" import logging from FeedSource import FeedSource LOG = logging.getLogger(__name__) BASE_URL = 'http://www.cttransit.com/sites/default/files/gtfs/googlect_transit.zip' SHORELINE_EAST_URL = 'http://www.shorelineeast.com/google_transit.zip' HARTFORD_URL = 'http://www.hartfordline.com/files/gtfs/gtfs.zip' class CTTransit(FeedSource): """Fetch PATH feed.""" def __init__(self): super(CTTransit, self).__init__() self.urls = { 'ct_transit.zip': BASE_URL, 'ct_shoreline_east.zip': SHORELINE_EAST_URL, 'ct_hartford_rail.zip': HARTFORD_URL }
Update CT Transit feed fetcher
Update CT Transit feed fetcher CT Transit has changed their URLs.
Python
mit
azavea/gtfs-feed-fetcher
"""Fetch CT Transit (Connecticut) feeds.""" import logging from FeedSource import FeedSource LOG = logging.getLogger(__name__) - BASE_URL = 'http://www.cttransit.com/uploads_GTFS/' + BASE_URL = 'http://www.cttransit.com/sites/default/files/gtfs/googlect_transit.zip' SHORELINE_EAST_URL = 'http://www.shorelineeast.com/google_transit.zip' + HARTFORD_URL = 'http://www.hartfordline.com/files/gtfs/gtfs.zip' class CTTransit(FeedSource): """Fetch PATH feed.""" def __init__(self): super(CTTransit, self).__init__() - # feeds for Hartford, New Haven, Stamford, Waterbury, New Britain, Meridien, - # and Shore Line East. Shore Line East has its own URL. - ct_suffixes = {'Hartford': 'ha', 'New Haven': 'nh', 'Stamford': 'stam', - 'Waterbury': 'wat', 'New Britain': 'nb', 'Meridien': 'me'} + self.urls = { + 'ct_transit.zip': BASE_URL, + 'ct_shoreline_east.zip': SHORELINE_EAST_URL, + 'ct_hartford_rail.zip': HARTFORD_URL + } - urls = {} - for sfx in ct_suffixes: - url = '%sgoogle%s_transit.zip' % (BASE_URL, ct_suffixes[sfx]) - filename = 'ct_%s.zip' % ct_suffixes[sfx] - urls[filename] = url - - urls['ct_shoreline_east.zip'] = SHORELINE_EAST_URL - self.urls = urls -
Update CT Transit feed fetcher
## Code Before: """Fetch CT Transit (Connecticut) feeds.""" import logging from FeedSource import FeedSource LOG = logging.getLogger(__name__) BASE_URL = 'http://www.cttransit.com/uploads_GTFS/' SHORELINE_EAST_URL = 'http://www.shorelineeast.com/google_transit.zip' class CTTransit(FeedSource): """Fetch PATH feed.""" def __init__(self): super(CTTransit, self).__init__() # feeds for Hartford, New Haven, Stamford, Waterbury, New Britain, Meridien, # and Shore Line East. Shore Line East has its own URL. ct_suffixes = {'Hartford': 'ha', 'New Haven': 'nh', 'Stamford': 'stam', 'Waterbury': 'wat', 'New Britain': 'nb', 'Meridien': 'me'} urls = {} for sfx in ct_suffixes: url = '%sgoogle%s_transit.zip' % (BASE_URL, ct_suffixes[sfx]) filename = 'ct_%s.zip' % ct_suffixes[sfx] urls[filename] = url urls['ct_shoreline_east.zip'] = SHORELINE_EAST_URL self.urls = urls ## Instruction: Update CT Transit feed fetcher ## Code After: """Fetch CT Transit (Connecticut) feeds.""" import logging from FeedSource import FeedSource LOG = logging.getLogger(__name__) BASE_URL = 'http://www.cttransit.com/sites/default/files/gtfs/googlect_transit.zip' SHORELINE_EAST_URL = 'http://www.shorelineeast.com/google_transit.zip' HARTFORD_URL = 'http://www.hartfordline.com/files/gtfs/gtfs.zip' class CTTransit(FeedSource): """Fetch PATH feed.""" def __init__(self): super(CTTransit, self).__init__() self.urls = { 'ct_transit.zip': BASE_URL, 'ct_shoreline_east.zip': SHORELINE_EAST_URL, 'ct_hartford_rail.zip': HARTFORD_URL }
"""Fetch CT Transit (Connecticut) feeds.""" import logging from FeedSource import FeedSource LOG = logging.getLogger(__name__) - BASE_URL = 'http://www.cttransit.com/uploads_GTFS/' + BASE_URL = 'http://www.cttransit.com/sites/default/files/gtfs/googlect_transit.zip' SHORELINE_EAST_URL = 'http://www.shorelineeast.com/google_transit.zip' + HARTFORD_URL = 'http://www.hartfordline.com/files/gtfs/gtfs.zip' class CTTransit(FeedSource): """Fetch PATH feed.""" def __init__(self): super(CTTransit, self).__init__() - # feeds for Hartford, New Haven, Stamford, Waterbury, New Britain, Meridien, - # and Shore Line East. Shore Line East has its own URL. - ct_suffixes = {'Hartford': 'ha', 'New Haven': 'nh', 'Stamford': 'stam', - 'Waterbury': 'wat', 'New Britain': 'nb', 'Meridien': 'me'} - - urls = {} - for sfx in ct_suffixes: - url = '%sgoogle%s_transit.zip' % (BASE_URL, ct_suffixes[sfx]) - filename = 'ct_%s.zip' % ct_suffixes[sfx] - urls[filename] = url - - urls['ct_shoreline_east.zip'] = SHORELINE_EAST_URL - self.urls = urls ? ^^^^ + self.urls = { ? ^ + 'ct_transit.zip': BASE_URL, + 'ct_shoreline_east.zip': SHORELINE_EAST_URL, + 'ct_hartford_rail.zip': HARTFORD_URL + }
6f128279e8f4126c2d0f1a4076b93768678cdc0a
zerver/migrations/0130_text_choice_in_emojiset.py
zerver/migrations/0130_text_choice_in_emojiset.py
from django.db import migrations, models from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps # change emojiset to text if emoji_alt_code is true. def change_emojiset(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: UserProfile = apps.get_model("zerver", "UserProfile") for user in UserProfile.objects.filter(emoji_alt_code=True): user.emojiset = "text" user.save(update_fields=["emojiset"]) class Migration(migrations.Migration): dependencies = [ ('zerver', '0129_remove_userprofile_autoscroll_forever'), ] operations = [ migrations.AlterField( model_name='userprofile', name='emojiset', field=models.CharField(choices=[('google', 'Google'), ('apple', 'Apple'), ('twitter', 'Twitter'), ('emojione', 'EmojiOne'), ('text', 'Plain text')], default='google', max_length=20), ), migrations.RunPython(change_emojiset), migrations.RemoveField( model_name='userprofile', name='emoji_alt_code', ), ]
from django.db import migrations, models from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps # change emojiset to text if emoji_alt_code is true. def change_emojiset(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: UserProfile = apps.get_model("zerver", "UserProfile") for user in UserProfile.objects.filter(emoji_alt_code=True): user.emojiset = "text" user.save(update_fields=["emojiset"]) def reverse_change_emojiset(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: UserProfile = apps.get_model("zerver", "UserProfile") for user in UserProfile.objects.filter(emojiset="text"): # Resetting `emojiset` to "google" (the default) doesn't make an # exact round trip, but it's nearly indistinguishable -- the setting # shouldn't really matter while `emoji_alt_code` is true. user.emoji_alt_code = True user.emojiset = "google" user.save(update_fields=["emoji_alt_code", "emojiset"]) class Migration(migrations.Migration): dependencies = [ ('zerver', '0129_remove_userprofile_autoscroll_forever'), ] operations = [ migrations.AlterField( model_name='userprofile', name='emojiset', field=models.CharField(choices=[('google', 'Google'), ('apple', 'Apple'), ('twitter', 'Twitter'), ('emojione', 'EmojiOne'), ('text', 'Plain text')], default='google', max_length=20), ), migrations.RunPython(change_emojiset, reverse_change_emojiset), migrations.RemoveField( model_name='userprofile', name='emoji_alt_code', ), ]
Add reverser for emoji_alt_code migration.
migrations: Add reverser for emoji_alt_code migration. This is easy to do, and prevents this feature from getting a server admin stuck in potentially a pretty uncomfortable way -- unable to roll back a deploy.
Python
apache-2.0
tommyip/zulip,eeshangarg/zulip,rht/zulip,jackrzhang/zulip,brainwane/zulip,andersk/zulip,shubhamdhama/zulip,shubhamdhama/zulip,punchagan/zulip,kou/zulip,hackerkid/zulip,timabbott/zulip,showell/zulip,hackerkid/zulip,eeshangarg/zulip,dhcrzf/zulip,andersk/zulip,shubhamdhama/zulip,punchagan/zulip,kou/zulip,synicalsyntax/zulip,hackerkid/zulip,dhcrzf/zulip,showell/zulip,rishig/zulip,shubhamdhama/zulip,hackerkid/zulip,hackerkid/zulip,rishig/zulip,eeshangarg/zulip,synicalsyntax/zulip,timabbott/zulip,synicalsyntax/zulip,shubhamdhama/zulip,rht/zulip,synicalsyntax/zulip,jackrzhang/zulip,dhcrzf/zulip,kou/zulip,andersk/zulip,andersk/zulip,synicalsyntax/zulip,jackrzhang/zulip,dhcrzf/zulip,brainwane/zulip,jackrzhang/zulip,kou/zulip,punchagan/zulip,zulip/zulip,timabbott/zulip,brainwane/zulip,zulip/zulip,rht/zulip,rht/zulip,tommyip/zulip,tommyip/zulip,tommyip/zulip,jackrzhang/zulip,andersk/zulip,rishig/zulip,synicalsyntax/zulip,tommyip/zulip,zulip/zulip,punchagan/zulip,brainwane/zulip,showell/zulip,eeshangarg/zulip,showell/zulip,rishig/zulip,dhcrzf/zulip,punchagan/zulip,punchagan/zulip,eeshangarg/zulip,showell/zulip,timabbott/zulip,shubhamdhama/zulip,zulip/zulip,showell/zulip,zulip/zulip,brainwane/zulip,eeshangarg/zulip,timabbott/zulip,showell/zulip,jackrzhang/zulip,hackerkid/zulip,rishig/zulip,eeshangarg/zulip,tommyip/zulip,kou/zulip,dhcrzf/zulip,shubhamdhama/zulip,rht/zulip,synicalsyntax/zulip,timabbott/zulip,zulip/zulip,tommyip/zulip,zulip/zulip,kou/zulip,andersk/zulip,hackerkid/zulip,rishig/zulip,timabbott/zulip,punchagan/zulip,rht/zulip,andersk/zulip,rishig/zulip,brainwane/zulip,jackrzhang/zulip,kou/zulip,brainwane/zulip,dhcrzf/zulip,rht/zulip
from django.db import migrations, models from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps # change emojiset to text if emoji_alt_code is true. def change_emojiset(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: UserProfile = apps.get_model("zerver", "UserProfile") for user in UserProfile.objects.filter(emoji_alt_code=True): user.emojiset = "text" user.save(update_fields=["emojiset"]) + + def reverse_change_emojiset(apps: StateApps, + schema_editor: DatabaseSchemaEditor) -> None: + UserProfile = apps.get_model("zerver", "UserProfile") + for user in UserProfile.objects.filter(emojiset="text"): + # Resetting `emojiset` to "google" (the default) doesn't make an + # exact round trip, but it's nearly indistinguishable -- the setting + # shouldn't really matter while `emoji_alt_code` is true. + user.emoji_alt_code = True + user.emojiset = "google" + user.save(update_fields=["emoji_alt_code", "emojiset"]) class Migration(migrations.Migration): dependencies = [ ('zerver', '0129_remove_userprofile_autoscroll_forever'), ] operations = [ migrations.AlterField( model_name='userprofile', name='emojiset', field=models.CharField(choices=[('google', 'Google'), ('apple', 'Apple'), ('twitter', 'Twitter'), ('emojione', 'EmojiOne'), ('text', 'Plain text')], default='google', max_length=20), ), - migrations.RunPython(change_emojiset), + migrations.RunPython(change_emojiset, reverse_change_emojiset), migrations.RemoveField( model_name='userprofile', name='emoji_alt_code', ), ]
Add reverser for emoji_alt_code migration.
## Code Before: from django.db import migrations, models from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps # change emojiset to text if emoji_alt_code is true. def change_emojiset(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: UserProfile = apps.get_model("zerver", "UserProfile") for user in UserProfile.objects.filter(emoji_alt_code=True): user.emojiset = "text" user.save(update_fields=["emojiset"]) class Migration(migrations.Migration): dependencies = [ ('zerver', '0129_remove_userprofile_autoscroll_forever'), ] operations = [ migrations.AlterField( model_name='userprofile', name='emojiset', field=models.CharField(choices=[('google', 'Google'), ('apple', 'Apple'), ('twitter', 'Twitter'), ('emojione', 'EmojiOne'), ('text', 'Plain text')], default='google', max_length=20), ), migrations.RunPython(change_emojiset), migrations.RemoveField( model_name='userprofile', name='emoji_alt_code', ), ] ## Instruction: Add reverser for emoji_alt_code migration. ## Code After: from django.db import migrations, models from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps # change emojiset to text if emoji_alt_code is true. def change_emojiset(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: UserProfile = apps.get_model("zerver", "UserProfile") for user in UserProfile.objects.filter(emoji_alt_code=True): user.emojiset = "text" user.save(update_fields=["emojiset"]) def reverse_change_emojiset(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: UserProfile = apps.get_model("zerver", "UserProfile") for user in UserProfile.objects.filter(emojiset="text"): # Resetting `emojiset` to "google" (the default) doesn't make an # exact round trip, but it's nearly indistinguishable -- the setting # shouldn't really matter while `emoji_alt_code` is true. user.emoji_alt_code = True user.emojiset = "google" user.save(update_fields=["emoji_alt_code", "emojiset"]) class Migration(migrations.Migration): dependencies = [ ('zerver', '0129_remove_userprofile_autoscroll_forever'), ] operations = [ migrations.AlterField( model_name='userprofile', name='emojiset', field=models.CharField(choices=[('google', 'Google'), ('apple', 'Apple'), ('twitter', 'Twitter'), ('emojione', 'EmojiOne'), ('text', 'Plain text')], default='google', max_length=20), ), migrations.RunPython(change_emojiset, reverse_change_emojiset), migrations.RemoveField( model_name='userprofile', name='emoji_alt_code', ), ]
from django.db import migrations, models from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps # change emojiset to text if emoji_alt_code is true. def change_emojiset(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: UserProfile = apps.get_model("zerver", "UserProfile") for user in UserProfile.objects.filter(emoji_alt_code=True): user.emojiset = "text" user.save(update_fields=["emojiset"]) + + def reverse_change_emojiset(apps: StateApps, + schema_editor: DatabaseSchemaEditor) -> None: + UserProfile = apps.get_model("zerver", "UserProfile") + for user in UserProfile.objects.filter(emojiset="text"): + # Resetting `emojiset` to "google" (the default) doesn't make an + # exact round trip, but it's nearly indistinguishable -- the setting + # shouldn't really matter while `emoji_alt_code` is true. + user.emoji_alt_code = True + user.emojiset = "google" + user.save(update_fields=["emoji_alt_code", "emojiset"]) class Migration(migrations.Migration): dependencies = [ ('zerver', '0129_remove_userprofile_autoscroll_forever'), ] operations = [ migrations.AlterField( model_name='userprofile', name='emojiset', field=models.CharField(choices=[('google', 'Google'), ('apple', 'Apple'), ('twitter', 'Twitter'), ('emojione', 'EmojiOne'), ('text', 'Plain text')], default='google', max_length=20), ), - migrations.RunPython(change_emojiset), + migrations.RunPython(change_emojiset, reverse_change_emojiset), ? +++++++++++++++++++++++++ migrations.RemoveField( model_name='userprofile', name='emoji_alt_code', ), ]
9ce2faa950086f95f5a9c1f3e4f22e0a52622d8f
luminoso_api/wrappers/account.py
luminoso_api/wrappers/account.py
from .base import BaseWrapper from .database import Database from ..constants import URL_BASE class Account(BaseWrapper): """An object encapsulating a billing account on Luminoso's servers""" def __init__(self, acct_name, session): """Construct a wrapper around a particular account name NOTE: Construction does not validate the existence or accessibility of the account""" super(Account, self).__init__(path=acct_name, session=session) self.acct_name = acct_name def __unicode__(self): return u'Account("%s")' % self.acct_name @classmethod def accessible(cls, session): accounts = session.get(URL_BASE + '/.accounts/').json return [Account(acct, session) for acct in accounts['accounts']] def databases(self): db_table = self._get('/.list_dbs/') dbs = {} for db_name, db_meta in db_table.items(): path = self.api_path + '/' + db_meta['name'] dbs[db_name]=Database(path, db_name, meta=db_meta, session=self._session) return dbs def create_project(self, db_name): resp = self._post_raw('/%s/create_project/' % db_name) if resp == 'Database %s created' % db_name: return None return resp
from .base import BaseWrapper from .database import Database from ..constants import URL_BASE class Account(BaseWrapper): """An object encapsulating a billing account on Luminoso's servers""" def __init__(self, acct_name, session): """Construct a wrapper around a particular account name NOTE: Construction does not validate the existence or accessibility of the account""" super(Account, self).__init__(path=acct_name, session=session) self.acct_name = acct_name def __unicode__(self): return u'Account("%s")' % self.acct_name @classmethod def accessible(cls, session): accounts = session.get(URL_BASE + '/.accounts/').json return [Account(acct, session) for acct in accounts['accounts']] def databases(self): db_table = self._get('/.list_dbs/')['result'] dbs = {} for db_name, db_meta in db_table.items(): path = self.api_path + '/' + db_meta['name'] dbs[db_name]=Database(path, db_name, meta=db_meta, session=self._session) return dbs def create_project(self, db_name): resp = self._post_raw('/%s/create_project/' % db_name) if resp == 'Database %s created' % db_name: return None return resp
Adjust Account.databases() to new return format
Adjust Account.databases() to new return format
Python
mit
LuminosoInsight/luminoso-api-client-python
from .base import BaseWrapper from .database import Database from ..constants import URL_BASE class Account(BaseWrapper): """An object encapsulating a billing account on Luminoso's servers""" def __init__(self, acct_name, session): """Construct a wrapper around a particular account name NOTE: Construction does not validate the existence or accessibility of the account""" super(Account, self).__init__(path=acct_name, session=session) self.acct_name = acct_name def __unicode__(self): return u'Account("%s")' % self.acct_name @classmethod def accessible(cls, session): accounts = session.get(URL_BASE + '/.accounts/').json return [Account(acct, session) for acct in accounts['accounts']] def databases(self): - db_table = self._get('/.list_dbs/') + db_table = self._get('/.list_dbs/')['result'] dbs = {} for db_name, db_meta in db_table.items(): path = self.api_path + '/' + db_meta['name'] dbs[db_name]=Database(path, db_name, meta=db_meta, session=self._session) return dbs def create_project(self, db_name): resp = self._post_raw('/%s/create_project/' % db_name) if resp == 'Database %s created' % db_name: return None return resp
Adjust Account.databases() to new return format
## Code Before: from .base import BaseWrapper from .database import Database from ..constants import URL_BASE class Account(BaseWrapper): """An object encapsulating a billing account on Luminoso's servers""" def __init__(self, acct_name, session): """Construct a wrapper around a particular account name NOTE: Construction does not validate the existence or accessibility of the account""" super(Account, self).__init__(path=acct_name, session=session) self.acct_name = acct_name def __unicode__(self): return u'Account("%s")' % self.acct_name @classmethod def accessible(cls, session): accounts = session.get(URL_BASE + '/.accounts/').json return [Account(acct, session) for acct in accounts['accounts']] def databases(self): db_table = self._get('/.list_dbs/') dbs = {} for db_name, db_meta in db_table.items(): path = self.api_path + '/' + db_meta['name'] dbs[db_name]=Database(path, db_name, meta=db_meta, session=self._session) return dbs def create_project(self, db_name): resp = self._post_raw('/%s/create_project/' % db_name) if resp == 'Database %s created' % db_name: return None return resp ## Instruction: Adjust Account.databases() to new return format ## Code After: from .base import BaseWrapper from .database import Database from ..constants import URL_BASE class Account(BaseWrapper): """An object encapsulating a billing account on Luminoso's servers""" def __init__(self, acct_name, session): """Construct a wrapper around a particular account name NOTE: Construction does not validate the existence or accessibility of the account""" super(Account, self).__init__(path=acct_name, session=session) self.acct_name = acct_name def __unicode__(self): return u'Account("%s")' % self.acct_name @classmethod def accessible(cls, session): accounts = session.get(URL_BASE + '/.accounts/').json return [Account(acct, session) for acct in accounts['accounts']] def databases(self): db_table = self._get('/.list_dbs/')['result'] dbs = {} for db_name, db_meta in db_table.items(): path = self.api_path + '/' + db_meta['name'] dbs[db_name]=Database(path, db_name, meta=db_meta, session=self._session) return dbs def create_project(self, db_name): resp = self._post_raw('/%s/create_project/' % db_name) if resp == 'Database %s created' % db_name: return None return resp
from .base import BaseWrapper from .database import Database from ..constants import URL_BASE class Account(BaseWrapper): """An object encapsulating a billing account on Luminoso's servers""" def __init__(self, acct_name, session): """Construct a wrapper around a particular account name NOTE: Construction does not validate the existence or accessibility of the account""" super(Account, self).__init__(path=acct_name, session=session) self.acct_name = acct_name def __unicode__(self): return u'Account("%s")' % self.acct_name @classmethod def accessible(cls, session): accounts = session.get(URL_BASE + '/.accounts/').json return [Account(acct, session) for acct in accounts['accounts']] def databases(self): - db_table = self._get('/.list_dbs/') + db_table = self._get('/.list_dbs/')['result'] ? ++++++++++ dbs = {} for db_name, db_meta in db_table.items(): path = self.api_path + '/' + db_meta['name'] dbs[db_name]=Database(path, db_name, meta=db_meta, session=self._session) return dbs def create_project(self, db_name): resp = self._post_raw('/%s/create_project/' % db_name) if resp == 'Database %s created' % db_name: return None return resp
b63b22678a005baa6195854b65cc1828061febba
vx/mode.py
vx/mode.py
import vx import os.path def mode_from_filename(file): root, ext = os.path.splitext(file) ext = ext if ext else root mode = None if ext == '.c': return c_mode class mode: def __init__(self, window): self.breaks = ('_', ' ', '\n', '\t') self.keywords = () class python_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '{', '}', '.', ',', '#') self.keywords = ('return', 'for', 'while', 'break', 'continue', 'def') class c_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '<', '>', '.', ',', '#') self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'"(?:[^"\\]|\\.)*"')
import vx import os.path def mode_from_filename(file): root, ext = os.path.splitext(file) ext = ext if ext else root mode = None if ext == '.c': return c_mode elif ext == '.py': return python_mode class mode: def __init__(self, window): self.breaks = ('_', ' ', '\n', '\t') self.keywords = () class python_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '{', '}', '.', ',', '#') self.keywords = ('class', 'return', 'for', 'while', 'break', 'continue', 'def', 'from', 'import') class c_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '<', '>', '.', ',', '#') self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'"(?:[^"\\]|\\.)*"')
Add .py extension handling and more python keywords
Add .py extension handling and more python keywords
Python
mit
philipdexter/vx,philipdexter/vx
import vx import os.path def mode_from_filename(file): root, ext = os.path.splitext(file) ext = ext if ext else root mode = None if ext == '.c': return c_mode + elif ext == '.py': + return python_mode class mode: def __init__(self, window): self.breaks = ('_', ' ', '\n', '\t') self.keywords = () class python_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '{', '}', '.', ',', '#') - self.keywords = ('return', 'for', 'while', 'break', 'continue', 'def') + self.keywords = ('class', 'return', 'for', 'while', 'break', 'continue', 'def', 'from', 'import') class c_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '<', '>', '.', ',', '#') self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'"(?:[^"\\]|\\.)*"')
Add .py extension handling and more python keywords
## Code Before: import vx import os.path def mode_from_filename(file): root, ext = os.path.splitext(file) ext = ext if ext else root mode = None if ext == '.c': return c_mode class mode: def __init__(self, window): self.breaks = ('_', ' ', '\n', '\t') self.keywords = () class python_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '{', '}', '.', ',', '#') self.keywords = ('return', 'for', 'while', 'break', 'continue', 'def') class c_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '<', '>', '.', ',', '#') self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'"(?:[^"\\]|\\.)*"') ## Instruction: Add .py extension handling and more python keywords ## Code After: import vx import os.path def mode_from_filename(file): root, ext = os.path.splitext(file) ext = ext if ext else root mode = None if ext == '.c': return c_mode elif ext == '.py': return python_mode class mode: def __init__(self, window): self.breaks = ('_', ' ', '\n', '\t') self.keywords = () class python_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '{', '}', '.', ',', '#') self.keywords = ('class', 'return', 'for', 'while', 'break', 'continue', 'def', 'from', 'import') class c_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '<', '>', '.', ',', '#') self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'"(?:[^"\\]|\\.)*"')
import vx import os.path def mode_from_filename(file): root, ext = os.path.splitext(file) ext = ext if ext else root mode = None if ext == '.c': return c_mode + elif ext == '.py': + return python_mode class mode: def __init__(self, window): self.breaks = ('_', ' ', '\n', '\t') self.keywords = () class python_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '{', '}', '.', ',', '#') - self.keywords = ('return', 'for', 'while', 'break', 'continue', 'def') + self.keywords = ('class', 'return', 'for', 'while', 'break', 'continue', 'def', 'from', 'import') ? +++++++++ ++++++++++++++++++ class c_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '<', '>', '.', ',', '#') self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'"(?:[^"\\]|\\.)*"')
605443886582d13c2b45b19fad86854bf4e8ddbd
backend/catalogue/serializers.py
backend/catalogue/serializers.py
from rest_framework import serializers from .models import Release, Track, Comment class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('id', 'comment') class TrackSerializer(serializers.ModelSerializer): cdid = serializers.StringRelatedField( read_only=True ) class Meta: model = Track fields = ('trackid', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'cdid') class ReleaseSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedIdentityField(view_name='release-tracks') comments = serializers.HyperlinkedIdentityField(view_name='release-comments') class Meta: model = Release fields = ('id', 'arrivaldate', 'artist', 'title', 'year', 'local', 'cpa', 'compilation', 'female', 'tracks', 'comments')
from rest_framework import serializers from .models import Release, Track, Comment class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('id', 'comment') class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('trackid', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'release') class ReleaseSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedIdentityField(view_name='release-tracks') comments = serializers.HyperlinkedIdentityField(view_name='release-comments') class Meta: model = Release fields = ('id', 'arrivaldate', 'artist', 'title', 'year','company','genre','format', 'local', 'cpa', 'compilation', 'female', 'tracks', 'comments')
Add more fields to Release serializer.
Add more fields to Release serializer.
Python
mit
ThreeDRadio/playlists,ThreeDRadio/playlists,ThreeDRadio/playlists
from rest_framework import serializers from .models import Release, Track, Comment class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('id', 'comment') class TrackSerializer(serializers.ModelSerializer): - cdid = serializers.StringRelatedField( - read_only=True - ) class Meta: model = Track - fields = ('trackid', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'cdid') + fields = ('trackid', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'release') class ReleaseSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedIdentityField(view_name='release-tracks') comments = serializers.HyperlinkedIdentityField(view_name='release-comments') class Meta: model = Release - fields = ('id', 'arrivaldate', 'artist', 'title', 'year', 'local', 'cpa', 'compilation', 'female', 'tracks', 'comments') + fields = ('id', 'arrivaldate', 'artist', 'title', 'year','company','genre','format', 'local', 'cpa', 'compilation', 'female', 'tracks', 'comments')
Add more fields to Release serializer.
## Code Before: from rest_framework import serializers from .models import Release, Track, Comment class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('id', 'comment') class TrackSerializer(serializers.ModelSerializer): cdid = serializers.StringRelatedField( read_only=True ) class Meta: model = Track fields = ('trackid', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'cdid') class ReleaseSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedIdentityField(view_name='release-tracks') comments = serializers.HyperlinkedIdentityField(view_name='release-comments') class Meta: model = Release fields = ('id', 'arrivaldate', 'artist', 'title', 'year', 'local', 'cpa', 'compilation', 'female', 'tracks', 'comments') ## Instruction: Add more fields to Release serializer. ## Code After: from rest_framework import serializers from .models import Release, Track, Comment class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('id', 'comment') class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('trackid', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'release') class ReleaseSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedIdentityField(view_name='release-tracks') comments = serializers.HyperlinkedIdentityField(view_name='release-comments') class Meta: model = Release fields = ('id', 'arrivaldate', 'artist', 'title', 'year','company','genre','format', 'local', 'cpa', 'compilation', 'female', 'tracks', 'comments')
from rest_framework import serializers from .models import Release, Track, Comment class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('id', 'comment') class TrackSerializer(serializers.ModelSerializer): - cdid = serializers.StringRelatedField( - read_only=True - ) class Meta: model = Track - fields = ('trackid', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'cdid') ? ^^^^ + fields = ('trackid', 'tracknum', 'trackartist', 'tracktitle', 'tracklength', 'release') ? ^^^^^^^ class ReleaseSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedIdentityField(view_name='release-tracks') comments = serializers.HyperlinkedIdentityField(view_name='release-comments') class Meta: model = Release - fields = ('id', 'arrivaldate', 'artist', 'title', 'year', 'local', 'cpa', 'compilation', 'female', 'tracks', 'comments') + fields = ('id', 'arrivaldate', 'artist', 'title', 'year','company','genre','format', 'local', 'cpa', 'compilation', 'female', 'tracks', 'comments') ? +++++++++++++++++++++++++++
d5377e06ae059a9d478c3fe06652a353f1a8359c
address_book/address_book.py
address_book/address_book.py
from person import Person __all__ = ['AddressBook'] class AddressBook(object): def __init__(self): self.persons = [] self.groups = [] def add_person(self, person): self.persons.append(person) def add_group(self, group): self.groups.append(group) def __contains__(self, item): if isinstance(item, Person): return item in self.persons return False
from group import Group from person import Person __all__ = ['AddressBook'] class AddressBook(object): def __init__(self): self.persons = [] self.groups = [] def add_person(self, person): self.persons.append(person) def add_group(self, group): self.groups.append(group) def __contains__(self, item): if isinstance(item, Person): return item in self.persons if isinstance(item, Group): return item in self.groups return False
Make it possible to check if some group is in the AddressBook or not
Make it possible to check if some group is in the AddressBook or not
Python
mit
dizpers/python-address-book-assignment
+ from group import Group + from person import Person __all__ = ['AddressBook'] class AddressBook(object): def __init__(self): self.persons = [] self.groups = [] def add_person(self, person): self.persons.append(person) def add_group(self, group): self.groups.append(group) def __contains__(self, item): if isinstance(item, Person): return item in self.persons + if isinstance(item, Group): + return item in self.groups return False
Make it possible to check if some group is in the AddressBook or not
## Code Before: from person import Person __all__ = ['AddressBook'] class AddressBook(object): def __init__(self): self.persons = [] self.groups = [] def add_person(self, person): self.persons.append(person) def add_group(self, group): self.groups.append(group) def __contains__(self, item): if isinstance(item, Person): return item in self.persons return False ## Instruction: Make it possible to check if some group is in the AddressBook or not ## Code After: from group import Group from person import Person __all__ = ['AddressBook'] class AddressBook(object): def __init__(self): self.persons = [] self.groups = [] def add_person(self, person): self.persons.append(person) def add_group(self, group): self.groups.append(group) def __contains__(self, item): if isinstance(item, Person): return item in self.persons if isinstance(item, Group): return item in self.groups return False
+ from group import Group + from person import Person __all__ = ['AddressBook'] class AddressBook(object): def __init__(self): self.persons = [] self.groups = [] def add_person(self, person): self.persons.append(person) def add_group(self, group): self.groups.append(group) def __contains__(self, item): if isinstance(item, Person): return item in self.persons + if isinstance(item, Group): + return item in self.groups return False
ab506307b6b3fc2997a7afd38c02cae630dbf90b
addons/hr_holidays/migrations/8.0.1.5/pre-migration.py
addons/hr_holidays/migrations/8.0.1.5/pre-migration.py
from openerp.openupgrade import openupgrade @openupgrade.migrate() def migrate(cr, version): cr.execute( '''update hr_holidays set meeting_id=calendar_event.id from calendar_event where meeting_id=%s''' % ( openupgrade.get_legacy_name('crm_meeting_id'), ) )
from openerp.openupgrade import openupgrade @openupgrade.migrate() def migrate(cr, version): cr.execute( "ALTER TABLE hr_holidays DROP CONSTRAINT hr_holidays_meeting_id_fkey" ) cr.execute( '''update hr_holidays set meeting_id=calendar_event.id from calendar_event where meeting_id=%s''' % ( openupgrade.get_legacy_name('crm_meeting_id'), ) )
Remove hr_holidays_meeting_id_fkey constrain to avoid migration issues.
Remove hr_holidays_meeting_id_fkey constrain to avoid migration issues. - The constraint will be reset by the ORM later. - Not doing it may both slow the migration and abort it altogether.
Python
agpl-3.0
OpenUpgrade-dev/OpenUpgrade,kirca/OpenUpgrade,bwrsandman/OpenUpgrade,sebalix/OpenUpgrade,kirca/OpenUpgrade,hifly/OpenUpgrade,grap/OpenUpgrade,Endika/OpenUpgrade,bwrsandman/OpenUpgrade,damdam-s/OpenUpgrade,blaggacao/OpenUpgrade,mvaled/OpenUpgrade,blaggacao/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,OpenUpgrade/OpenUpgrade,pedrobaeza/OpenUpgrade,damdam-s/OpenUpgrade,pedrobaeza/OpenUpgrade,sebalix/OpenUpgrade,hifly/OpenUpgrade,mvaled/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,csrocha/OpenUpgrade,sebalix/OpenUpgrade,mvaled/OpenUpgrade,OpenUpgrade/OpenUpgrade,blaggacao/OpenUpgrade,0k/OpenUpgrade,blaggacao/OpenUpgrade,bwrsandman/OpenUpgrade,OpenUpgrade/OpenUpgrade,damdam-s/OpenUpgrade,damdam-s/OpenUpgrade,pedrobaeza/OpenUpgrade,OpenUpgrade/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,csrocha/OpenUpgrade,Endika/OpenUpgrade,Endika/OpenUpgrade,csrocha/OpenUpgrade,Endika/OpenUpgrade,Endika/OpenUpgrade,bwrsandman/OpenUpgrade,pedrobaeza/OpenUpgrade,damdam-s/OpenUpgrade,0k/OpenUpgrade,Endika/OpenUpgrade,blaggacao/OpenUpgrade,grap/OpenUpgrade,mvaled/OpenUpgrade,0k/OpenUpgrade,blaggacao/OpenUpgrade,kirca/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,kirca/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,grap/OpenUpgrade,grap/OpenUpgrade,OpenUpgrade/OpenUpgrade,mvaled/OpenUpgrade,pedrobaeza/OpenUpgrade,damdam-s/OpenUpgrade,pedrobaeza/OpenUpgrade,kirca/OpenUpgrade,sebalix/OpenUpgrade,grap/OpenUpgrade,kirca/OpenUpgrade,blaggacao/OpenUpgrade,bwrsandman/OpenUpgrade,sebalix/OpenUpgrade,grap/OpenUpgrade,sebalix/OpenUpgrade,hifly/OpenUpgrade,csrocha/OpenUpgrade,mvaled/OpenUpgrade,0k/OpenUpgrade,0k/OpenUpgrade,pedrobaeza/OpenUpgrade,bwrsandman/OpenUpgrade,csrocha/OpenUpgrade,OpenUpgrade/OpenUpgrade,csrocha/OpenUpgrade,hifly/OpenUpgrade,0k/OpenUpgrade,Endika/OpenUpgrade,mvaled/OpenUpgrade,OpenUpgrade/OpenUpgrade,hifly/OpenUpgrade,bwrsandman/OpenUpgrade,damdam-s/OpenUpgrade,hifly/OpenUpgrade,csrocha/OpenUpgrade,hifly/OpenUpgrade,kirca/OpenUpgrade,grap/OpenUpgrade,sebalix/OpenUpgrade
from openerp.openupgrade import openupgrade @openupgrade.migrate() def migrate(cr, version): + cr.execute( + "ALTER TABLE hr_holidays DROP CONSTRAINT hr_holidays_meeting_id_fkey" + ) cr.execute( '''update hr_holidays set meeting_id=calendar_event.id from calendar_event where meeting_id=%s''' % ( openupgrade.get_legacy_name('crm_meeting_id'), ) )
Remove hr_holidays_meeting_id_fkey constrain to avoid migration issues.
## Code Before: from openerp.openupgrade import openupgrade @openupgrade.migrate() def migrate(cr, version): cr.execute( '''update hr_holidays set meeting_id=calendar_event.id from calendar_event where meeting_id=%s''' % ( openupgrade.get_legacy_name('crm_meeting_id'), ) ) ## Instruction: Remove hr_holidays_meeting_id_fkey constrain to avoid migration issues. ## Code After: from openerp.openupgrade import openupgrade @openupgrade.migrate() def migrate(cr, version): cr.execute( "ALTER TABLE hr_holidays DROP CONSTRAINT hr_holidays_meeting_id_fkey" ) cr.execute( '''update hr_holidays set meeting_id=calendar_event.id from calendar_event where meeting_id=%s''' % ( openupgrade.get_legacy_name('crm_meeting_id'), ) )
from openerp.openupgrade import openupgrade @openupgrade.migrate() def migrate(cr, version): + cr.execute( + "ALTER TABLE hr_holidays DROP CONSTRAINT hr_holidays_meeting_id_fkey" + ) cr.execute( '''update hr_holidays set meeting_id=calendar_event.id from calendar_event where meeting_id=%s''' % ( openupgrade.get_legacy_name('crm_meeting_id'), ) )
0dc3e4ffe86f25697799b8092822a8d77a22493b
pi_mqtt_gpio/__init__.py
pi_mqtt_gpio/__init__.py
import sys print("FATAL ERROR: The file at pi_mqtt_gpio/__init__.py should be replaced us" "ing 'make schema' before packaging.") sys.exit(1)
import yaml CONFIG_SCHEMA = yaml.load(""" mqtt: type: dict required: yes schema: host: type: string empty: no required: no default: localhost port: type: integer min: 1 max: 65535 required: no default: 1883 user: type: string required: no default: "" password: type: string required: no default: "" client_id: type: string required: no default: "" topic_prefix: type: string required: no default: "" coerce: rstrip_slash protocol: type: string required: no empty: no coerce: tostring default: "3.1.1" allowed: - "3.1" - "3.1.1" status_topic: type: string required: no default: status status_payload_running: type: string required: no default: running status_payload_stopped: type: string required: no default: stopped status_payload_dead: type: string required: no default: dead gpio_modules: type: list required: yes schema: type: dict allow_unknown: yes schema: name: type: string required: yes empty: no module: type: string required: yes empty: no cleanup: type: boolean required: no default: yes digital_inputs: type: list required: no default: [] schema: type: dict schema: name: type: string required: yes empty: no module: type: string required: yes empty: no pin: type: integer required: yes min: 0 on_payload: type: string required: yes empty: no off_payload: type: string required: yes empty: no pullup: type: boolean required: no default: no pulldown: type: boolean required: no default: no retain: type: boolean required: no default: no digital_outputs: type: list required: no default: [] schema: type: dict schema: name: type: string required: yes module: type: string required: yes pin: type: integer required: yes min: 0 on_payload: type: string required: no empty: no off_payload: type: string required: no empty: no inverted: type: boolean required: no default: no initial: type: string required: no allowed: - high - low retain: type: boolean required: no default: no """)
Add schema to repo for now
Add schema to repo for now
Python
mit
flyte/pi-mqtt-gpio
- import sys + import yaml - print("FATAL ERROR: The file at pi_mqtt_gpio/__init__.py should be replaced us" - "ing 'make schema' before packaging.") - sys.exit(1) + CONFIG_SCHEMA = yaml.load(""" + mqtt: + type: dict + required: yes + schema: + host: + type: string + empty: no + required: no + default: localhost + port: + type: integer + min: 1 + max: 65535 + required: no + default: 1883 + user: + type: string + required: no + default: "" + password: + type: string + required: no + default: "" + client_id: + type: string + required: no + default: "" + topic_prefix: + type: string + required: no + default: "" + coerce: rstrip_slash + protocol: + type: string + required: no + empty: no + coerce: tostring + default: "3.1.1" + allowed: + - "3.1" + - "3.1.1" + status_topic: + type: string + required: no + default: status + status_payload_running: + type: string + required: no + default: running + status_payload_stopped: + type: string + required: no + default: stopped + status_payload_dead: + type: string + required: no + default: dead + + gpio_modules: + type: list + required: yes + schema: + type: dict + allow_unknown: yes + schema: + name: + type: string + required: yes + empty: no + module: + type: string + required: yes + empty: no + cleanup: + type: boolean + required: no + default: yes + + digital_inputs: + type: list + required: no + default: [] + schema: + type: dict + schema: + name: + type: string + required: yes + empty: no + module: + type: string + required: yes + empty: no + pin: + type: integer + required: yes + min: 0 + on_payload: + type: string + required: yes + empty: no + off_payload: + type: string + required: yes + empty: no + pullup: + type: boolean + required: no + default: no + pulldown: + type: boolean + required: no + default: no + retain: + type: boolean + required: no + default: no + + digital_outputs: + type: list + required: no + default: [] + schema: + type: dict + schema: + name: + type: string + required: yes + module: + type: string + required: yes + pin: + type: integer + required: yes + min: 0 + on_payload: + type: string + required: no + empty: no + off_payload: + type: string + required: no + empty: no + inverted: + type: boolean + required: no + default: no + initial: + type: string + required: no + allowed: + - high + - low + retain: + type: boolean + required: no + default: no + + + """) +
Add schema to repo for now
## Code Before: import sys print("FATAL ERROR: The file at pi_mqtt_gpio/__init__.py should be replaced us" "ing 'make schema' before packaging.") sys.exit(1) ## Instruction: Add schema to repo for now ## Code After: import yaml CONFIG_SCHEMA = yaml.load(""" mqtt: type: dict required: yes schema: host: type: string empty: no required: no default: localhost port: type: integer min: 1 max: 65535 required: no default: 1883 user: type: string required: no default: "" password: type: string required: no default: "" client_id: type: string required: no default: "" topic_prefix: type: string required: no default: "" coerce: rstrip_slash protocol: type: string required: no empty: no coerce: tostring default: "3.1.1" allowed: - "3.1" - "3.1.1" status_topic: type: string required: no default: status status_payload_running: type: string required: no default: running status_payload_stopped: type: string required: no default: stopped status_payload_dead: type: string required: no default: dead gpio_modules: type: list required: yes schema: type: dict allow_unknown: yes schema: name: type: string required: yes empty: no module: type: string required: yes empty: no cleanup: type: boolean required: no default: yes digital_inputs: type: list required: no default: [] schema: type: dict schema: name: type: string required: yes empty: no module: type: string required: yes empty: no pin: type: integer required: yes min: 0 on_payload: type: string required: yes empty: no off_payload: type: string required: yes empty: no pullup: type: boolean required: no default: no pulldown: type: boolean required: no default: no retain: type: boolean required: no default: no digital_outputs: type: list required: no default: [] schema: type: dict schema: name: type: string required: yes module: type: string required: yes pin: type: integer required: yes min: 0 on_payload: type: string required: no empty: no off_payload: type: string required: no empty: no inverted: type: boolean required: no default: no initial: type: string required: no allowed: - high - low retain: type: boolean required: no default: no """)
- import sys ? - ^ + import yaml ? ^^^ - print("FATAL ERROR: The file at pi_mqtt_gpio/__init__.py should be replaced us" - "ing 'make schema' before packaging.") - sys.exit(1) + + CONFIG_SCHEMA = yaml.load(""" + mqtt: + type: dict + required: yes + schema: + host: + type: string + empty: no + required: no + default: localhost + port: + type: integer + min: 1 + max: 65535 + required: no + default: 1883 + user: + type: string + required: no + default: "" + password: + type: string + required: no + default: "" + client_id: + type: string + required: no + default: "" + topic_prefix: + type: string + required: no + default: "" + coerce: rstrip_slash + protocol: + type: string + required: no + empty: no + coerce: tostring + default: "3.1.1" + allowed: + - "3.1" + - "3.1.1" + status_topic: + type: string + required: no + default: status + status_payload_running: + type: string + required: no + default: running + status_payload_stopped: + type: string + required: no + default: stopped + status_payload_dead: + type: string + required: no + default: dead + + gpio_modules: + type: list + required: yes + schema: + type: dict + allow_unknown: yes + schema: + name: + type: string + required: yes + empty: no + module: + type: string + required: yes + empty: no + cleanup: + type: boolean + required: no + default: yes + + digital_inputs: + type: list + required: no + default: [] + schema: + type: dict + schema: + name: + type: string + required: yes + empty: no + module: + type: string + required: yes + empty: no + pin: + type: integer + required: yes + min: 0 + on_payload: + type: string + required: yes + empty: no + off_payload: + type: string + required: yes + empty: no + pullup: + type: boolean + required: no + default: no + pulldown: + type: boolean + required: no + default: no + retain: + type: boolean + required: no + default: no + + digital_outputs: + type: list + required: no + default: [] + schema: + type: dict + schema: + name: + type: string + required: yes + module: + type: string + required: yes + pin: + type: integer + required: yes + min: 0 + on_payload: + type: string + required: no + empty: no + off_payload: + type: string + required: no + empty: no + inverted: + type: boolean + required: no + default: no + initial: + type: string + required: no + allowed: + - high + - low + retain: + type: boolean + required: no + default: no + + + """)
4a827bfff24758677e9c1d9d3b186fc14f23e0bb
lib/oeqa/runtime/cases/parselogs_rpi.py
lib/oeqa/runtime/cases/parselogs_rpi.py
from oeqa.runtime.cases.parselogs import * rpi_errors = [ 'bcmgenet fd580000.genet: failed to get enet-eee clock', 'bcmgenet fd580000.genet: failed to get enet-wol clock', 'bcmgenet fd580000.genet: failed to get enet clock', 'bcmgenet fd580000.ethernet: failed to get enet-eee clock', 'bcmgenet fd580000.ethernet: failed to get enet-wol clock', 'bcmgenet fd580000.ethernet: failed to get enet clock', ] ignore_errors['raspberrypi4'] = rpi_errors + common_errors ignore_errors['raspberrypi4-64'] = rpi_errors + common_errors ignore_errors['raspberrypi3'] = rpi_errors + common_errors ignore_errors['raspberrypi3-64'] = rpi_errors + common_errors class ParseLogsTestRpi(ParseLogsTest): pass
from oeqa.runtime.cases.parselogs import * rpi_errors = [ ] ignore_errors['raspberrypi4'] = rpi_errors + common_errors ignore_errors['raspberrypi4-64'] = rpi_errors + common_errors ignore_errors['raspberrypi3'] = rpi_errors + common_errors ignore_errors['raspberrypi3-64'] = rpi_errors + common_errors class ParseLogsTestRpi(ParseLogsTest): pass
Update the error regexps to 5.10 kernel
parselogs: Update the error regexps to 5.10 kernel The old messages are no longer necessary Signed-off-by: Khem Raj <729d64b6f67515e258459a5f6d20ec88b2caf8df@gmail.com>
Python
mit
agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi
from oeqa.runtime.cases.parselogs import * rpi_errors = [ - 'bcmgenet fd580000.genet: failed to get enet-eee clock', - 'bcmgenet fd580000.genet: failed to get enet-wol clock', - 'bcmgenet fd580000.genet: failed to get enet clock', - 'bcmgenet fd580000.ethernet: failed to get enet-eee clock', - 'bcmgenet fd580000.ethernet: failed to get enet-wol clock', - 'bcmgenet fd580000.ethernet: failed to get enet clock', ] ignore_errors['raspberrypi4'] = rpi_errors + common_errors ignore_errors['raspberrypi4-64'] = rpi_errors + common_errors ignore_errors['raspberrypi3'] = rpi_errors + common_errors ignore_errors['raspberrypi3-64'] = rpi_errors + common_errors class ParseLogsTestRpi(ParseLogsTest): pass
Update the error regexps to 5.10 kernel
## Code Before: from oeqa.runtime.cases.parselogs import * rpi_errors = [ 'bcmgenet fd580000.genet: failed to get enet-eee clock', 'bcmgenet fd580000.genet: failed to get enet-wol clock', 'bcmgenet fd580000.genet: failed to get enet clock', 'bcmgenet fd580000.ethernet: failed to get enet-eee clock', 'bcmgenet fd580000.ethernet: failed to get enet-wol clock', 'bcmgenet fd580000.ethernet: failed to get enet clock', ] ignore_errors['raspberrypi4'] = rpi_errors + common_errors ignore_errors['raspberrypi4-64'] = rpi_errors + common_errors ignore_errors['raspberrypi3'] = rpi_errors + common_errors ignore_errors['raspberrypi3-64'] = rpi_errors + common_errors class ParseLogsTestRpi(ParseLogsTest): pass ## Instruction: Update the error regexps to 5.10 kernel ## Code After: from oeqa.runtime.cases.parselogs import * rpi_errors = [ ] ignore_errors['raspberrypi4'] = rpi_errors + common_errors ignore_errors['raspberrypi4-64'] = rpi_errors + common_errors ignore_errors['raspberrypi3'] = rpi_errors + common_errors ignore_errors['raspberrypi3-64'] = rpi_errors + common_errors class ParseLogsTestRpi(ParseLogsTest): pass
from oeqa.runtime.cases.parselogs import * rpi_errors = [ - 'bcmgenet fd580000.genet: failed to get enet-eee clock', - 'bcmgenet fd580000.genet: failed to get enet-wol clock', - 'bcmgenet fd580000.genet: failed to get enet clock', - 'bcmgenet fd580000.ethernet: failed to get enet-eee clock', - 'bcmgenet fd580000.ethernet: failed to get enet-wol clock', - 'bcmgenet fd580000.ethernet: failed to get enet clock', ] ignore_errors['raspberrypi4'] = rpi_errors + common_errors ignore_errors['raspberrypi4-64'] = rpi_errors + common_errors ignore_errors['raspberrypi3'] = rpi_errors + common_errors ignore_errors['raspberrypi3-64'] = rpi_errors + common_errors class ParseLogsTestRpi(ParseLogsTest): pass
cdaf1c4a9a99a7f089470e8ceaaa226124a42cf0
digdag-cli/src/main/resources/digdag/cli/tasks/__init__.py
digdag-cli/src/main/resources/digdag/cli/tasks/__init__.py
class MyWorkflow(object): def __init__(self): pass def step3(self, session_time = None): print "Step3 of session %s" % session_time
class MyWorkflow(object): def __init__(self): pass def step3(self, session_time = None): print("Step3 of session {0}".format(session_time))
Fix an example of python task
Fix an example of python task The original python print method doesn't work on python3. print(format) method works on python2 and python 3.
Python
apache-2.0
treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,KimuraTakaumi/digdag,KimuraTakaumi/digdag,treasure-data/digdag,KimuraTakaumi/digdag,treasure-data/digdag,KimuraTakaumi/digdag,KimuraTakaumi/digdag,KimuraTakaumi/digdag
class MyWorkflow(object): def __init__(self): pass def step3(self, session_time = None): - print "Step3 of session %s" % session_time + print("Step3 of session {0}".format(session_time))
Fix an example of python task
## Code Before: class MyWorkflow(object): def __init__(self): pass def step3(self, session_time = None): print "Step3 of session %s" % session_time ## Instruction: Fix an example of python task ## Code After: class MyWorkflow(object): def __init__(self): pass def step3(self, session_time = None): print("Step3 of session {0}".format(session_time))
class MyWorkflow(object): def __init__(self): pass def step3(self, session_time = None): - print "Step3 of session %s" % session_time ? ^ ^^ ^^^ + print("Step3 of session {0}".format(session_time)) ? ^ ^^^ ^^^^^^^^ ++
6ebb2b021594633a66f2ff90121d4a39eec96cc8
test_project/test_project/urls.py
test_project/test_project/urls.py
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', url(r'^', include('test_app.urls')), )
from django.conf.urls import patterns, include, url from django.http import HttpResponseNotFound # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', url(r'^', include('test_app.urls')), ) def custom404(request): return HttpResponseNotFound(status=404) handler404 = 'test_project.urls.custom404'
Use a custom 404 handler to avoid using the default template loader.
Use a custom 404 handler to avoid using the default template loader.
Python
mit
liberation/django-elasticsearch,leotsem/django-elasticsearch,sadnoodles/django-elasticsearch,alsur/django-elasticsearch
from django.conf.urls import patterns, include, url + from django.http import HttpResponseNotFound # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', url(r'^', include('test_app.urls')), ) + def custom404(request): + return HttpResponseNotFound(status=404) + + handler404 = 'test_project.urls.custom404' +
Use a custom 404 handler to avoid using the default template loader.
## Code Before: from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', url(r'^', include('test_app.urls')), ) ## Instruction: Use a custom 404 handler to avoid using the default template loader. ## Code After: from django.conf.urls import patterns, include, url from django.http import HttpResponseNotFound # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', url(r'^', include('test_app.urls')), ) def custom404(request): return HttpResponseNotFound(status=404) handler404 = 'test_project.urls.custom404'
from django.conf.urls import patterns, include, url + from django.http import HttpResponseNotFound # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', url(r'^', include('test_app.urls')), ) + + def custom404(request): + return HttpResponseNotFound(status=404) + + handler404 = 'test_project.urls.custom404'
88d15544556cdfc9fe1f2e000f67846a8cd1bb25
stginga/__init__.py
stginga/__init__.py
# Set up the version from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed __version__ = 'unknown' # UI from .plugin_info import * # noqa
# Packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # noqa # ---------------------------------------------------------------------------- # UI from .plugin_info import * # noqa
Remove duplicate version and restore test runner
BUG: Remove duplicate version and restore test runner
Python
bsd-3-clause
pllim/stginga,spacetelescope/stginga
+ # Packages may add whatever they like to this file, but + # should keep this content at the top. + # ---------------------------------------------------------------------------- + from ._astropy_init import * # noqa + # ---------------------------------------------------------------------------- - # Set up the version - from pkg_resources import get_distribution, DistributionNotFound - - try: - __version__ = get_distribution(__name__).version - except DistributionNotFound: - # package is not installed - __version__ = 'unknown' # UI from .plugin_info import * # noqa
Remove duplicate version and restore test runner
## Code Before: # Set up the version from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed __version__ = 'unknown' # UI from .plugin_info import * # noqa ## Instruction: Remove duplicate version and restore test runner ## Code After: # Packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # noqa # ---------------------------------------------------------------------------- # UI from .plugin_info import * # noqa
+ # Packages may add whatever they like to this file, but + # should keep this content at the top. + # ---------------------------------------------------------------------------- + from ._astropy_init import * # noqa + # ---------------------------------------------------------------------------- - # Set up the version - from pkg_resources import get_distribution, DistributionNotFound - - try: - __version__ = get_distribution(__name__).version - except DistributionNotFound: - # package is not installed - __version__ = 'unknown' # UI from .plugin_info import * # noqa
6db55e993cb4a93aeede2cd9aff244e2c517fa06
setup.py
setup.py
from distutils.core import setup setup( name='firebase-token-generator', version='1.2', author='Greg Soltis', author_email='greg@firebase.com', py_modules=['firebase_token_generator'], license='LICENSE', url='https://github.com/firebase/PyFirebaseTokenGenerator', description='A utility to generate signed Firebase Authentication Tokens', long_description=open('README.md').read() )
from distutils.core import setup setup( name='firebase-token-generator', version='1.2', author='Greg Soltis', author_email='greg@firebase.com', py_modules=['firebase_token_generator'], license='LICENSE', url='https://github.com/firebase/firebase-token-generator-python', description='A utility to generate signed Firebase Authentication Tokens', long_description=open('README.md').read() )
Fix repo URL after rename
Fix repo URL after rename
Python
mit
googlearchive/firebase-token-generator-python
from distutils.core import setup setup( name='firebase-token-generator', version='1.2', author='Greg Soltis', author_email='greg@firebase.com', py_modules=['firebase_token_generator'], license='LICENSE', - url='https://github.com/firebase/PyFirebaseTokenGenerator', + url='https://github.com/firebase/firebase-token-generator-python', description='A utility to generate signed Firebase Authentication Tokens', long_description=open('README.md').read() )
Fix repo URL after rename
## Code Before: from distutils.core import setup setup( name='firebase-token-generator', version='1.2', author='Greg Soltis', author_email='greg@firebase.com', py_modules=['firebase_token_generator'], license='LICENSE', url='https://github.com/firebase/PyFirebaseTokenGenerator', description='A utility to generate signed Firebase Authentication Tokens', long_description=open('README.md').read() ) ## Instruction: Fix repo URL after rename ## Code After: from distutils.core import setup setup( name='firebase-token-generator', version='1.2', author='Greg Soltis', author_email='greg@firebase.com', py_modules=['firebase_token_generator'], license='LICENSE', url='https://github.com/firebase/firebase-token-generator-python', description='A utility to generate signed Firebase Authentication Tokens', long_description=open('README.md').read() )
from distutils.core import setup setup( name='firebase-token-generator', version='1.2', author='Greg Soltis', author_email='greg@firebase.com', py_modules=['firebase_token_generator'], license='LICENSE', - url='https://github.com/firebase/PyFirebaseTokenGenerator', ? ^^^ ^ ^ + url='https://github.com/firebase/firebase-token-generator-python', ? ^ ^^ ^^ +++++++ description='A utility to generate signed Firebase Authentication Tokens', long_description=open('README.md').read() )
643e04ec09612d6f36dcd98dba44e00011674353
fito/data_store/dict_ds.py
fito/data_store/dict_ds.py
from fito.data_store.base import BaseDataStore class DictDataStore(BaseDataStore): def __init__(self, *args, **kwargs): super(DictDataStore, self).__init__(*args, **kwargs) self.data = {} def iteritems(self): return self.data.iteritems() def save(self, spec, object): self.data[spec] = object def _get(self, spec): if spec not in self.data: raise KeyError("Spec not found: {}".format(spec)) return self.data.get(spec) def iterkeys(self): return self.data.iterkeys()
from fito.data_store.base import BaseDataStore class DictDataStore(BaseDataStore): def __init__(self, *args, **kwargs): super(DictDataStore, self).__init__(*args, **kwargs) self.data = {} def iteritems(self): return self.data.iteritems() def save(self, spec, object): self.data[spec] = object def _get(self, spec): if spec not in self.data: raise KeyError("Spec not found: {}".format(spec)) return self.data.get(spec) def iterkeys(self): return self.data.iterkeys() def clean(self): self.data = {}
Clean method for dict ds
Clean method for dict ds
Python
mit
elsonidoq/fito
from fito.data_store.base import BaseDataStore class DictDataStore(BaseDataStore): def __init__(self, *args, **kwargs): super(DictDataStore, self).__init__(*args, **kwargs) self.data = {} def iteritems(self): return self.data.iteritems() def save(self, spec, object): self.data[spec] = object def _get(self, spec): if spec not in self.data: raise KeyError("Spec not found: {}".format(spec)) return self.data.get(spec) def iterkeys(self): return self.data.iterkeys() + def clean(self): + self.data = {} + + +
Clean method for dict ds
## Code Before: from fito.data_store.base import BaseDataStore class DictDataStore(BaseDataStore): def __init__(self, *args, **kwargs): super(DictDataStore, self).__init__(*args, **kwargs) self.data = {} def iteritems(self): return self.data.iteritems() def save(self, spec, object): self.data[spec] = object def _get(self, spec): if spec not in self.data: raise KeyError("Spec not found: {}".format(spec)) return self.data.get(spec) def iterkeys(self): return self.data.iterkeys() ## Instruction: Clean method for dict ds ## Code After: from fito.data_store.base import BaseDataStore class DictDataStore(BaseDataStore): def __init__(self, *args, **kwargs): super(DictDataStore, self).__init__(*args, **kwargs) self.data = {} def iteritems(self): return self.data.iteritems() def save(self, spec, object): self.data[spec] = object def _get(self, spec): if spec not in self.data: raise KeyError("Spec not found: {}".format(spec)) return self.data.get(spec) def iterkeys(self): return self.data.iterkeys() def clean(self): self.data = {}
from fito.data_store.base import BaseDataStore class DictDataStore(BaseDataStore): def __init__(self, *args, **kwargs): super(DictDataStore, self).__init__(*args, **kwargs) self.data = {} def iteritems(self): return self.data.iteritems() def save(self, spec, object): self.data[spec] = object def _get(self, spec): if spec not in self.data: raise KeyError("Spec not found: {}".format(spec)) return self.data.get(spec) def iterkeys(self): return self.data.iterkeys() + + def clean(self): + self.data = {} + +
045192dd0a69dfe581075e76bbb7ca4676d321b8
test_project/urls.py
test_project/urls.py
from django.conf.urls import url from django.contrib import admin from django.http import HttpResponse urlpatterns = [ url(r'^$', lambda request, *args, **kwargs: HttpResponse()), url(r'^admin/', admin.site.urls), ]
from django.urls import re_path from django.contrib import admin from django.http import HttpResponse urlpatterns = [ re_path(r'^$', lambda request, *args, **kwargs: HttpResponse()), re_path(r'^admin/', admin.site.urls), ]
Replace url() with re_path() available in newer Django
Replace url() with re_path() available in newer Django
Python
bsd-3-clause
ecometrica/django-vinaigrette
- from django.conf.urls import url + from django.urls import re_path from django.contrib import admin from django.http import HttpResponse urlpatterns = [ - url(r'^$', lambda request, *args, **kwargs: HttpResponse()), + re_path(r'^$', lambda request, *args, **kwargs: HttpResponse()), - url(r'^admin/', admin.site.urls), + re_path(r'^admin/', admin.site.urls), ]
Replace url() with re_path() available in newer Django
## Code Before: from django.conf.urls import url from django.contrib import admin from django.http import HttpResponse urlpatterns = [ url(r'^$', lambda request, *args, **kwargs: HttpResponse()), url(r'^admin/', admin.site.urls), ] ## Instruction: Replace url() with re_path() available in newer Django ## Code After: from django.urls import re_path from django.contrib import admin from django.http import HttpResponse urlpatterns = [ re_path(r'^$', lambda request, *args, **kwargs: HttpResponse()), re_path(r'^admin/', admin.site.urls), ]
- from django.conf.urls import url ? ----- - ^ + from django.urls import re_path ? ^^^^^^ from django.contrib import admin from django.http import HttpResponse urlpatterns = [ - url(r'^$', lambda request, *args, **kwargs: HttpResponse()), ? - ^ + re_path(r'^$', lambda request, *args, **kwargs: HttpResponse()), ? ^^^^^^ - url(r'^admin/', admin.site.urls), ? - ^ + re_path(r'^admin/', admin.site.urls), ? ^^^^^^ ]
09a6e2528f062581c90ed3f3225f19b36f0ac0f9
eve_api/forms.py
eve_api/forms.py
import re from django import forms from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation class EveAPIForm(forms.Form): """ EVE API input form """ user_id = forms.IntegerField(label=u'User ID') api_key = forms.CharField(label=u'API Key', max_length=64) description = forms.CharField(max_length=100, required=False) def clean_api_key(self): if not len(self.cleaned_data['api_key']) == 64: raise forms.ValidationError("Provided API Key is not 64 characters long.") if re.search(r'[^\.a-zA-Z0-9]', self.cleaned_data['api_key']): raise forms.ValidationError("Provided API Key has invalid characters.") def clean_user_id(self): if not 'user_id' in self.cleaned_data or self.cleaned_data['user_id'] == '': raise forms.ValidationError("Please provide a valid User ID") try: eaccount = EVEAccount.objects.get(api_user_id=self.cleaned_data['user_id']) except EVEAccount.DoesNotExist: return self.cleaned_data else: raise forms.ValidationError("This API User ID is already registered")
import re from django import forms from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation class EveAPIForm(forms.Form): """ EVE API input form """ user_id = forms.IntegerField(label=u'User ID') api_key = forms.CharField(label=u'API Key', max_length=64) description = forms.CharField(max_length=100, required=False) def clean_api_key(self): if not len(self.cleaned_data['api_key']) == 64: raise forms.ValidationError("Provided API Key is not 64 characters long.") if re.search(r'[^\.a-zA-Z0-9]', self.cleaned_data['api_key']): raise forms.ValidationError("Provided API Key has invalid characters.") return self.cleaned_data['api_key'] def clean_user_id(self): if not 'user_id' in self.cleaned_data or self.cleaned_data['user_id'] == '': raise forms.ValidationError("Please provide a valid User ID") try: eaccount = EVEAccount.objects.get(api_user_id=self.cleaned_data['user_id']) except EVEAccount.DoesNotExist: pass else: raise forms.ValidationError("This API User ID is already registered") return self.cleaned_data['user_id']
Fix the validation data on the EVEAPIForm
Fix the validation data on the EVEAPIForm
Python
bsd-3-clause
nikdoof/test-auth
import re from django import forms from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation class EveAPIForm(forms.Form): """ EVE API input form """ user_id = forms.IntegerField(label=u'User ID') api_key = forms.CharField(label=u'API Key', max_length=64) description = forms.CharField(max_length=100, required=False) def clean_api_key(self): if not len(self.cleaned_data['api_key']) == 64: raise forms.ValidationError("Provided API Key is not 64 characters long.") if re.search(r'[^\.a-zA-Z0-9]', self.cleaned_data['api_key']): raise forms.ValidationError("Provided API Key has invalid characters.") + return self.cleaned_data['api_key'] + def clean_user_id(self): if not 'user_id' in self.cleaned_data or self.cleaned_data['user_id'] == '': raise forms.ValidationError("Please provide a valid User ID") try: eaccount = EVEAccount.objects.get(api_user_id=self.cleaned_data['user_id']) except EVEAccount.DoesNotExist: - return self.cleaned_data + pass else: raise forms.ValidationError("This API User ID is already registered") + return self.cleaned_data['user_id']
Fix the validation data on the EVEAPIForm
## Code Before: import re from django import forms from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation class EveAPIForm(forms.Form): """ EVE API input form """ user_id = forms.IntegerField(label=u'User ID') api_key = forms.CharField(label=u'API Key', max_length=64) description = forms.CharField(max_length=100, required=False) def clean_api_key(self): if not len(self.cleaned_data['api_key']) == 64: raise forms.ValidationError("Provided API Key is not 64 characters long.") if re.search(r'[^\.a-zA-Z0-9]', self.cleaned_data['api_key']): raise forms.ValidationError("Provided API Key has invalid characters.") def clean_user_id(self): if not 'user_id' in self.cleaned_data or self.cleaned_data['user_id'] == '': raise forms.ValidationError("Please provide a valid User ID") try: eaccount = EVEAccount.objects.get(api_user_id=self.cleaned_data['user_id']) except EVEAccount.DoesNotExist: return self.cleaned_data else: raise forms.ValidationError("This API User ID is already registered") ## Instruction: Fix the validation data on the EVEAPIForm ## Code After: import re from django import forms from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation class EveAPIForm(forms.Form): """ EVE API input form """ user_id = forms.IntegerField(label=u'User ID') api_key = forms.CharField(label=u'API Key', max_length=64) description = forms.CharField(max_length=100, required=False) def clean_api_key(self): if not len(self.cleaned_data['api_key']) == 64: raise forms.ValidationError("Provided API Key is not 64 characters long.") if re.search(r'[^\.a-zA-Z0-9]', self.cleaned_data['api_key']): raise forms.ValidationError("Provided API Key has invalid characters.") return self.cleaned_data['api_key'] def clean_user_id(self): if not 'user_id' in self.cleaned_data or self.cleaned_data['user_id'] == '': raise forms.ValidationError("Please provide a valid User ID") try: eaccount = EVEAccount.objects.get(api_user_id=self.cleaned_data['user_id']) except EVEAccount.DoesNotExist: pass else: raise forms.ValidationError("This API User ID is already registered") return self.cleaned_data['user_id']
import re from django import forms from eve_api.models import EVEAccount, EVEPlayerCharacter, EVEPlayerCorporation class EveAPIForm(forms.Form): """ EVE API input form """ user_id = forms.IntegerField(label=u'User ID') api_key = forms.CharField(label=u'API Key', max_length=64) description = forms.CharField(max_length=100, required=False) def clean_api_key(self): if not len(self.cleaned_data['api_key']) == 64: raise forms.ValidationError("Provided API Key is not 64 characters long.") if re.search(r'[^\.a-zA-Z0-9]', self.cleaned_data['api_key']): raise forms.ValidationError("Provided API Key has invalid characters.") + return self.cleaned_data['api_key'] + def clean_user_id(self): if not 'user_id' in self.cleaned_data or self.cleaned_data['user_id'] == '': raise forms.ValidationError("Please provide a valid User ID") try: eaccount = EVEAccount.objects.get(api_user_id=self.cleaned_data['user_id']) except EVEAccount.DoesNotExist: - return self.cleaned_data + pass else: raise forms.ValidationError("This API User ID is already registered") + return self.cleaned_data['user_id']
e4c5ff6901fe7652c7f76f67189058de76406406
casepro/cases/forms.py
casepro/cases/forms.py
from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from casepro.msgs.models import Label from .models import Partner class PartnerUpdateForm(forms.ModelForm): labels = forms.ModelMultipleChoiceField(label=_("Can Access"), queryset=Label.objects.none(), widget=forms.CheckboxSelectMultiple(), required=False) def __init__(self, *args, **kwargs): org = kwargs.pop('org') super(PartnerUpdateForm, self).__init__(*args, **kwargs) self.fields['primary_contact'].queryset = kwargs['instance'].get_users() self.fields['labels'].queryset = Label.get_all(org).order_by('name') class Meta: model = Partner fields = ('name', 'description', 'primary_contact', 'logo', 'is_restricted', 'labels') class PartnerCreateForm(forms.ModelForm): labels = forms.ModelMultipleChoiceField(label=_("Can Access"), queryset=Label.objects.none(), widget=forms.CheckboxSelectMultiple(), required=False) def __init__(self, *args, **kwargs): org = kwargs.pop('org') super(PartnerCreateForm, self).__init__(*args, **kwargs) self.fields['labels'].queryset = Label.get_all(org).order_by('name') class Meta: model = Partner fields = ('name', 'description', 'logo', 'is_restricted', 'labels')
from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from casepro.msgs.models import Label from .models import Partner class BasePartnerForm(forms.ModelForm): description = forms.CharField(label=_("Description"), max_length=255, required=False, widget=forms.Textarea) labels = forms.ModelMultipleChoiceField(label=_("Can Access"), queryset=Label.objects.none(), widget=forms.CheckboxSelectMultiple(), required=False) def __init__(self, *args, **kwargs): org = kwargs.pop('org') super(BasePartnerForm, self).__init__(*args, **kwargs) self.fields['labels'].queryset = Label.get_all(org).order_by('name') class PartnerUpdateForm(BasePartnerForm): def __init__(self, *args, **kwargs): super(PartnerUpdateForm, self).__init__(*args, **kwargs) self.fields['primary_contact'].queryset = kwargs['instance'].get_users() class Meta: model = Partner fields = ('name', 'description', 'primary_contact', 'logo', 'is_restricted', 'labels') class PartnerCreateForm(BasePartnerForm): def __init__(self, *args, **kwargs): super(PartnerCreateForm, self).__init__(*args, **kwargs) class Meta: model = Partner fields = ('name', 'description', 'logo', 'is_restricted', 'labels')
Tweak partner form to use textarea for description
Tweak partner form to use textarea for description
Python
bsd-3-clause
praekelt/casepro,xkmato/casepro,rapidpro/casepro,praekelt/casepro,rapidpro/casepro,rapidpro/casepro,praekelt/casepro,xkmato/casepro
from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from casepro.msgs.models import Label from .models import Partner - class PartnerUpdateForm(forms.ModelForm): + class BasePartnerForm(forms.ModelForm): + description = forms.CharField(label=_("Description"), max_length=255, required=False, widget=forms.Textarea) + labels = forms.ModelMultipleChoiceField(label=_("Can Access"), queryset=Label.objects.none(), widget=forms.CheckboxSelectMultiple(), required=False) def __init__(self, *args, **kwargs): org = kwargs.pop('org') + + super(BasePartnerForm, self).__init__(*args, **kwargs) + + self.fields['labels'].queryset = Label.get_all(org).order_by('name') + + + class PartnerUpdateForm(BasePartnerForm): + def __init__(self, *args, **kwargs): super(PartnerUpdateForm, self).__init__(*args, **kwargs) self.fields['primary_contact'].queryset = kwargs['instance'].get_users() - self.fields['labels'].queryset = Label.get_all(org).order_by('name') class Meta: model = Partner fields = ('name', 'description', 'primary_contact', 'logo', 'is_restricted', 'labels') - class PartnerCreateForm(forms.ModelForm): + class PartnerCreateForm(BasePartnerForm): - labels = forms.ModelMultipleChoiceField(label=_("Can Access"), - queryset=Label.objects.none(), - widget=forms.CheckboxSelectMultiple(), - required=False) - def __init__(self, *args, **kwargs): - org = kwargs.pop('org') super(PartnerCreateForm, self).__init__(*args, **kwargs) - - self.fields['labels'].queryset = Label.get_all(org).order_by('name') class Meta: model = Partner fields = ('name', 'description', 'logo', 'is_restricted', 'labels')
Tweak partner form to use textarea for description
## Code Before: from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from casepro.msgs.models import Label from .models import Partner class PartnerUpdateForm(forms.ModelForm): labels = forms.ModelMultipleChoiceField(label=_("Can Access"), queryset=Label.objects.none(), widget=forms.CheckboxSelectMultiple(), required=False) def __init__(self, *args, **kwargs): org = kwargs.pop('org') super(PartnerUpdateForm, self).__init__(*args, **kwargs) self.fields['primary_contact'].queryset = kwargs['instance'].get_users() self.fields['labels'].queryset = Label.get_all(org).order_by('name') class Meta: model = Partner fields = ('name', 'description', 'primary_contact', 'logo', 'is_restricted', 'labels') class PartnerCreateForm(forms.ModelForm): labels = forms.ModelMultipleChoiceField(label=_("Can Access"), queryset=Label.objects.none(), widget=forms.CheckboxSelectMultiple(), required=False) def __init__(self, *args, **kwargs): org = kwargs.pop('org') super(PartnerCreateForm, self).__init__(*args, **kwargs) self.fields['labels'].queryset = Label.get_all(org).order_by('name') class Meta: model = Partner fields = ('name', 'description', 'logo', 'is_restricted', 'labels') ## Instruction: Tweak partner form to use textarea for description ## Code After: from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from casepro.msgs.models import Label from .models import Partner class BasePartnerForm(forms.ModelForm): description = forms.CharField(label=_("Description"), max_length=255, required=False, widget=forms.Textarea) labels = forms.ModelMultipleChoiceField(label=_("Can Access"), queryset=Label.objects.none(), widget=forms.CheckboxSelectMultiple(), required=False) def __init__(self, *args, **kwargs): org = kwargs.pop('org') super(BasePartnerForm, self).__init__(*args, **kwargs) self.fields['labels'].queryset = Label.get_all(org).order_by('name') class PartnerUpdateForm(BasePartnerForm): def __init__(self, *args, **kwargs): super(PartnerUpdateForm, self).__init__(*args, **kwargs) self.fields['primary_contact'].queryset = kwargs['instance'].get_users() class Meta: model = Partner fields = ('name', 'description', 'primary_contact', 'logo', 'is_restricted', 'labels') class PartnerCreateForm(BasePartnerForm): def __init__(self, *args, **kwargs): super(PartnerCreateForm, self).__init__(*args, **kwargs) class Meta: model = Partner fields = ('name', 'description', 'logo', 'is_restricted', 'labels')
from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from casepro.msgs.models import Label from .models import Partner - class PartnerUpdateForm(forms.ModelForm): ? ------ + class BasePartnerForm(forms.ModelForm): ? ++++ + description = forms.CharField(label=_("Description"), max_length=255, required=False, widget=forms.Textarea) + labels = forms.ModelMultipleChoiceField(label=_("Can Access"), queryset=Label.objects.none(), widget=forms.CheckboxSelectMultiple(), required=False) def __init__(self, *args, **kwargs): org = kwargs.pop('org') + + super(BasePartnerForm, self).__init__(*args, **kwargs) + + self.fields['labels'].queryset = Label.get_all(org).order_by('name') + + + class PartnerUpdateForm(BasePartnerForm): + def __init__(self, *args, **kwargs): super(PartnerUpdateForm, self).__init__(*args, **kwargs) self.fields['primary_contact'].queryset = kwargs['instance'].get_users() - self.fields['labels'].queryset = Label.get_all(org).order_by('name') class Meta: model = Partner fields = ('name', 'description', 'primary_contact', 'logo', 'is_restricted', 'labels') - class PartnerCreateForm(forms.ModelForm): ? ^^ ^^^^^^ ^ + class PartnerCreateForm(BasePartnerForm): ? ^^^^^^ ^^ ^ - labels = forms.ModelMultipleChoiceField(label=_("Can Access"), - queryset=Label.objects.none(), - widget=forms.CheckboxSelectMultiple(), - required=False) - def __init__(self, *args, **kwargs): - org = kwargs.pop('org') super(PartnerCreateForm, self).__init__(*args, **kwargs) - - self.fields['labels'].queryset = Label.get_all(org).order_by('name') class Meta: model = Partner fields = ('name', 'description', 'logo', 'is_restricted', 'labels')
519aff5c44c6801c44981b059654e598c6d8db49
second/blog/models.py
second/blog/models.py
from __future__ import unicode_literals from django.db import models # Create your models here.
from __future__ import unicode_literals from django.db import models from django.utils import timezone # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title
Create Post model in model.py
Create Post model in model.py
Python
mit
ugaliguy/Django-Tutorial-Projects,ugaliguy/Django-Tutorial-Projects
from __future__ import unicode_literals from django.db import models + from django.utils import timezone # Create your models here. + class Post(models.Model): + author = models.ForeignKey('auth.User') + title = models.CharField(max_length=200) + text = models.TextField() + created_date = models.DateTimeField(default=timezone.now) + published_date = models.DateTimeField(blank=True, null=True) + + def publish(self): + self.published_date = timezone.now() + self.save() + + def __str__(self): + return self.title
Create Post model in model.py
## Code Before: from __future__ import unicode_literals from django.db import models # Create your models here. ## Instruction: Create Post model in model.py ## Code After: from __future__ import unicode_literals from django.db import models from django.utils import timezone # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title
from __future__ import unicode_literals from django.db import models + from django.utils import timezone # Create your models here. + + class Post(models.Model): + author = models.ForeignKey('auth.User') + title = models.CharField(max_length=200) + text = models.TextField() + created_date = models.DateTimeField(default=timezone.now) + published_date = models.DateTimeField(blank=True, null=True) + + def publish(self): + self.published_date = timezone.now() + self.save() + + def __str__(self): + return self.title
17fe6d36a34218e74b53e9617212f0e67b05297d
pysteps/io/__init__.py
pysteps/io/__init__.py
from .interface import get_method from .archive import * from .importers import * from .readers import *
from .interface import get_method from .archive import * from .exporters import * from .importers import * from .readers import *
Add missing import of the exporters module
Add missing import of the exporters module
Python
bsd-3-clause
pySTEPS/pysteps
from .interface import get_method from .archive import * + from .exporters import * from .importers import * from .readers import *
Add missing import of the exporters module
## Code Before: from .interface import get_method from .archive import * from .importers import * from .readers import * ## Instruction: Add missing import of the exporters module ## Code After: from .interface import get_method from .archive import * from .exporters import * from .importers import * from .readers import *
from .interface import get_method from .archive import * + from .exporters import * from .importers import * from .readers import *
e229c797a507932d7992f44d3ab93517096c2e94
tests/test_autotime.py
tests/test_autotime.py
from IPython import get_ipython from IPython.testing import tools as tt from IPython.terminal.interactiveshell import TerminalInteractiveShell def test_full_cycle(): shell = TerminalInteractiveShell.instance() ip = get_ipython() with tt.AssertPrints('time: '): ip.run_cell("%load_ext autotime") with tt.AssertPrints('time: '): ip.run_cell("x = 1") with tt.AssertPrints(''): ip.run_cell("%unload_ext autotime")
from IPython import get_ipython from IPython.testing import tools as tt from IPython.terminal.interactiveshell import TerminalInteractiveShell def test_full_cycle(): shell = TerminalInteractiveShell.instance() ip = get_ipython() with tt.AssertPrints('time: '): ip.run_cell('%load_ext autotime') with tt.AssertPrints('time: '): ip.run_cell('x = 1') with tt.AssertNotPrints('time: '): ip.run_cell('%unload_ext autotime')
Make unload test assertion explicit
Make unload test assertion explicit
Python
apache-2.0
cpcloud/ipython-autotime
from IPython import get_ipython from IPython.testing import tools as tt from IPython.terminal.interactiveshell import TerminalInteractiveShell def test_full_cycle(): shell = TerminalInteractiveShell.instance() ip = get_ipython() with tt.AssertPrints('time: '): - ip.run_cell("%load_ext autotime") + ip.run_cell('%load_ext autotime') with tt.AssertPrints('time: '): - ip.run_cell("x = 1") + ip.run_cell('x = 1') - with tt.AssertPrints(''): + with tt.AssertNotPrints('time: '): - ip.run_cell("%unload_ext autotime") + ip.run_cell('%unload_ext autotime')
Make unload test assertion explicit
## Code Before: from IPython import get_ipython from IPython.testing import tools as tt from IPython.terminal.interactiveshell import TerminalInteractiveShell def test_full_cycle(): shell = TerminalInteractiveShell.instance() ip = get_ipython() with tt.AssertPrints('time: '): ip.run_cell("%load_ext autotime") with tt.AssertPrints('time: '): ip.run_cell("x = 1") with tt.AssertPrints(''): ip.run_cell("%unload_ext autotime") ## Instruction: Make unload test assertion explicit ## Code After: from IPython import get_ipython from IPython.testing import tools as tt from IPython.terminal.interactiveshell import TerminalInteractiveShell def test_full_cycle(): shell = TerminalInteractiveShell.instance() ip = get_ipython() with tt.AssertPrints('time: '): ip.run_cell('%load_ext autotime') with tt.AssertPrints('time: '): ip.run_cell('x = 1') with tt.AssertNotPrints('time: '): ip.run_cell('%unload_ext autotime')
from IPython import get_ipython from IPython.testing import tools as tt from IPython.terminal.interactiveshell import TerminalInteractiveShell def test_full_cycle(): shell = TerminalInteractiveShell.instance() ip = get_ipython() with tt.AssertPrints('time: '): - ip.run_cell("%load_ext autotime") ? ^ ^ + ip.run_cell('%load_ext autotime') ? ^ ^ with tt.AssertPrints('time: '): - ip.run_cell("x = 1") ? ^ ^ + ip.run_cell('x = 1') ? ^ ^ - with tt.AssertPrints(''): + with tt.AssertNotPrints('time: '): ? +++ ++++++ - ip.run_cell("%unload_ext autotime") ? ^ ^ + ip.run_cell('%unload_ext autotime') ? ^ ^
fc18f86964e170c48632c614c86a0d26c9fbdd41
tests/test_load_module_from_file_location.py
tests/test_load_module_from_file_location.py
from pathlib import Path from types import ModuleType import pytest from sanic.exceptions import LoadFileException from sanic.utils import load_module_from_file_location @pytest.fixture def loaded_module_from_file_location(): return load_module_from_file_location( str(Path(__file__).parent / "static/app_test_config.py") ) @pytest.mark.dependency(name="test_load_module_from_file_location") def test_load_module_from_file_location(loaded_module_from_file_location): assert isinstance(loaded_module_from_file_location, ModuleType) @pytest.mark.dependency(depends=["test_load_module_from_file_location"]) def test_loaded_module_from_file_location_name( loaded_module_from_file_location, ): assert loaded_module_from_file_location.__name__ == "app_test_config" def test_load_module_from_file_location_with_non_existing_env_variable(): with pytest.raises( LoadFileException, match="The following environment variables are not set: MuuMilk", ): load_module_from_file_location("${MuuMilk}")
from pathlib import Path from types import ModuleType import pytest from sanic.exceptions import LoadFileException from sanic.utils import load_module_from_file_location @pytest.fixture def loaded_module_from_file_location(): return load_module_from_file_location( str(Path(__file__).parent / "static" / "app_test_config.py") ) @pytest.mark.dependency(name="test_load_module_from_file_location") def test_load_module_from_file_location(loaded_module_from_file_location): assert isinstance(loaded_module_from_file_location, ModuleType) @pytest.mark.dependency(depends=["test_load_module_from_file_location"]) def test_loaded_module_from_file_location_name(loaded_module_from_file_location,): assert loaded_module_from_file_location.__name__ == "app_test_config" def test_load_module_from_file_location_with_non_existing_env_variable(): with pytest.raises( LoadFileException, match="The following environment variables are not set: MuuMilk", ): load_module_from_file_location("${MuuMilk}")
Resolve broken test in appveyor
Resolve broken test in appveyor
Python
mit
channelcat/sanic,channelcat/sanic,ashleysommer/sanic,channelcat/sanic,ashleysommer/sanic,ashleysommer/sanic,channelcat/sanic
from pathlib import Path from types import ModuleType import pytest from sanic.exceptions import LoadFileException from sanic.utils import load_module_from_file_location @pytest.fixture def loaded_module_from_file_location(): return load_module_from_file_location( - str(Path(__file__).parent / "static/app_test_config.py") + str(Path(__file__).parent / "static" / "app_test_config.py") ) @pytest.mark.dependency(name="test_load_module_from_file_location") def test_load_module_from_file_location(loaded_module_from_file_location): assert isinstance(loaded_module_from_file_location, ModuleType) @pytest.mark.dependency(depends=["test_load_module_from_file_location"]) + def test_loaded_module_from_file_location_name(loaded_module_from_file_location,): - def test_loaded_module_from_file_location_name( - loaded_module_from_file_location, - ): assert loaded_module_from_file_location.__name__ == "app_test_config" def test_load_module_from_file_location_with_non_existing_env_variable(): with pytest.raises( LoadFileException, match="The following environment variables are not set: MuuMilk", ): load_module_from_file_location("${MuuMilk}")
Resolve broken test in appveyor
## Code Before: from pathlib import Path from types import ModuleType import pytest from sanic.exceptions import LoadFileException from sanic.utils import load_module_from_file_location @pytest.fixture def loaded_module_from_file_location(): return load_module_from_file_location( str(Path(__file__).parent / "static/app_test_config.py") ) @pytest.mark.dependency(name="test_load_module_from_file_location") def test_load_module_from_file_location(loaded_module_from_file_location): assert isinstance(loaded_module_from_file_location, ModuleType) @pytest.mark.dependency(depends=["test_load_module_from_file_location"]) def test_loaded_module_from_file_location_name( loaded_module_from_file_location, ): assert loaded_module_from_file_location.__name__ == "app_test_config" def test_load_module_from_file_location_with_non_existing_env_variable(): with pytest.raises( LoadFileException, match="The following environment variables are not set: MuuMilk", ): load_module_from_file_location("${MuuMilk}") ## Instruction: Resolve broken test in appveyor ## Code After: from pathlib import Path from types import ModuleType import pytest from sanic.exceptions import LoadFileException from sanic.utils import load_module_from_file_location @pytest.fixture def loaded_module_from_file_location(): return load_module_from_file_location( str(Path(__file__).parent / "static" / "app_test_config.py") ) @pytest.mark.dependency(name="test_load_module_from_file_location") def test_load_module_from_file_location(loaded_module_from_file_location): assert isinstance(loaded_module_from_file_location, ModuleType) @pytest.mark.dependency(depends=["test_load_module_from_file_location"]) def test_loaded_module_from_file_location_name(loaded_module_from_file_location,): assert loaded_module_from_file_location.__name__ == "app_test_config" def test_load_module_from_file_location_with_non_existing_env_variable(): with pytest.raises( LoadFileException, match="The following environment variables are not set: MuuMilk", ): load_module_from_file_location("${MuuMilk}")
from pathlib import Path from types import ModuleType import pytest from sanic.exceptions import LoadFileException from sanic.utils import load_module_from_file_location @pytest.fixture def loaded_module_from_file_location(): return load_module_from_file_location( - str(Path(__file__).parent / "static/app_test_config.py") + str(Path(__file__).parent / "static" / "app_test_config.py") ? ++ ++ ) @pytest.mark.dependency(name="test_load_module_from_file_location") def test_load_module_from_file_location(loaded_module_from_file_location): assert isinstance(loaded_module_from_file_location, ModuleType) @pytest.mark.dependency(depends=["test_load_module_from_file_location"]) + def test_loaded_module_from_file_location_name(loaded_module_from_file_location,): - def test_loaded_module_from_file_location_name( - loaded_module_from_file_location, - ): assert loaded_module_from_file_location.__name__ == "app_test_config" def test_load_module_from_file_location_with_non_existing_env_variable(): with pytest.raises( LoadFileException, match="The following environment variables are not set: MuuMilk", ): load_module_from_file_location("${MuuMilk}")
eac78bcb95e2c34a5c2de75db785dd6532306819
ibei/main.py
ibei/main.py
import numpy as np from astropy import constants from astropy import units from sympy.mpmath import polylog def uibei(order, energy_lo, temp, chem_potential): """ Upper incomplete Bose-Einstein integral. """ kT = temp * constants.k_B reduced_energy_lo = energy_lo / kT reduced_chem_potential = chem_potential / kT prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \ (constants.h**3 * constants.c**2) summand = 0 for indx in range(1, order + 2): expt = (reduced_chem_potential - reduced_energy_lo).decompose() term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1) summand += term return summand def bb_rad_power(temp): """ Blackbody radiant power (Stefan-Boltzmann). """ return constants.sigma_sb * temp**4
import numpy as np from astropy import constants from astropy import units from sympy.mpmath import polylog def uibei(order, energy_lo, temp, chem_potential): """ Upper incomplete Bose-Einstein integral. """ kT = temp * constants.k_B reduced_energy_lo = energy_lo / kT reduced_chem_potential = chem_potential / kT prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \ (constants.h**3 * constants.c**2) summand = 0 for indx in range(1, order + 2): expt = (reduced_chem_potential - reduced_energy_lo).decompose() term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1) summand += term return summand def bb_rad_power(temp): """ Blackbody radiant power (Stefan-Boltzmann). """ return constants.sigma_sb * temp**4 def devos_power(bandgap, temp_sun, temp_planet, voltage): """ Power calculated according to DeVos Eq. 6.4. """ sun = uibei(2, bandgap, temp_sun, 0) solar_cell = uibei(2, bandgap, temp_sun, constants.q * voltage) return voltage * constants.e * (sun - solar_cell)
Add draft of DeVos solar cell power function
Add draft of DeVos solar cell power function
Python
mit
jrsmith3/tec,jrsmith3/ibei,jrsmith3/tec
import numpy as np from astropy import constants from astropy import units from sympy.mpmath import polylog def uibei(order, energy_lo, temp, chem_potential): """ Upper incomplete Bose-Einstein integral. """ kT = temp * constants.k_B reduced_energy_lo = energy_lo / kT reduced_chem_potential = chem_potential / kT prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \ (constants.h**3 * constants.c**2) summand = 0 for indx in range(1, order + 2): expt = (reduced_chem_potential - reduced_energy_lo).decompose() term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1) summand += term return summand def bb_rad_power(temp): """ Blackbody radiant power (Stefan-Boltzmann). """ return constants.sigma_sb * temp**4 + + def devos_power(bandgap, temp_sun, temp_planet, voltage): + """ + Power calculated according to DeVos Eq. 6.4. + """ + sun = uibei(2, bandgap, temp_sun, 0) + solar_cell = uibei(2, bandgap, temp_sun, constants.q * voltage) + return voltage * constants.e * (sun - solar_cell) + +
Add draft of DeVos solar cell power function
## Code Before: import numpy as np from astropy import constants from astropy import units from sympy.mpmath import polylog def uibei(order, energy_lo, temp, chem_potential): """ Upper incomplete Bose-Einstein integral. """ kT = temp * constants.k_B reduced_energy_lo = energy_lo / kT reduced_chem_potential = chem_potential / kT prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \ (constants.h**3 * constants.c**2) summand = 0 for indx in range(1, order + 2): expt = (reduced_chem_potential - reduced_energy_lo).decompose() term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1) summand += term return summand def bb_rad_power(temp): """ Blackbody radiant power (Stefan-Boltzmann). """ return constants.sigma_sb * temp**4 ## Instruction: Add draft of DeVos solar cell power function ## Code After: import numpy as np from astropy import constants from astropy import units from sympy.mpmath import polylog def uibei(order, energy_lo, temp, chem_potential): """ Upper incomplete Bose-Einstein integral. """ kT = temp * constants.k_B reduced_energy_lo = energy_lo / kT reduced_chem_potential = chem_potential / kT prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \ (constants.h**3 * constants.c**2) summand = 0 for indx in range(1, order + 2): expt = (reduced_chem_potential - reduced_energy_lo).decompose() term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1) summand += term return summand def bb_rad_power(temp): """ Blackbody radiant power (Stefan-Boltzmann). """ return constants.sigma_sb * temp**4 def devos_power(bandgap, temp_sun, temp_planet, voltage): """ Power calculated according to DeVos Eq. 6.4. """ sun = uibei(2, bandgap, temp_sun, 0) solar_cell = uibei(2, bandgap, temp_sun, constants.q * voltage) return voltage * constants.e * (sun - solar_cell)
import numpy as np from astropy import constants from astropy import units from sympy.mpmath import polylog def uibei(order, energy_lo, temp, chem_potential): """ Upper incomplete Bose-Einstein integral. """ kT = temp * constants.k_B reduced_energy_lo = energy_lo / kT reduced_chem_potential = chem_potential / kT prefactor = (2 * np.pi * np.math.factorial(order) * kT**(order + 1)) / \ (constants.h**3 * constants.c**2) summand = 0 for indx in range(1, order + 2): expt = (reduced_chem_potential - reduced_energy_lo).decompose() term = reduced_energy_lo**(order - indx + 1) * polylog(indx, np.exp(expt)) / np.math.factorial(order - indx + 1) summand += term return summand def bb_rad_power(temp): """ Blackbody radiant power (Stefan-Boltzmann). """ return constants.sigma_sb * temp**4 + + + def devos_power(bandgap, temp_sun, temp_planet, voltage): + """ + Power calculated according to DeVos Eq. 6.4. + """ + sun = uibei(2, bandgap, temp_sun, 0) + solar_cell = uibei(2, bandgap, temp_sun, constants.q * voltage) + return voltage * constants.e * (sun - solar_cell) +
c9f21a389028ed3b831286dc6c3991f48faa6e81
app/soc/mapreduce/convert_project_mentors.py
app/soc/mapreduce/convert_project_mentors.py
__authors__ = [ '"Madhusudan.C.S" <madhusudancs@gmail.com>', ] import logging from google.appengine.ext import db from google.appengine.ext.mapreduce import operation from soc.modules.gsoc.models.profile import GSoCProfile from soc.modules.gsoc.models.project import GSoCProject def process(project): if not project: yield operation.counters.Increment("missing_project") mentor = GSoCProject.mentor.get_value_for_datastore(project) mentors = [mentor] for am in project.additional_mentors: if am not in mentors: mentors.append(am) project.mentors = mentors yield operation.db.Put(project) yield operation.counters.Increment("projects_updated")
__authors__ = [ '"Madhusudan.C.S" <madhusudancs@gmail.com>', ] from google.appengine.ext.mapreduce import operation from soc.modules.gsoc.models.project import GSoCProject def process(project): mentor = GSoCProject.mentor.get_value_for_datastore(project) mentors = [mentor] for am in project.additional_mentors: if am not in mentors: mentors.append(am) project.mentors = mentors yield operation.db.Put(project) yield operation.counters.Increment("projects_updated")
Remove the check for existence of project since mapreduce API guarantees that.
Remove the check for existence of project since mapreduce API guarantees that. Also remove unused imports.
Python
apache-2.0
rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son
__authors__ = [ '"Madhusudan.C.S" <madhusudancs@gmail.com>', ] - import logging - - from google.appengine.ext import db from google.appengine.ext.mapreduce import operation - from soc.modules.gsoc.models.profile import GSoCProfile from soc.modules.gsoc.models.project import GSoCProject def process(project): - if not project: - yield operation.counters.Increment("missing_project") - mentor = GSoCProject.mentor.get_value_for_datastore(project) mentors = [mentor] for am in project.additional_mentors: if am not in mentors: mentors.append(am) project.mentors = mentors yield operation.db.Put(project) yield operation.counters.Increment("projects_updated")
Remove the check for existence of project since mapreduce API guarantees that.
## Code Before: __authors__ = [ '"Madhusudan.C.S" <madhusudancs@gmail.com>', ] import logging from google.appengine.ext import db from google.appengine.ext.mapreduce import operation from soc.modules.gsoc.models.profile import GSoCProfile from soc.modules.gsoc.models.project import GSoCProject def process(project): if not project: yield operation.counters.Increment("missing_project") mentor = GSoCProject.mentor.get_value_for_datastore(project) mentors = [mentor] for am in project.additional_mentors: if am not in mentors: mentors.append(am) project.mentors = mentors yield operation.db.Put(project) yield operation.counters.Increment("projects_updated") ## Instruction: Remove the check for existence of project since mapreduce API guarantees that. ## Code After: __authors__ = [ '"Madhusudan.C.S" <madhusudancs@gmail.com>', ] from google.appengine.ext.mapreduce import operation from soc.modules.gsoc.models.project import GSoCProject def process(project): mentor = GSoCProject.mentor.get_value_for_datastore(project) mentors = [mentor] for am in project.additional_mentors: if am not in mentors: mentors.append(am) project.mentors = mentors yield operation.db.Put(project) yield operation.counters.Increment("projects_updated")
__authors__ = [ '"Madhusudan.C.S" <madhusudancs@gmail.com>', ] - import logging - - from google.appengine.ext import db from google.appengine.ext.mapreduce import operation - from soc.modules.gsoc.models.profile import GSoCProfile from soc.modules.gsoc.models.project import GSoCProject def process(project): - if not project: - yield operation.counters.Increment("missing_project") - mentor = GSoCProject.mentor.get_value_for_datastore(project) mentors = [mentor] for am in project.additional_mentors: if am not in mentors: mentors.append(am) project.mentors = mentors yield operation.db.Put(project) yield operation.counters.Increment("projects_updated")
b89f6981d4f55790aa919f36e02a6312bd5f1583
tests/__init__.py
tests/__init__.py
import unittest import sys from six import PY3 if PY3: from urllib.parse import urlsplit, parse_qsl else: from urlparse import urlsplit, parse_qsl import werkzeug as wz from flask import Flask, url_for, render_template_string from flask.ext.images import Images, ImageSize, resized_img_src import flask flask_version = tuple(map(int, flask.__version__.split('.'))) class TestCase(unittest.TestCase): def setUp(self): self.app = self.create_app() self.app_ctx = self.app.app_context() self.app_ctx.push() self.req_ctx = self.app.test_request_context('http://localhost:8000/') self.req_ctx.push() self.client = self.app.test_client() def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['SERVER_NAME'] = 'localhost' app.config['SECRET_KEY'] = 'secret secret' app.config['IMAGES_PATH'] = ['assets'] self.images = Images(app) return app def assert200(self, res): self.assertEqual(res.status_code, 200)
import unittest import sys from six import PY3 if PY3: from urllib.parse import urlsplit, parse_qsl else: from urlparse import urlsplit, parse_qsl import werkzeug as wz from flask import Flask, url_for, render_template_string import flask from flask_images import Images, ImageSize, resized_img_src flask_version = tuple(map(int, flask.__version__.split('.'))) class TestCase(unittest.TestCase): def setUp(self): self.app = self.create_app() self.app_ctx = self.app.app_context() self.app_ctx.push() self.req_ctx = self.app.test_request_context('http://localhost:8000/') self.req_ctx.push() self.client = self.app.test_client() def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['SERVER_NAME'] = 'localhost' app.config['SECRET_KEY'] = 'secret secret' app.config['IMAGES_PATH'] = ['assets'] self.images = Images(app) return app def assert200(self, res): self.assertEqual(res.status_code, 200)
Stop using `flask.ext.*` in tests.
Stop using `flask.ext.*` in tests.
Python
bsd-3-clause
mikeboers/Flask-Images
import unittest import sys from six import PY3 if PY3: from urllib.parse import urlsplit, parse_qsl else: from urlparse import urlsplit, parse_qsl import werkzeug as wz from flask import Flask, url_for, render_template_string - from flask.ext.images import Images, ImageSize, resized_img_src import flask + + from flask_images import Images, ImageSize, resized_img_src + flask_version = tuple(map(int, flask.__version__.split('.'))) class TestCase(unittest.TestCase): def setUp(self): self.app = self.create_app() self.app_ctx = self.app.app_context() self.app_ctx.push() self.req_ctx = self.app.test_request_context('http://localhost:8000/') self.req_ctx.push() self.client = self.app.test_client() def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['SERVER_NAME'] = 'localhost' app.config['SECRET_KEY'] = 'secret secret' app.config['IMAGES_PATH'] = ['assets'] self.images = Images(app) return app def assert200(self, res): self.assertEqual(res.status_code, 200)
Stop using `flask.ext.*` in tests.
## Code Before: import unittest import sys from six import PY3 if PY3: from urllib.parse import urlsplit, parse_qsl else: from urlparse import urlsplit, parse_qsl import werkzeug as wz from flask import Flask, url_for, render_template_string from flask.ext.images import Images, ImageSize, resized_img_src import flask flask_version = tuple(map(int, flask.__version__.split('.'))) class TestCase(unittest.TestCase): def setUp(self): self.app = self.create_app() self.app_ctx = self.app.app_context() self.app_ctx.push() self.req_ctx = self.app.test_request_context('http://localhost:8000/') self.req_ctx.push() self.client = self.app.test_client() def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['SERVER_NAME'] = 'localhost' app.config['SECRET_KEY'] = 'secret secret' app.config['IMAGES_PATH'] = ['assets'] self.images = Images(app) return app def assert200(self, res): self.assertEqual(res.status_code, 200) ## Instruction: Stop using `flask.ext.*` in tests. ## Code After: import unittest import sys from six import PY3 if PY3: from urllib.parse import urlsplit, parse_qsl else: from urlparse import urlsplit, parse_qsl import werkzeug as wz from flask import Flask, url_for, render_template_string import flask from flask_images import Images, ImageSize, resized_img_src flask_version = tuple(map(int, flask.__version__.split('.'))) class TestCase(unittest.TestCase): def setUp(self): self.app = self.create_app() self.app_ctx = self.app.app_context() self.app_ctx.push() self.req_ctx = self.app.test_request_context('http://localhost:8000/') self.req_ctx.push() self.client = self.app.test_client() def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['SERVER_NAME'] = 'localhost' app.config['SECRET_KEY'] = 'secret secret' app.config['IMAGES_PATH'] = ['assets'] self.images = Images(app) return app def assert200(self, res): self.assertEqual(res.status_code, 200)
import unittest import sys from six import PY3 if PY3: from urllib.parse import urlsplit, parse_qsl else: from urlparse import urlsplit, parse_qsl import werkzeug as wz from flask import Flask, url_for, render_template_string - from flask.ext.images import Images, ImageSize, resized_img_src import flask + + from flask_images import Images, ImageSize, resized_img_src + flask_version = tuple(map(int, flask.__version__.split('.'))) class TestCase(unittest.TestCase): def setUp(self): self.app = self.create_app() self.app_ctx = self.app.app_context() self.app_ctx.push() self.req_ctx = self.app.test_request_context('http://localhost:8000/') self.req_ctx.push() self.client = self.app.test_client() def create_app(self): app = Flask(__name__) app.config['TESTING'] = True app.config['SERVER_NAME'] = 'localhost' app.config['SECRET_KEY'] = 'secret secret' app.config['IMAGES_PATH'] = ['assets'] self.images = Images(app) return app def assert200(self, res): self.assertEqual(res.status_code, 200)
c5f9b9bc76f797156b73a2bb26b80ebf23d62fe4
polyaxon/pipelines/celery_task.py
polyaxon/pipelines/celery_task.py
from pipelines.models import Operation from polyaxon.celery_api import CeleryTask class OperationTask(CeleryTask): """Base operation celery task with basic logging.""" _operation = None def run(self, *args, **kwargs): self._operation = Operation.objects.get(id=kwargs['query_id']) super(OperationTask, self).run(*args, **kwargs) def on_failure(self, exc, task_id, args, kwargs, einfo): """Update query status and send email notification to a user""" super(OperationTask, self).on_failure(exc, task_id, args, kwargs, einfo) self._operation.on_failure() def on_retry(self, exc, task_id, args, kwargs, einfo): super(OperationTask, self).on_retry(exc, task_id, args, kwargs, einfo) self._operation.on_retry() def on_success(self, retval, task_id, args, kwargs): """Send email notification and a file, if requested to do so by a user""" super(OperationTask, self).on_success(retval, task_id, args, kwargs) self._operation.on_success()
from pipelines.models import Operation from polyaxon.celery_api import CeleryTask class OperationTask(CeleryTask): """Base operation celery task with basic logging.""" _operation = None def __call__(self, *args, **kwargs): self._operation = Operation.objects.get(id=kwargs['query_id']) self._operation.on_run() self.max_retries = self._operation.max_retries self.countdown = self._operation.get_countdown(self.request.retries) super(OperationTask, self).__call__(*args, **kwargs) def on_failure(self, exc, task_id, args, kwargs, einfo): """Update query status and send email notification to a user""" super(OperationTask, self).on_failure(exc, task_id, args, kwargs, einfo) self._operation.on_failure() def on_retry(self, exc, task_id, args, kwargs, einfo): super(OperationTask, self).on_retry(exc, task_id, args, kwargs, einfo) self._operation.on_retry() def on_success(self, retval, task_id, args, kwargs): """Send email notification and a file, if requested to do so by a user""" super(OperationTask, self).on_success(retval, task_id, args, kwargs) self._operation.on_success()
Update OperationCelery with max_retries and countdown logic
Update OperationCelery with max_retries and countdown logic
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
from pipelines.models import Operation from polyaxon.celery_api import CeleryTask class OperationTask(CeleryTask): """Base operation celery task with basic logging.""" _operation = None - def run(self, *args, **kwargs): + def __call__(self, *args, **kwargs): self._operation = Operation.objects.get(id=kwargs['query_id']) + self._operation.on_run() + self.max_retries = self._operation.max_retries + self.countdown = self._operation.get_countdown(self.request.retries) + - super(OperationTask, self).run(*args, **kwargs) + super(OperationTask, self).__call__(*args, **kwargs) def on_failure(self, exc, task_id, args, kwargs, einfo): """Update query status and send email notification to a user""" super(OperationTask, self).on_failure(exc, task_id, args, kwargs, einfo) self._operation.on_failure() def on_retry(self, exc, task_id, args, kwargs, einfo): super(OperationTask, self).on_retry(exc, task_id, args, kwargs, einfo) self._operation.on_retry() def on_success(self, retval, task_id, args, kwargs): """Send email notification and a file, if requested to do so by a user""" super(OperationTask, self).on_success(retval, task_id, args, kwargs) self._operation.on_success()
Update OperationCelery with max_retries and countdown logic
## Code Before: from pipelines.models import Operation from polyaxon.celery_api import CeleryTask class OperationTask(CeleryTask): """Base operation celery task with basic logging.""" _operation = None def run(self, *args, **kwargs): self._operation = Operation.objects.get(id=kwargs['query_id']) super(OperationTask, self).run(*args, **kwargs) def on_failure(self, exc, task_id, args, kwargs, einfo): """Update query status and send email notification to a user""" super(OperationTask, self).on_failure(exc, task_id, args, kwargs, einfo) self._operation.on_failure() def on_retry(self, exc, task_id, args, kwargs, einfo): super(OperationTask, self).on_retry(exc, task_id, args, kwargs, einfo) self._operation.on_retry() def on_success(self, retval, task_id, args, kwargs): """Send email notification and a file, if requested to do so by a user""" super(OperationTask, self).on_success(retval, task_id, args, kwargs) self._operation.on_success() ## Instruction: Update OperationCelery with max_retries and countdown logic ## Code After: from pipelines.models import Operation from polyaxon.celery_api import CeleryTask class OperationTask(CeleryTask): """Base operation celery task with basic logging.""" _operation = None def __call__(self, *args, **kwargs): self._operation = Operation.objects.get(id=kwargs['query_id']) self._operation.on_run() self.max_retries = self._operation.max_retries self.countdown = self._operation.get_countdown(self.request.retries) super(OperationTask, self).__call__(*args, **kwargs) def on_failure(self, exc, task_id, args, kwargs, einfo): """Update query status and send email notification to a user""" super(OperationTask, self).on_failure(exc, task_id, args, kwargs, einfo) self._operation.on_failure() def on_retry(self, exc, task_id, args, kwargs, einfo): super(OperationTask, self).on_retry(exc, task_id, args, kwargs, einfo) self._operation.on_retry() def on_success(self, retval, task_id, args, kwargs): """Send email notification and a file, if requested to do so by a user""" super(OperationTask, self).on_success(retval, task_id, args, kwargs) self._operation.on_success()
from pipelines.models import Operation from polyaxon.celery_api import CeleryTask class OperationTask(CeleryTask): """Base operation celery task with basic logging.""" _operation = None - def run(self, *args, **kwargs): ? ^^^ + def __call__(self, *args, **kwargs): ? ^^^^^^^^ self._operation = Operation.objects.get(id=kwargs['query_id']) + self._operation.on_run() + self.max_retries = self._operation.max_retries + self.countdown = self._operation.get_countdown(self.request.retries) + - super(OperationTask, self).run(*args, **kwargs) ? ^^^ + super(OperationTask, self).__call__(*args, **kwargs) ? ^^^^^^^^ def on_failure(self, exc, task_id, args, kwargs, einfo): """Update query status and send email notification to a user""" super(OperationTask, self).on_failure(exc, task_id, args, kwargs, einfo) self._operation.on_failure() def on_retry(self, exc, task_id, args, kwargs, einfo): super(OperationTask, self).on_retry(exc, task_id, args, kwargs, einfo) self._operation.on_retry() def on_success(self, retval, task_id, args, kwargs): """Send email notification and a file, if requested to do so by a user""" super(OperationTask, self).on_success(retval, task_id, args, kwargs) self._operation.on_success()
b26dc2f572fdd8f90a8241c3588870603d763d4d
examples/voice_list_webhook.py
examples/voice_list_webhook.py
import argparse import messagebird from messagebird.voice_webhook import VoiceCreateWebhookRequest parser = argparse.ArgumentParser() parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) args = vars(parser.parse_args()) try: client = messagebird.Client(args['accessKey']) webhooks_list = client.voice_list_webhooks(limit=5, offset=0) # Print the object information. print('\nThe following information was returned as a Voice Webhook objects:\n') for webhook in webhooks_list.data: print('{') print(' id : %s' % webhook.id) print(' token : %s' % webhook.token) print(' url : %s' % webhook.url) print(' createdAtDatetime : %s' % webhook.createdDatetime) print(' updatedAtDatetime : %s' % webhook.updatedDatetime) print('}\n') except messagebird.client.ErrorException as e: print('An error occured while reading a Voice Webhook object:') for error in e.errors: print(' code : %d' % error.code) print(' description : %s' % error.description) print(' parameter : %s\n' % error.parameter)
import argparse import messagebird from messagebird.voice_webhook import VoiceCreateWebhookRequest parser = argparse.ArgumentParser() parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) args = vars(parser.parse_args()) try: client = messagebird.Client(args['accessKey']) webhooks_list = client.voice_list_webhooks(limit=5, offset=0) if webhooks_list is None or webhooks_list.data is None: print("\nNo webhooks\n") exit(0) # Print the object information. print('\nThe following information was returned as a Voice Webhook objects:\n') for webhook in webhooks_list.data: print('{') print(' id : %s' % webhook.id) print(' token : %s' % webhook.token) print(' url : %s' % webhook.url) print(' createdAtDatetime : %s' % webhook.createdDatetime) print(' updatedAtDatetime : %s' % webhook.updatedDatetime) print('}\n') except messagebird.client.ErrorException as e: print('An error occured while reading a Voice Webhook object:') for error in e.errors: print(' code : %d' % error.code) print(' description : %s' % error.description) print(' parameter : %s\n' % error.parameter)
Exit in voice webhook deletion example, if result is empty
Exit in voice webhook deletion example, if result is empty
Python
bsd-2-clause
messagebird/python-rest-api
import argparse import messagebird from messagebird.voice_webhook import VoiceCreateWebhookRequest parser = argparse.ArgumentParser() parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) args = vars(parser.parse_args()) try: client = messagebird.Client(args['accessKey']) webhooks_list = client.voice_list_webhooks(limit=5, offset=0) + if webhooks_list is None or webhooks_list.data is None: + print("\nNo webhooks\n") + exit(0) # Print the object information. print('\nThe following information was returned as a Voice Webhook objects:\n') for webhook in webhooks_list.data: print('{') print(' id : %s' % webhook.id) print(' token : %s' % webhook.token) print(' url : %s' % webhook.url) print(' createdAtDatetime : %s' % webhook.createdDatetime) print(' updatedAtDatetime : %s' % webhook.updatedDatetime) print('}\n') except messagebird.client.ErrorException as e: print('An error occured while reading a Voice Webhook object:') for error in e.errors: print(' code : %d' % error.code) print(' description : %s' % error.description) print(' parameter : %s\n' % error.parameter)
Exit in voice webhook deletion example, if result is empty
## Code Before: import argparse import messagebird from messagebird.voice_webhook import VoiceCreateWebhookRequest parser = argparse.ArgumentParser() parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) args = vars(parser.parse_args()) try: client = messagebird.Client(args['accessKey']) webhooks_list = client.voice_list_webhooks(limit=5, offset=0) # Print the object information. print('\nThe following information was returned as a Voice Webhook objects:\n') for webhook in webhooks_list.data: print('{') print(' id : %s' % webhook.id) print(' token : %s' % webhook.token) print(' url : %s' % webhook.url) print(' createdAtDatetime : %s' % webhook.createdDatetime) print(' updatedAtDatetime : %s' % webhook.updatedDatetime) print('}\n') except messagebird.client.ErrorException as e: print('An error occured while reading a Voice Webhook object:') for error in e.errors: print(' code : %d' % error.code) print(' description : %s' % error.description) print(' parameter : %s\n' % error.parameter) ## Instruction: Exit in voice webhook deletion example, if result is empty ## Code After: import argparse import messagebird from messagebird.voice_webhook import VoiceCreateWebhookRequest parser = argparse.ArgumentParser() parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) args = vars(parser.parse_args()) try: client = messagebird.Client(args['accessKey']) webhooks_list = client.voice_list_webhooks(limit=5, offset=0) if webhooks_list is None or webhooks_list.data is None: print("\nNo webhooks\n") exit(0) # Print the object information. print('\nThe following information was returned as a Voice Webhook objects:\n') for webhook in webhooks_list.data: print('{') print(' id : %s' % webhook.id) print(' token : %s' % webhook.token) print(' url : %s' % webhook.url) print(' createdAtDatetime : %s' % webhook.createdDatetime) print(' updatedAtDatetime : %s' % webhook.updatedDatetime) print('}\n') except messagebird.client.ErrorException as e: print('An error occured while reading a Voice Webhook object:') for error in e.errors: print(' code : %d' % error.code) print(' description : %s' % error.description) print(' parameter : %s\n' % error.parameter)
import argparse import messagebird from messagebird.voice_webhook import VoiceCreateWebhookRequest parser = argparse.ArgumentParser() parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) args = vars(parser.parse_args()) try: client = messagebird.Client(args['accessKey']) webhooks_list = client.voice_list_webhooks(limit=5, offset=0) + if webhooks_list is None or webhooks_list.data is None: + print("\nNo webhooks\n") + exit(0) # Print the object information. print('\nThe following information was returned as a Voice Webhook objects:\n') for webhook in webhooks_list.data: print('{') print(' id : %s' % webhook.id) print(' token : %s' % webhook.token) print(' url : %s' % webhook.url) print(' createdAtDatetime : %s' % webhook.createdDatetime) print(' updatedAtDatetime : %s' % webhook.updatedDatetime) print('}\n') except messagebird.client.ErrorException as e: print('An error occured while reading a Voice Webhook object:') for error in e.errors: print(' code : %d' % error.code) print(' description : %s' % error.description) print(' parameter : %s\n' % error.parameter)
1010cb2c4a4930254e2586949314aa0bb6b89b3d
tests/test_solver_constraint.py
tests/test_solver_constraint.py
import pytest from gaphas.solver import Constraint, MultiConstraint, Variable @pytest.fixture def handler(): events = [] def handler(e): events.append(e) handler.events = events # type: ignore[attr-defined] return handler def test_constraint_propagates_variable_changed(handler): v = Variable() c = Constraint(v) c.add_handler(handler) v.value = 3 assert handler.events == [c] def test_multi_constraint(handler): v = Variable() c = Constraint(v) m = MultiConstraint(c) m.add_handler(handler) v.value = 3 assert handler.events == [c]
import pytest from gaphas.solver import Constraint, MultiConstraint, Variable @pytest.fixture def handler(): events = [] def handler(e): events.append(e) handler.events = events # type: ignore[attr-defined] return handler def test_constraint_propagates_variable_changed(handler): v = Variable() c = Constraint(v) c.add_handler(handler) v.value = 3 assert handler.events == [c] def test_multi_constraint(handler): v = Variable() c = Constraint(v) m = MultiConstraint(c) m.add_handler(handler) v.value = 3 assert handler.events == [c] def test_default_constraint_can_not_solve(): v = Variable() c = Constraint(v) with pytest.raises(NotImplementedError): c.solve()
Test default case for constraint.solve()
Test default case for constraint.solve()
Python
lgpl-2.1
amolenaar/gaphas
import pytest from gaphas.solver import Constraint, MultiConstraint, Variable @pytest.fixture def handler(): events = [] def handler(e): events.append(e) handler.events = events # type: ignore[attr-defined] return handler def test_constraint_propagates_variable_changed(handler): v = Variable() c = Constraint(v) c.add_handler(handler) v.value = 3 assert handler.events == [c] def test_multi_constraint(handler): v = Variable() c = Constraint(v) m = MultiConstraint(c) m.add_handler(handler) v.value = 3 assert handler.events == [c] + + def test_default_constraint_can_not_solve(): + v = Variable() + c = Constraint(v) + + with pytest.raises(NotImplementedError): + c.solve() +
Test default case for constraint.solve()
## Code Before: import pytest from gaphas.solver import Constraint, MultiConstraint, Variable @pytest.fixture def handler(): events = [] def handler(e): events.append(e) handler.events = events # type: ignore[attr-defined] return handler def test_constraint_propagates_variable_changed(handler): v = Variable() c = Constraint(v) c.add_handler(handler) v.value = 3 assert handler.events == [c] def test_multi_constraint(handler): v = Variable() c = Constraint(v) m = MultiConstraint(c) m.add_handler(handler) v.value = 3 assert handler.events == [c] ## Instruction: Test default case for constraint.solve() ## Code After: import pytest from gaphas.solver import Constraint, MultiConstraint, Variable @pytest.fixture def handler(): events = [] def handler(e): events.append(e) handler.events = events # type: ignore[attr-defined] return handler def test_constraint_propagates_variable_changed(handler): v = Variable() c = Constraint(v) c.add_handler(handler) v.value = 3 assert handler.events == [c] def test_multi_constraint(handler): v = Variable() c = Constraint(v) m = MultiConstraint(c) m.add_handler(handler) v.value = 3 assert handler.events == [c] def test_default_constraint_can_not_solve(): v = Variable() c = Constraint(v) with pytest.raises(NotImplementedError): c.solve()
import pytest from gaphas.solver import Constraint, MultiConstraint, Variable @pytest.fixture def handler(): events = [] def handler(e): events.append(e) handler.events = events # type: ignore[attr-defined] return handler def test_constraint_propagates_variable_changed(handler): v = Variable() c = Constraint(v) c.add_handler(handler) v.value = 3 assert handler.events == [c] def test_multi_constraint(handler): v = Variable() c = Constraint(v) m = MultiConstraint(c) m.add_handler(handler) v.value = 3 assert handler.events == [c] + + + def test_default_constraint_can_not_solve(): + v = Variable() + c = Constraint(v) + + with pytest.raises(NotImplementedError): + c.solve()
7881e6d06a34eddef5523df88ee601fb5e5d3ba6
encryptit/dump_json.py
encryptit/dump_json.py
import json from .compat import OrderedDict from .openpgp_message import OpenPGPMessage def dump_stream(f, output_stream, indent=4): message = OpenPGPMessage.from_stream(f) return json.dump(message, output_stream, indent=indent, cls=OpenPGPJsonEncoder) class OpenPGPJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, bytearray): return self.serialize_bytes(obj) if getattr(obj, 'serialize', None): return obj.serialize() return super(OpenPGPJsonEncoder, self).default(obj) def encode(self, obj): # If a builtin type provides a `serialize` method, use that instead of # the default serialisation, eg. namedtuple if getattr(obj, 'serialize', None): obj = obj.serialize() return super(OpenPGPJsonEncoder, self).encode(obj) @staticmethod def serialize_bytes(some_bytes): return OrderedDict([ ('octets', ':'.join(['{0:02x}'.format(byte) for byte in some_bytes])), ('length', len(some_bytes)), ])
import json from .compat import OrderedDict from .openpgp_message import OpenPGPMessage def dump_stream(f, output_stream, indent=4): message = OpenPGPMessage.from_stream(f) return json.dump(message, output_stream, indent=indent, cls=OpenPGPJsonEncoder) class OpenPGPJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, bytearray): return self.serialize_bytes(obj) if getattr(obj, 'serialize', None): return obj.serialize() return super(OpenPGPJsonEncoder, self).default(obj) @staticmethod def serialize_bytes(some_bytes): return OrderedDict([ ('octets', ':'.join(['{0:02x}'.format(byte) for byte in some_bytes])), ('length', len(some_bytes)), ])
Revert "Fix JSON encoding of `PacketLocation`"
Revert "Fix JSON encoding of `PacketLocation`" This reverts commit 9e91912c6c1764c88890ec47df9372e6ac41612c.
Python
agpl-3.0
paulfurley/encryptit,paulfurley/encryptit
import json from .compat import OrderedDict from .openpgp_message import OpenPGPMessage def dump_stream(f, output_stream, indent=4): message = OpenPGPMessage.from_stream(f) return json.dump(message, output_stream, indent=indent, cls=OpenPGPJsonEncoder) class OpenPGPJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, bytearray): return self.serialize_bytes(obj) if getattr(obj, 'serialize', None): return obj.serialize() return super(OpenPGPJsonEncoder, self).default(obj) - def encode(self, obj): - # If a builtin type provides a `serialize` method, use that instead of - # the default serialisation, eg. namedtuple - - if getattr(obj, 'serialize', None): - obj = obj.serialize() - - return super(OpenPGPJsonEncoder, self).encode(obj) - @staticmethod def serialize_bytes(some_bytes): return OrderedDict([ ('octets', ':'.join(['{0:02x}'.format(byte) for byte in some_bytes])), ('length', len(some_bytes)), ])
Revert "Fix JSON encoding of `PacketLocation`"
## Code Before: import json from .compat import OrderedDict from .openpgp_message import OpenPGPMessage def dump_stream(f, output_stream, indent=4): message = OpenPGPMessage.from_stream(f) return json.dump(message, output_stream, indent=indent, cls=OpenPGPJsonEncoder) class OpenPGPJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, bytearray): return self.serialize_bytes(obj) if getattr(obj, 'serialize', None): return obj.serialize() return super(OpenPGPJsonEncoder, self).default(obj) def encode(self, obj): # If a builtin type provides a `serialize` method, use that instead of # the default serialisation, eg. namedtuple if getattr(obj, 'serialize', None): obj = obj.serialize() return super(OpenPGPJsonEncoder, self).encode(obj) @staticmethod def serialize_bytes(some_bytes): return OrderedDict([ ('octets', ':'.join(['{0:02x}'.format(byte) for byte in some_bytes])), ('length', len(some_bytes)), ]) ## Instruction: Revert "Fix JSON encoding of `PacketLocation`" ## Code After: import json from .compat import OrderedDict from .openpgp_message import OpenPGPMessage def dump_stream(f, output_stream, indent=4): message = OpenPGPMessage.from_stream(f) return json.dump(message, output_stream, indent=indent, cls=OpenPGPJsonEncoder) class OpenPGPJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, bytearray): return self.serialize_bytes(obj) if getattr(obj, 'serialize', None): return obj.serialize() return super(OpenPGPJsonEncoder, self).default(obj) @staticmethod def serialize_bytes(some_bytes): return OrderedDict([ ('octets', ':'.join(['{0:02x}'.format(byte) for byte in some_bytes])), ('length', len(some_bytes)), ])
import json from .compat import OrderedDict from .openpgp_message import OpenPGPMessage def dump_stream(f, output_stream, indent=4): message = OpenPGPMessage.from_stream(f) return json.dump(message, output_stream, indent=indent, cls=OpenPGPJsonEncoder) class OpenPGPJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, bytearray): return self.serialize_bytes(obj) if getattr(obj, 'serialize', None): return obj.serialize() return super(OpenPGPJsonEncoder, self).default(obj) - def encode(self, obj): - # If a builtin type provides a `serialize` method, use that instead of - # the default serialisation, eg. namedtuple - - if getattr(obj, 'serialize', None): - obj = obj.serialize() - - return super(OpenPGPJsonEncoder, self).encode(obj) - @staticmethod def serialize_bytes(some_bytes): return OrderedDict([ ('octets', ':'.join(['{0:02x}'.format(byte) for byte in some_bytes])), ('length', len(some_bytes)), ])
791e254c6f1efed88bdc0714ee9bb264634e74a8
transunit.py
transunit.py
class TransUnit(object): "Container for XLIFF trans-unit element" def __init__(self, argument): self.origin_unit = argument self.attributes = argument.attrib self.id = '' self.ns = '' self.state = '' @staticmethod def create(xml_tu): tunit = TransUnit(xml_tu) tunit.id = tunit.attributes['id'] tunit.ns = tunit.__read_ns() tunit.state = tunit.__get_state_from_target() return tunit def __get_state_from_target(self): target = self.origin_unit.find('{}target'.format(self.ns)) if "state" in target.attrib.keys(): return target.attrib['state'] else: return '' def __has_ns(self): return '{' in self.origin_unit.tag def __read_ns(self): if self.__has_ns(): ns, tag = self.origin_unit.tag.split('}') ns = ns + '}' return ns else: return '' def has_any_state(self, list_of_states): return self.state in list_of_states
class TransUnit(object): "Container for XLIFF trans-unit element" def __init__(self, argument): self.origin_unit = argument self.attributes = argument.attrib self.id = '' self.ns = '' self.state = '' @staticmethod def create(xml_tu): tunit = TransUnit(xml_tu) tunit.id = tunit.attributes['id'] tunit.ns = tunit._read_ns() tunit.state = tunit._get_state_from_target() return tunit def _read_ns(self): if self._has_ns(): ns, tag = self.origin_unit.tag.split('}') ns = ns + '}' return ns else: return '' def _has_ns(self): return '{' in self.origin_unit.tag def _get_state_from_target(self): target = self.origin_unit.find('{}target'.format(self.ns)) if "state" in target.attrib.keys(): return target.attrib['state'] else: return '' def has_any_state(self, list_of_states): return self.state in list_of_states
Restructure transUnit class for better readibility
Restructure transUnit class for better readibility
Python
mit
jakub-szczepaniak/xliff
- - class TransUnit(object): "Container for XLIFF trans-unit element" def __init__(self, argument): self.origin_unit = argument self.attributes = argument.attrib self.id = '' self.ns = '' self.state = '' @staticmethod def create(xml_tu): tunit = TransUnit(xml_tu) tunit.id = tunit.attributes['id'] - tunit.ns = tunit.__read_ns() + tunit.ns = tunit._read_ns() - tunit.state = tunit.__get_state_from_target() + tunit.state = tunit._get_state_from_target() return tunit + def _read_ns(self): + if self._has_ns(): + ns, tag = self.origin_unit.tag.split('}') + ns = ns + '}' + return ns + else: + return '' + + def _has_ns(self): + return '{' in self.origin_unit.tag + - def __get_state_from_target(self): + def _get_state_from_target(self): target = self.origin_unit.find('{}target'.format(self.ns)) if "state" in target.attrib.keys(): return target.attrib['state'] else: return '' - def __has_ns(self): - return '{' in self.origin_unit.tag - - def __read_ns(self): - if self.__has_ns(): - ns, tag = self.origin_unit.tag.split('}') - ns = ns + '}' - return ns - else: - return '' - def has_any_state(self, list_of_states): return self.state in list_of_states
Restructure transUnit class for better readibility
## Code Before: class TransUnit(object): "Container for XLIFF trans-unit element" def __init__(self, argument): self.origin_unit = argument self.attributes = argument.attrib self.id = '' self.ns = '' self.state = '' @staticmethod def create(xml_tu): tunit = TransUnit(xml_tu) tunit.id = tunit.attributes['id'] tunit.ns = tunit.__read_ns() tunit.state = tunit.__get_state_from_target() return tunit def __get_state_from_target(self): target = self.origin_unit.find('{}target'.format(self.ns)) if "state" in target.attrib.keys(): return target.attrib['state'] else: return '' def __has_ns(self): return '{' in self.origin_unit.tag def __read_ns(self): if self.__has_ns(): ns, tag = self.origin_unit.tag.split('}') ns = ns + '}' return ns else: return '' def has_any_state(self, list_of_states): return self.state in list_of_states ## Instruction: Restructure transUnit class for better readibility ## Code After: class TransUnit(object): "Container for XLIFF trans-unit element" def __init__(self, argument): self.origin_unit = argument self.attributes = argument.attrib self.id = '' self.ns = '' self.state = '' @staticmethod def create(xml_tu): tunit = TransUnit(xml_tu) tunit.id = tunit.attributes['id'] tunit.ns = tunit._read_ns() tunit.state = tunit._get_state_from_target() return tunit def _read_ns(self): if self._has_ns(): ns, tag = self.origin_unit.tag.split('}') ns = ns + '}' return ns else: return '' def _has_ns(self): return '{' in self.origin_unit.tag def _get_state_from_target(self): target = self.origin_unit.find('{}target'.format(self.ns)) if "state" in target.attrib.keys(): return target.attrib['state'] else: return '' def has_any_state(self, list_of_states): return self.state in list_of_states
- - class TransUnit(object): "Container for XLIFF trans-unit element" def __init__(self, argument): self.origin_unit = argument self.attributes = argument.attrib self.id = '' self.ns = '' self.state = '' @staticmethod def create(xml_tu): tunit = TransUnit(xml_tu) tunit.id = tunit.attributes['id'] - tunit.ns = tunit.__read_ns() ? - + tunit.ns = tunit._read_ns() - tunit.state = tunit.__get_state_from_target() ? - + tunit.state = tunit._get_state_from_target() return tunit + def _read_ns(self): + if self._has_ns(): + ns, tag = self.origin_unit.tag.split('}') + ns = ns + '}' + return ns + else: + return '' + + def _has_ns(self): + return '{' in self.origin_unit.tag + - def __get_state_from_target(self): ? - + def _get_state_from_target(self): target = self.origin_unit.find('{}target'.format(self.ns)) if "state" in target.attrib.keys(): return target.attrib['state'] else: return '' - def __has_ns(self): - return '{' in self.origin_unit.tag - - def __read_ns(self): - if self.__has_ns(): - ns, tag = self.origin_unit.tag.split('}') - ns = ns + '}' - return ns - else: - return '' - def has_any_state(self, list_of_states): return self.state in list_of_states
2917c8d380bfee3c7589f806ea12f2e3f83e8b93
npc/character/__init__.py
npc/character/__init__.py
from .character import *
from .character import Character from .changeling import Changeling from .werewolf import Werewolf def build(attributes: dict = None, other_char: Character = None): """ Build a new character object with the appropriate class This derives the correct character class based on the type tag of either the other_char character object or the attributes dict, then creates a new character object using that class. If neither is supplied, a blank Character is returned. The character type is fetched first from other_char and only if that is not present is it fetched from attributes. Both other_char and attribuets are passed to the character constructor. See that for how their precedence is applied. If you need more control over the instantiation process, use character_klass_from_type and call the object manually. Args: attributes (dict): Dictionary of attributes to insert into the Character. other_char (Character): Existing character object to copy. Returns: Instantiated Character class or subclass matching the given type. """ if other_char: klass = character_klass_from_type(other_char.type_key) elif attributes: klass = character_klass_from_type(attributes['type'][0]) else: klass = Character return klass(other_char = other_char, attributes = attributes) def character_klass_from_type(ctype: str): """ Choose the correct character class based on type tag Args: ctype (str): Character type tag to use Returns: Character class or subclass depending on the type """ if ctype: ctype = ctype.lower() if ctype == 'changeling': return Changeling if ctype == 'werewolf': return Werewolf return Character
Add helpers to find the right character class
Add helpers to find the right character class
Python
mit
aurule/npc,aurule/npc
- from .character import * + from .character import Character + from .changeling import Changeling + from .werewolf import Werewolf + + def build(attributes: dict = None, other_char: Character = None): + """ + Build a new character object with the appropriate class + + This derives the correct character class based on the type tag of either the + other_char character object or the attributes dict, then creates a new + character object using that class. If neither is supplied, a blank Character + is returned. + + The character type is fetched first from other_char and only if that is not + present is it fetched from attributes. + + Both other_char and attribuets are passed to the character constructor. See + that for how their precedence is applied. + + If you need more control over the instantiation process, use + character_klass_from_type and call the object manually. + + Args: + attributes (dict): Dictionary of attributes to insert into the + Character. + other_char (Character): Existing character object to copy. + + Returns: + Instantiated Character class or subclass matching the given type. + """ + if other_char: + klass = character_klass_from_type(other_char.type_key) + elif attributes: + klass = character_klass_from_type(attributes['type'][0]) + else: + klass = Character + + return klass(other_char = other_char, attributes = attributes) + + def character_klass_from_type(ctype: str): + """ + Choose the correct character class based on type tag + + Args: + ctype (str): Character type tag to use + + Returns: + Character class or subclass depending on the type + """ + if ctype: + ctype = ctype.lower() + if ctype == 'changeling': + return Changeling + if ctype == 'werewolf': + return Werewolf + + return Character +
Add helpers to find the right character class
## Code Before: from .character import * ## Instruction: Add helpers to find the right character class ## Code After: from .character import Character from .changeling import Changeling from .werewolf import Werewolf def build(attributes: dict = None, other_char: Character = None): """ Build a new character object with the appropriate class This derives the correct character class based on the type tag of either the other_char character object or the attributes dict, then creates a new character object using that class. If neither is supplied, a blank Character is returned. The character type is fetched first from other_char and only if that is not present is it fetched from attributes. Both other_char and attribuets are passed to the character constructor. See that for how their precedence is applied. If you need more control over the instantiation process, use character_klass_from_type and call the object manually. Args: attributes (dict): Dictionary of attributes to insert into the Character. other_char (Character): Existing character object to copy. Returns: Instantiated Character class or subclass matching the given type. """ if other_char: klass = character_klass_from_type(other_char.type_key) elif attributes: klass = character_klass_from_type(attributes['type'][0]) else: klass = Character return klass(other_char = other_char, attributes = attributes) def character_klass_from_type(ctype: str): """ Choose the correct character class based on type tag Args: ctype (str): Character type tag to use Returns: Character class or subclass depending on the type """ if ctype: ctype = ctype.lower() if ctype == 'changeling': return Changeling if ctype == 'werewolf': return Werewolf return Character
+ - from .character import * ? ^ + from .character import Character ? ^^^^^^^^^ + from .changeling import Changeling + from .werewolf import Werewolf + + def build(attributes: dict = None, other_char: Character = None): + """ + Build a new character object with the appropriate class + + This derives the correct character class based on the type tag of either the + other_char character object or the attributes dict, then creates a new + character object using that class. If neither is supplied, a blank Character + is returned. + + The character type is fetched first from other_char and only if that is not + present is it fetched from attributes. + + Both other_char and attribuets are passed to the character constructor. See + that for how their precedence is applied. + + If you need more control over the instantiation process, use + character_klass_from_type and call the object manually. + + Args: + attributes (dict): Dictionary of attributes to insert into the + Character. + other_char (Character): Existing character object to copy. + + Returns: + Instantiated Character class or subclass matching the given type. + """ + if other_char: + klass = character_klass_from_type(other_char.type_key) + elif attributes: + klass = character_klass_from_type(attributes['type'][0]) + else: + klass = Character + + return klass(other_char = other_char, attributes = attributes) + + def character_klass_from_type(ctype: str): + """ + Choose the correct character class based on type tag + + Args: + ctype (str): Character type tag to use + + Returns: + Character class or subclass depending on the type + """ + if ctype: + ctype = ctype.lower() + if ctype == 'changeling': + return Changeling + if ctype == 'werewolf': + return Werewolf + + return Character
4bfa6627b14c3e00e32b10a2806f02d4fafd6509
chipy_org/libs/social_auth_pipelines.py
chipy_org/libs/social_auth_pipelines.py
from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name == 'google-oauth2': # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name })
from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name in ['google-oauth2', 'github']: # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) email = kwargs['details'].get('email') if email: User = get_user_model() if User.objects.filter(email=email).exists(): msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name })
Fix false positive for the social login
Fix false positive for the social login
Python
mit
brianray/chipy.org,agfor/chipy.org,bharathelangovan/chipy.org,tanyaschlusser/chipy.org,brianray/chipy.org,tanyaschlusser/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,agfor/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,chicagopython/chipy.org,brianray/chipy.org,agfor/chipy.org
+ from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] - if backend.name == 'google-oauth2': + if backend.name in ['google-oauth2', 'github']: # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) + email = kwargs['details'].get('email') - msg = ugettext('This email is already in use. First login with your other account and ' - 'under the top right menu click add account.') - raise AuthAlreadyAssociated(backend, msg % { - 'provider': backend.name - }) + if email: + User = get_user_model() + if User.objects.filter(email=email).exists(): + msg = ugettext('This email is already in use. First login with your other account and ' + 'under the top right menu click add account.') + raise AuthAlreadyAssociated(backend, msg % { + 'provider': backend.name + }) +
Fix false positive for the social login
## Code Before: from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name == 'google-oauth2': # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) ## Instruction: Fix false positive for the social login ## Code After: from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] if backend.name in ['google-oauth2', 'github']: # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) email = kwargs['details'].get('email') if email: User = get_user_model() if User.objects.filter(email=email).exists(): msg = ugettext('This email is already in use. First login with your other account and ' 'under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name })
+ from django.contrib.auth import get_user_model from django.utils.translation import ugettext from social_auth.exceptions import AuthAlreadyAssociated from social_auth.backends.pipeline.associate import associate_by_email as super_associate_by_email def associate_by_email(*args, **kwargs): """Check if a user with this email already exists. If they do, don't create an account.""" backend = kwargs['backend'] - if backend.name == 'google-oauth2': ? ^^ + if backend.name in ['google-oauth2', 'github']: ? ^^ + +++++++++++ # We provide and exception here for users upgrading. return super_associate_by_email(*args, **kwargs) + email = kwargs['details'].get('email') + + if email: + User = get_user_model() + if User.objects.filter(email=email).exists(): - msg = ugettext('This email is already in use. First login with your other account and ' + msg = ugettext('This email is already in use. First login with your other account and ' ? ++++++++ - 'under the top right menu click add account.') + 'under the top right menu click add account.') ? ++++++++ - raise AuthAlreadyAssociated(backend, msg % { + raise AuthAlreadyAssociated(backend, msg % { ? ++++++++ - 'provider': backend.name + 'provider': backend.name ? ++++++++ - }) + })
6292cd114d8d982162fa8076605cce569acd8fc5
panphon/xsampa.py
panphon/xsampa.py
from __future__ import absolute_import, print_function, unicode_literals import regex as re import unicodecsv as csv import os.path import pkg_resources class XSampa(object): def __init__(self, delimiter=' '): self.delimiter = delimiter self.xs_regex, self.xs2ipa = self.read_xsampa_table() def read_xsampa_table(self): filename = os.path.join('data', 'ipa-xsampa.csv') filename = pkg_resources.resource_filename(__name__, filename) with open(filename, 'rb') as f: xs2ipa = {x[1]: x[0] for x in csv.reader(f, encoding='utf-8')} xs = sorted(xs2ipa.keys(), key=len, reverse=True) xs_regex = re.compile('|'.join(map(re.escape, xs))) return xs_regex, xs2ipa def convert(self, xsampa): def seg2ipa(seg): ipa = [] while seg: match = self.xs_regex.match(seg) if match: ipa.append(self.xs2ipa[match.group(0)]) seg = seg[len(match.group(0)):] else: seg = seg[1:] return ''.join(ipa) ipasegs = map(seg2ipa, xsampa.split(self.delimiter)) return ''.join(ipasegs)
from __future__ import absolute_import, print_function, unicode_literals import regex as re import unicodecsv as csv import os.path import pkg_resources class XSampa(object): def __init__(self, delimiter=' '): self.delimiter = delimiter self.xs_regex, self.xs2ipa = self.read_xsampa_table() def read_xsampa_table(self): filename = os.path.join('data', 'ipa-xsampa.csv') filename = pkg_resources.resource_filename(__name__, filename) with open(filename, 'rb') as f: xs2ipa = {x[1]: x[0] for x in csv.reader(f, encoding='utf-8')} xs = sorted(xs2ipa.keys(), key=len, reverse=True) xs_regex = re.compile('|'.join(list(map(re.escape, xs)))) return xs_regex, xs2ipa def convert(self, xsampa): def seg2ipa(seg): ipa = [] while seg: match = self.xs_regex.match(seg) if match: ipa.append(self.xs2ipa[match.group(0)]) seg = seg[len(match.group(0)):] else: seg = seg[1:] return ''.join(ipa) ipasegs = list(map(seg2ipa, xsampa.split(self.delimiter))) return ''.join(ipasegs)
Convert map objects to lists
Convert map objects to lists
Python
mit
dmort27/panphon,dmort27/panphon
from __future__ import absolute_import, print_function, unicode_literals import regex as re import unicodecsv as csv import os.path import pkg_resources class XSampa(object): def __init__(self, delimiter=' '): self.delimiter = delimiter self.xs_regex, self.xs2ipa = self.read_xsampa_table() def read_xsampa_table(self): filename = os.path.join('data', 'ipa-xsampa.csv') filename = pkg_resources.resource_filename(__name__, filename) with open(filename, 'rb') as f: xs2ipa = {x[1]: x[0] for x in csv.reader(f, encoding='utf-8')} xs = sorted(xs2ipa.keys(), key=len, reverse=True) - xs_regex = re.compile('|'.join(map(re.escape, xs))) + xs_regex = re.compile('|'.join(list(map(re.escape, xs)))) return xs_regex, xs2ipa def convert(self, xsampa): def seg2ipa(seg): ipa = [] while seg: match = self.xs_regex.match(seg) if match: ipa.append(self.xs2ipa[match.group(0)]) seg = seg[len(match.group(0)):] else: seg = seg[1:] return ''.join(ipa) - ipasegs = map(seg2ipa, xsampa.split(self.delimiter)) + ipasegs = list(map(seg2ipa, xsampa.split(self.delimiter))) return ''.join(ipasegs)
Convert map objects to lists
## Code Before: from __future__ import absolute_import, print_function, unicode_literals import regex as re import unicodecsv as csv import os.path import pkg_resources class XSampa(object): def __init__(self, delimiter=' '): self.delimiter = delimiter self.xs_regex, self.xs2ipa = self.read_xsampa_table() def read_xsampa_table(self): filename = os.path.join('data', 'ipa-xsampa.csv') filename = pkg_resources.resource_filename(__name__, filename) with open(filename, 'rb') as f: xs2ipa = {x[1]: x[0] for x in csv.reader(f, encoding='utf-8')} xs = sorted(xs2ipa.keys(), key=len, reverse=True) xs_regex = re.compile('|'.join(map(re.escape, xs))) return xs_regex, xs2ipa def convert(self, xsampa): def seg2ipa(seg): ipa = [] while seg: match = self.xs_regex.match(seg) if match: ipa.append(self.xs2ipa[match.group(0)]) seg = seg[len(match.group(0)):] else: seg = seg[1:] return ''.join(ipa) ipasegs = map(seg2ipa, xsampa.split(self.delimiter)) return ''.join(ipasegs) ## Instruction: Convert map objects to lists ## Code After: from __future__ import absolute_import, print_function, unicode_literals import regex as re import unicodecsv as csv import os.path import pkg_resources class XSampa(object): def __init__(self, delimiter=' '): self.delimiter = delimiter self.xs_regex, self.xs2ipa = self.read_xsampa_table() def read_xsampa_table(self): filename = os.path.join('data', 'ipa-xsampa.csv') filename = pkg_resources.resource_filename(__name__, filename) with open(filename, 'rb') as f: xs2ipa = {x[1]: x[0] for x in csv.reader(f, encoding='utf-8')} xs = sorted(xs2ipa.keys(), key=len, reverse=True) xs_regex = re.compile('|'.join(list(map(re.escape, xs)))) return xs_regex, xs2ipa def convert(self, xsampa): def seg2ipa(seg): ipa = [] while seg: match = self.xs_regex.match(seg) if match: ipa.append(self.xs2ipa[match.group(0)]) seg = seg[len(match.group(0)):] else: seg = seg[1:] return ''.join(ipa) ipasegs = list(map(seg2ipa, xsampa.split(self.delimiter))) return ''.join(ipasegs)
from __future__ import absolute_import, print_function, unicode_literals import regex as re import unicodecsv as csv import os.path import pkg_resources class XSampa(object): def __init__(self, delimiter=' '): self.delimiter = delimiter self.xs_regex, self.xs2ipa = self.read_xsampa_table() def read_xsampa_table(self): filename = os.path.join('data', 'ipa-xsampa.csv') filename = pkg_resources.resource_filename(__name__, filename) with open(filename, 'rb') as f: xs2ipa = {x[1]: x[0] for x in csv.reader(f, encoding='utf-8')} xs = sorted(xs2ipa.keys(), key=len, reverse=True) - xs_regex = re.compile('|'.join(map(re.escape, xs))) + xs_regex = re.compile('|'.join(list(map(re.escape, xs)))) ? +++++ + return xs_regex, xs2ipa def convert(self, xsampa): def seg2ipa(seg): ipa = [] while seg: match = self.xs_regex.match(seg) if match: ipa.append(self.xs2ipa[match.group(0)]) seg = seg[len(match.group(0)):] else: seg = seg[1:] return ''.join(ipa) - ipasegs = map(seg2ipa, xsampa.split(self.delimiter)) + ipasegs = list(map(seg2ipa, xsampa.split(self.delimiter))) ? +++++ + return ''.join(ipasegs)
ee28fdc66fbb0f91821ff18ff219791bf5de8f4d
corehq/apps/fixtures/tasks.py
corehq/apps/fixtures/tasks.py
from __future__ import absolute_import from __future__ import unicode_literals from corehq.apps.fixtures.upload import upload_fixture_file from soil import DownloadBase from celery.task import task @task(serializer='pickle') def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100)
from __future__ import absolute_import, unicode_literals from celery.task import task from soil import DownloadBase from corehq.apps.fixtures.upload import upload_fixture_file @task def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100)
Change fixture upload task to json serializer
Change fixture upload task to json serializer
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
- from __future__ import absolute_import - from __future__ import unicode_literals + from __future__ import absolute_import, unicode_literals + - from corehq.apps.fixtures.upload import upload_fixture_file - from soil import DownloadBase from celery.task import task + from soil import DownloadBase - @task(serializer='pickle') + from corehq.apps.fixtures.upload import upload_fixture_file + + + @task def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100)
Change fixture upload task to json serializer
## Code Before: from __future__ import absolute_import from __future__ import unicode_literals from corehq.apps.fixtures.upload import upload_fixture_file from soil import DownloadBase from celery.task import task @task(serializer='pickle') def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100) ## Instruction: Change fixture upload task to json serializer ## Code After: from __future__ import absolute_import, unicode_literals from celery.task import task from soil import DownloadBase from corehq.apps.fixtures.upload import upload_fixture_file @task def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100)
- from __future__ import absolute_import - from __future__ import unicode_literals + from __future__ import absolute_import, unicode_literals ? +++++++++++++++++ + - from corehq.apps.fixtures.upload import upload_fixture_file - from soil import DownloadBase from celery.task import task + from soil import DownloadBase - @task(serializer='pickle') + from corehq.apps.fixtures.upload import upload_fixture_file + + + @task def fixture_upload_async(domain, download_id, replace): task = fixture_upload_async DownloadBase.set_progress(task, 0, 100) download_ref = DownloadBase.get(download_id) result = upload_fixture_file(domain, download_ref.get_filename(), replace, task) DownloadBase.set_progress(task, 100, 100) return { 'messages': { 'success': result.success, 'messages': result.messages, 'errors': result.errors, 'number_of_fixtures': result.number_of_fixtures, }, } @task(serializer='pickle') def fixture_download_async(prepare_download, *args, **kw): task = fixture_download_async DownloadBase.set_progress(task, 0, 100) prepare_download(task=task, *args, **kw) DownloadBase.set_progress(task, 100, 100)
e3cba925ea106baa99951ac7b3ee72599ee7277d
demos/fs-demo/main.py
demos/fs-demo/main.py
import random import os from microbit import * if 'messages.txt' in os.listdir(): with open('messages.txt') as message_file: messages = message_file.read().split('\n') while True: if button_a.was_pressed(): display.scroll(random.choice(messages))
import random import os import speech from microbit import * if 'messages.txt' in os.listdir(): with open('messages.txt') as message_file: messages = message_file.read().split('\n') while True: if button_a.was_pressed(): speech.say(random.choice(messages))
Change output in fs-demo to voice.
Change output in fs-demo to voice.
Python
mit
mathisgerdes/microbit-macau
import random import os + import speech from microbit import * if 'messages.txt' in os.listdir(): with open('messages.txt') as message_file: messages = message_file.read().split('\n') while True: if button_a.was_pressed(): - display.scroll(random.choice(messages)) + speech.say(random.choice(messages))
Change output in fs-demo to voice.
## Code Before: import random import os from microbit import * if 'messages.txt' in os.listdir(): with open('messages.txt') as message_file: messages = message_file.read().split('\n') while True: if button_a.was_pressed(): display.scroll(random.choice(messages)) ## Instruction: Change output in fs-demo to voice. ## Code After: import random import os import speech from microbit import * if 'messages.txt' in os.listdir(): with open('messages.txt') as message_file: messages = message_file.read().split('\n') while True: if button_a.was_pressed(): speech.say(random.choice(messages))
import random import os + import speech from microbit import * if 'messages.txt' in os.listdir(): with open('messages.txt') as message_file: messages = message_file.read().split('\n') while True: if button_a.was_pressed(): - display.scroll(random.choice(messages)) ? -- ^ ------- + speech.say(random.choice(messages)) ? ^^^^^^
c95d78378c7b3b234439e1d9a9bc41539b9080f5
preferences/models.py
preferences/models.py
import uuid from django.db import models from django.contrib.auth.models import User from opencivicdata.models.people_orgs import Person class Preferences(models.Model): user = models.OneToOneField(User, related_name='preferences') address = models.CharField(max_length=100, blank=True, null=True) lat = models.FloatField(null=True, blank=True) lon = models.FloatField(null=True, blank=True) apikey = models.UUIDField(default=uuid.uuid4) class PersonFollow(models.Model): user = models.ForeignKey(User, related_name='person_follows') person = models.ForeignKey(Person, related_name='follows') class TopicFollow(models.Model): user = models.ForeignKey(User, related_name='topic_follows') topic = models.CharField(max_length=100) class LocationFollow(models.Model): user = models.ForeignKey(User, related_name='location_follows') location = models.CharField(max_length=100)
import uuid from django.db import models from django.contrib.auth.models import User from opencivicdata.models.people_orgs import Person class Preferences(models.Model): user = models.OneToOneField(User, related_name='preferences') address = models.CharField(max_length=100, blank=True, null=True) lat = models.FloatField(null=True, blank=True) lon = models.FloatField(null=True, blank=True) rep_from_address = models.CharField(max_length=255, blank=True, null=True) sen_from_address = models.CharField(max_length=255, blank=True, null=True) apikey = models.UUIDField(default=uuid.uuid4) class PersonFollow(models.Model): user = models.ForeignKey(User, related_name='person_follows') person = models.ForeignKey(Person, related_name='follows') class TopicFollow(models.Model): user = models.ForeignKey(User, related_name='topic_follows') topic = models.CharField(max_length=100) class LocationFollow(models.Model): user = models.ForeignKey(User, related_name='location_follows') location = models.CharField(max_length=100)
Add rep and sen from address fields to Preferences model
Add rep and sen from address fields to Preferences model
Python
mit
jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot
import uuid from django.db import models from django.contrib.auth.models import User from opencivicdata.models.people_orgs import Person class Preferences(models.Model): user = models.OneToOneField(User, related_name='preferences') address = models.CharField(max_length=100, blank=True, null=True) lat = models.FloatField(null=True, blank=True) lon = models.FloatField(null=True, blank=True) + rep_from_address = models.CharField(max_length=255, blank=True, null=True) + sen_from_address = models.CharField(max_length=255, blank=True, null=True) apikey = models.UUIDField(default=uuid.uuid4) class PersonFollow(models.Model): user = models.ForeignKey(User, related_name='person_follows') person = models.ForeignKey(Person, related_name='follows') class TopicFollow(models.Model): user = models.ForeignKey(User, related_name='topic_follows') topic = models.CharField(max_length=100) class LocationFollow(models.Model): user = models.ForeignKey(User, related_name='location_follows') location = models.CharField(max_length=100)
Add rep and sen from address fields to Preferences model
## Code Before: import uuid from django.db import models from django.contrib.auth.models import User from opencivicdata.models.people_orgs import Person class Preferences(models.Model): user = models.OneToOneField(User, related_name='preferences') address = models.CharField(max_length=100, blank=True, null=True) lat = models.FloatField(null=True, blank=True) lon = models.FloatField(null=True, blank=True) apikey = models.UUIDField(default=uuid.uuid4) class PersonFollow(models.Model): user = models.ForeignKey(User, related_name='person_follows') person = models.ForeignKey(Person, related_name='follows') class TopicFollow(models.Model): user = models.ForeignKey(User, related_name='topic_follows') topic = models.CharField(max_length=100) class LocationFollow(models.Model): user = models.ForeignKey(User, related_name='location_follows') location = models.CharField(max_length=100) ## Instruction: Add rep and sen from address fields to Preferences model ## Code After: import uuid from django.db import models from django.contrib.auth.models import User from opencivicdata.models.people_orgs import Person class Preferences(models.Model): user = models.OneToOneField(User, related_name='preferences') address = models.CharField(max_length=100, blank=True, null=True) lat = models.FloatField(null=True, blank=True) lon = models.FloatField(null=True, blank=True) rep_from_address = models.CharField(max_length=255, blank=True, null=True) sen_from_address = models.CharField(max_length=255, blank=True, null=True) apikey = models.UUIDField(default=uuid.uuid4) class PersonFollow(models.Model): user = models.ForeignKey(User, related_name='person_follows') person = models.ForeignKey(Person, related_name='follows') class TopicFollow(models.Model): user = models.ForeignKey(User, related_name='topic_follows') topic = models.CharField(max_length=100) class LocationFollow(models.Model): user = models.ForeignKey(User, related_name='location_follows') location = models.CharField(max_length=100)
import uuid from django.db import models from django.contrib.auth.models import User from opencivicdata.models.people_orgs import Person class Preferences(models.Model): user = models.OneToOneField(User, related_name='preferences') address = models.CharField(max_length=100, blank=True, null=True) lat = models.FloatField(null=True, blank=True) lon = models.FloatField(null=True, blank=True) + rep_from_address = models.CharField(max_length=255, blank=True, null=True) + sen_from_address = models.CharField(max_length=255, blank=True, null=True) apikey = models.UUIDField(default=uuid.uuid4) class PersonFollow(models.Model): user = models.ForeignKey(User, related_name='person_follows') person = models.ForeignKey(Person, related_name='follows') class TopicFollow(models.Model): user = models.ForeignKey(User, related_name='topic_follows') topic = models.CharField(max_length=100) class LocationFollow(models.Model): user = models.ForeignKey(User, related_name='location_follows') location = models.CharField(max_length=100)
2db6e8e294059847251feb9610c42180ae44e05b
fbone/appointment/views.py
fbone/appointment/views.py
from flask import (Blueprint, render_template, request, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, url_prefix='/appointment') @appointment.route('/create', methods=['GET', 'POST']) def create(): form = MakeAppointmentForm(formdata=request.args, next=request.args.get('next')) # Dump all available data from request or session object to form fields. for key in form.data.keys(): setattr(getattr(form, key), 'data', request.args.get(key) or session.get(key)) if form.validate_on_submit(): appointment = Appointment() form.populate_obj(appointment) db.session.add(appointment) db.session.commit() flash_message = """ Congratulations! You've just made an appointment on WPIC Web Calendar system, please check your email for details. """ flash(flash_message) return redirect(url_for('appointment.create')) return render_template('appointment/create.html', form=form)
from datetime import datetime from flask import (Blueprint, render_template, request, abort, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, url_prefix='/appointment') @appointment.route('/create', methods=['GET', 'POST']) def create(): if request.method == 'POST': form = MakeAppointmentForm(next=request.args.get('next')) if form.validate_on_submit(): appointment = Appointment() form.populate_obj(appointment) db.session.add(appointment) db.session.commit() flash_message = """ Congratulations! You've just made an appointment on WPIC Web Calendar system, please check your email for details. """ flash(flash_message) return redirect(url_for('appointment.create')) elif request.method == 'GET': form = MakeAppointmentForm(formdata=request.args, next=request.args.get('next')) # Dump all available data from request or session object to form # fields. for key in form.data.keys(): if key == "date": setattr(getattr(form, key), 'data', datetime.strptime(request.args.get(key) or session.get(key) or datetime.today().strftime('%Y-%m-%d'), "%Y-%m-%d")) else: setattr(getattr(form, key), 'data', request.args.get(key) or session.get(key)) return render_template('appointment/create.html', form=form) else: abort(405)
Fix some error about session.
Fix some error about session.
Python
bsd-3-clause
wpic/flask-appointment-calendar,wpic/flask-appointment-calendar
+ from datetime import datetime + - from flask import (Blueprint, render_template, request, + from flask import (Blueprint, render_template, request, abort, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, url_prefix='/appointment') @appointment.route('/create', methods=['GET', 'POST']) def create(): + if request.method == 'POST': - form = MakeAppointmentForm(formdata=request.args, + form = MakeAppointmentForm(next=request.args.get('next')) - next=request.args.get('next')) + if form.validate_on_submit(): + appointment = Appointment() + form.populate_obj(appointment) - # Dump all available data from request or session object to form fields. - for key in form.data.keys(): - setattr(getattr(form, key), 'data', - request.args.get(key) or session.get(key)) + db.session.add(appointment) + db.session.commit() - if form.validate_on_submit(): - appointment = Appointment() - form.populate_obj(appointment) - db.session.add(appointment) - db.session.commit() + flash_message = """ + Congratulations! You've just made an appointment + on WPIC Web Calendar system, please check your email for details. + """ + flash(flash_message) + return redirect(url_for('appointment.create')) - flash_message = """ - Congratulations! You've just made an appointment - on WPIC Web Calendar system, please check your email for details. - """ - flash(flash_message) - return redirect(url_for('appointment.create')) + elif request.method == 'GET': + form = MakeAppointmentForm(formdata=request.args, + next=request.args.get('next')) + # Dump all available data from request or session object to form + # fields. + for key in form.data.keys(): + if key == "date": + setattr(getattr(form, key), 'data', + datetime.strptime(request.args.get(key) or + session.get(key) or + datetime.today().strftime('%Y-%m-%d'), + "%Y-%m-%d")) + else: + setattr(getattr(form, key), 'data', + request.args.get(key) or session.get(key)) - return render_template('appointment/create.html', form=form) + return render_template('appointment/create.html', form=form) + else: + abort(405) +
Fix some error about session.
## Code Before: from flask import (Blueprint, render_template, request, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, url_prefix='/appointment') @appointment.route('/create', methods=['GET', 'POST']) def create(): form = MakeAppointmentForm(formdata=request.args, next=request.args.get('next')) # Dump all available data from request or session object to form fields. for key in form.data.keys(): setattr(getattr(form, key), 'data', request.args.get(key) or session.get(key)) if form.validate_on_submit(): appointment = Appointment() form.populate_obj(appointment) db.session.add(appointment) db.session.commit() flash_message = """ Congratulations! You've just made an appointment on WPIC Web Calendar system, please check your email for details. """ flash(flash_message) return redirect(url_for('appointment.create')) return render_template('appointment/create.html', form=form) ## Instruction: Fix some error about session. ## Code After: from datetime import datetime from flask import (Blueprint, render_template, request, abort, flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, url_prefix='/appointment') @appointment.route('/create', methods=['GET', 'POST']) def create(): if request.method == 'POST': form = MakeAppointmentForm(next=request.args.get('next')) if form.validate_on_submit(): appointment = Appointment() form.populate_obj(appointment) db.session.add(appointment) db.session.commit() flash_message = """ Congratulations! You've just made an appointment on WPIC Web Calendar system, please check your email for details. """ flash(flash_message) return redirect(url_for('appointment.create')) elif request.method == 'GET': form = MakeAppointmentForm(formdata=request.args, next=request.args.get('next')) # Dump all available data from request or session object to form # fields. for key in form.data.keys(): if key == "date": setattr(getattr(form, key), 'data', datetime.strptime(request.args.get(key) or session.get(key) or datetime.today().strftime('%Y-%m-%d'), "%Y-%m-%d")) else: setattr(getattr(form, key), 'data', request.args.get(key) or session.get(key)) return render_template('appointment/create.html', form=form) else: abort(405)
+ from datetime import datetime + - from flask import (Blueprint, render_template, request, + from flask import (Blueprint, render_template, request, abort, ? +++++++ flash, url_for, redirect, session) from flask.ext.mail import Message from ..extensions import db, mail from .forms import MakeAppointmentForm from .models import Appointment appointment = Blueprint('appointment', __name__, url_prefix='/appointment') @appointment.route('/create', methods=['GET', 'POST']) def create(): + if request.method == 'POST': - form = MakeAppointmentForm(formdata=request.args, ? ^^^^^^ - ^ + form = MakeAppointmentForm(next=request.args.get('next')) ? ++++ ^^^ ^^^^^^^^^^^^^ - next=request.args.get('next')) + if form.validate_on_submit(): + appointment = Appointment() + form.populate_obj(appointment) - # Dump all available data from request or session object to form fields. - for key in form.data.keys(): - setattr(getattr(form, key), 'data', - request.args.get(key) or session.get(key)) + db.session.add(appointment) + db.session.commit() - if form.validate_on_submit(): - appointment = Appointment() - form.populate_obj(appointment) - db.session.add(appointment) - db.session.commit() + flash_message = """ + Congratulations! You've just made an appointment + on WPIC Web Calendar system, please check your email for details. + """ + flash(flash_message) + return redirect(url_for('appointment.create')) - flash_message = """ - Congratulations! You've just made an appointment - on WPIC Web Calendar system, please check your email for details. - """ - flash(flash_message) - return redirect(url_for('appointment.create')) + elif request.method == 'GET': + form = MakeAppointmentForm(formdata=request.args, + next=request.args.get('next')) + # Dump all available data from request or session object to form + # fields. + for key in form.data.keys(): + if key == "date": + setattr(getattr(form, key), 'data', + datetime.strptime(request.args.get(key) or + session.get(key) or + datetime.today().strftime('%Y-%m-%d'), + "%Y-%m-%d")) + else: + setattr(getattr(form, key), 'data', + request.args.get(key) or session.get(key)) - return render_template('appointment/create.html', form=form) + return render_template('appointment/create.html', form=form) ? ++++ + + else: + abort(405)
7512f4b5fb5ebad5781e76ecd61c0e2d24b54f6c
projects/urls.py
projects/urls.py
from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() # Include any views from . import views urlpatterns = [ url(r'^$', views.index, name='projects'), url(r'^(?P<slug>.+)$', views.post, name='project'), ] # Blog URLs if 'projects' in settings.INSTALLED_APPS: urlpatterns += [ url(r'^projects/', include(projects.urls, app_name='projects', namespace='projects')), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='projects'), url(r'^(?P<slug>.+)', views.project, name='project'), ]
Add license statement, removed unused code, and set up the project URL mapping
Add license statement, removed unused code, and set up the project URL mapping
Python
agpl-3.0
lo-windigo/fragdev,lo-windigo/fragdev
- from django.conf import settings - from django.conf.urls import include, url - from django.views.generic import TemplateView - # Uncomment the next two lines to enable the admin: - from django.contrib import admin + from django.conf.urls import url - admin.autodiscover() - - # Include any views from . import views - urlpatterns = [ - url(r'^$', views.index, name='projects'), - url(r'^(?P<slug>.+)$', views.post, name='project'), + url(r'^(?P<slug>.+)', views.project, name='project'), ] - # Blog URLs - if 'projects' in settings.INSTALLED_APPS: - urlpatterns += [ - url(r'^projects/', include(projects.urls, app_name='projects', - namespace='projects')), - ] -
Add license statement, removed unused code, and set up the project URL mapping
## Code Before: from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() # Include any views from . import views urlpatterns = [ url(r'^$', views.index, name='projects'), url(r'^(?P<slug>.+)$', views.post, name='project'), ] # Blog URLs if 'projects' in settings.INSTALLED_APPS: urlpatterns += [ url(r'^projects/', include(projects.urls, app_name='projects', namespace='projects')), ] ## Instruction: Add license statement, removed unused code, and set up the project URL mapping ## Code After: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='projects'), url(r'^(?P<slug>.+)', views.project, name='project'), ]
- from django.conf import settings - from django.conf.urls import include, url - from django.views.generic import TemplateView - # Uncomment the next two lines to enable the admin: - from django.contrib import admin ? ^ ^^ ^^^^^ + from django.conf.urls import url ? ^^^ ^^ ^^^ - admin.autodiscover() - - # Include any views from . import views - urlpatterns = [ - url(r'^$', views.index, name='projects'), - url(r'^(?P<slug>.+)$', views.post, name='project'), ? - ^ + url(r'^(?P<slug>.+)', views.project, name='project'), ? + ^^^ ] - # Blog URLs - if 'projects' in settings.INSTALLED_APPS: - - urlpatterns += [ - url(r'^projects/', include(projects.urls, app_name='projects', - namespace='projects')), - ]
6a293fef25b5760d8b783ad0db1d00a3d5cf4e7f
packs/puppet/actions/lib/python_actions.py
packs/puppet/actions/lib/python_actions.py
from st2actions.runners.pythonrunner import Action from lib.puppet_client import PuppetHTTPAPIClient class PuppetBasePythonAction(Action): def __init__(self): super(PupperBasePythonAction, self).__init__() self.client = self._get_client() def _get_client(self): master_config = self.config['master'] auth_config = self.config['auth'] client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'], master_port=master_config['port'], client_cert_path=auth_config['client_cert_path'], client_cert_key_path=auth_config['client_cert_key_path'], ca_cert_path=auth_config['ca_cert_path']) return client
from st2actions.runners.pythonrunner import Action from lib.puppet_client import PuppetHTTPAPIClient class PuppetBasePythonAction(Action): def __init__(self, config): super(PuppetBasePythonAction, self).__init__(config=config) self.client = self._get_client() def _get_client(self): master_config = self.config['master'] auth_config = self.config['auth'] client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'], master_port=master_config['port'], client_cert_path=auth_config['client_cert_path'], client_cert_key_path=auth_config['client_cert_key_path'], ca_cert_path=auth_config['ca_cert_path']) return client
Update affected Puppet action constructor to take in "config" argument.
Update affected Puppet action constructor to take in "config" argument.
Python
apache-2.0
Aamir-raza-1/st2contrib,digideskio/st2contrib,dennybaa/st2contrib,armab/st2contrib,lmEshoo/st2contrib,armab/st2contrib,pearsontechnology/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,jtopjian/st2contrib,digideskio/st2contrib,pidah/st2contrib,tonybaloney/st2contrib,pinterb/st2contrib,StackStorm/st2contrib,lakshmi-kannan/st2contrib,Aamir-raza-1/st2contrib,StackStorm/st2contrib,tonybaloney/st2contrib,pinterb/st2contrib,pearsontechnology/st2contrib,pearsontechnology/st2contrib,psychopenguin/st2contrib,jtopjian/st2contrib,dennybaa/st2contrib,pidah/st2contrib,armab/st2contrib,lmEshoo/st2contrib,pidah/st2contrib,meirwah/st2contrib,StackStorm/st2contrib,lakshmi-kannan/st2contrib,meirwah/st2contrib,psychopenguin/st2contrib
from st2actions.runners.pythonrunner import Action from lib.puppet_client import PuppetHTTPAPIClient class PuppetBasePythonAction(Action): - def __init__(self): + def __init__(self, config): - super(PupperBasePythonAction, self).__init__() + super(PuppetBasePythonAction, self).__init__(config=config) self.client = self._get_client() def _get_client(self): master_config = self.config['master'] auth_config = self.config['auth'] client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'], master_port=master_config['port'], client_cert_path=auth_config['client_cert_path'], client_cert_key_path=auth_config['client_cert_key_path'], ca_cert_path=auth_config['ca_cert_path']) return client
Update affected Puppet action constructor to take in "config" argument.
## Code Before: from st2actions.runners.pythonrunner import Action from lib.puppet_client import PuppetHTTPAPIClient class PuppetBasePythonAction(Action): def __init__(self): super(PupperBasePythonAction, self).__init__() self.client = self._get_client() def _get_client(self): master_config = self.config['master'] auth_config = self.config['auth'] client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'], master_port=master_config['port'], client_cert_path=auth_config['client_cert_path'], client_cert_key_path=auth_config['client_cert_key_path'], ca_cert_path=auth_config['ca_cert_path']) return client ## Instruction: Update affected Puppet action constructor to take in "config" argument. ## Code After: from st2actions.runners.pythonrunner import Action from lib.puppet_client import PuppetHTTPAPIClient class PuppetBasePythonAction(Action): def __init__(self, config): super(PuppetBasePythonAction, self).__init__(config=config) self.client = self._get_client() def _get_client(self): master_config = self.config['master'] auth_config = self.config['auth'] client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'], master_port=master_config['port'], client_cert_path=auth_config['client_cert_path'], client_cert_key_path=auth_config['client_cert_key_path'], ca_cert_path=auth_config['ca_cert_path']) return client
from st2actions.runners.pythonrunner import Action from lib.puppet_client import PuppetHTTPAPIClient class PuppetBasePythonAction(Action): - def __init__(self): + def __init__(self, config): ? ++++++++ - super(PupperBasePythonAction, self).__init__() ? ^ + super(PuppetBasePythonAction, self).__init__(config=config) ? ^ +++++++++++++ self.client = self._get_client() def _get_client(self): master_config = self.config['master'] auth_config = self.config['auth'] client = PuppetHTTPAPIClient(master_hostname=master_config['hostname'], master_port=master_config['port'], client_cert_path=auth_config['client_cert_path'], client_cert_key_path=auth_config['client_cert_key_path'], ca_cert_path=auth_config['ca_cert_path']) return client
5006ba3124cd80a4529b9ed645aa8981d06a9886
publishconf.py
publishconf.py
from __future__ import unicode_literals # This file is only used if you use `make publish` or # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = '' RELATIVE_URLS = False FEED_ALL_ATOM = 'feeds/all.atom.xml' CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml' DELETE_OUTPUT_DIRECTORY = True # Following items are often useful when publishing #DISQUS_SITENAME = "" #GOOGLE_ANALYTICS = ""
import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = '' RELATIVE_URLS = False DELETE_OUTPUT_DIRECTORY = True # Following items are often useful when publishing #DISQUS_SITENAME = "" #GOOGLE_ANALYTICS = ""
Stop generate feeds when publishing
Stop generate feeds when publishing
Python
mit
andrewheiss/scorecarddiplomacy-org,andrewheiss/scorecarddiplomacy-org,andrewheiss/scorecarddiplomacy-org,andrewheiss/scorecarddiplomacy-org
- from __future__ import unicode_literals - - # This file is only used if you use `make publish` or - # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = '' RELATIVE_URLS = False - FEED_ALL_ATOM = 'feeds/all.atom.xml' - CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml' - DELETE_OUTPUT_DIRECTORY = True # Following items are often useful when publishing #DISQUS_SITENAME = "" #GOOGLE_ANALYTICS = ""
Stop generate feeds when publishing
## Code Before: from __future__ import unicode_literals # This file is only used if you use `make publish` or # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = '' RELATIVE_URLS = False FEED_ALL_ATOM = 'feeds/all.atom.xml' CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml' DELETE_OUTPUT_DIRECTORY = True # Following items are often useful when publishing #DISQUS_SITENAME = "" #GOOGLE_ANALYTICS = "" ## Instruction: Stop generate feeds when publishing ## Code After: import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = '' RELATIVE_URLS = False DELETE_OUTPUT_DIRECTORY = True # Following items are often useful when publishing #DISQUS_SITENAME = "" #GOOGLE_ANALYTICS = ""
- from __future__ import unicode_literals - - # This file is only used if you use `make publish` or - # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = '' RELATIVE_URLS = False - FEED_ALL_ATOM = 'feeds/all.atom.xml' - CATEGORY_FEED_ATOM = 'feeds/%s.atom.xml' - DELETE_OUTPUT_DIRECTORY = True # Following items are often useful when publishing #DISQUS_SITENAME = "" #GOOGLE_ANALYTICS = ""
aefa8a3d6d4c809c7e470b22a0c9fb2c0875ba8b
project/project/urls.py
project/project/urls.py
from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.contrib.auth import views urlpatterns = [ url( r'^silk/', include('silk.urls', namespace='silk', app_name='silk') ), url( r'^example_app/', include('example_app.urls', namespace='example_app', app_name='example_app') ), url(r'^admin/', include(admin.site.urls)), ] urlpatterns += [ url( r'^login/$', views.login, {'template_name': 'example_app/login.html'}, name='login'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.contrib.auth import views urlpatterns = [ url( r'^silk/', include('silk.urls', namespace='silk') ), url( r'^example_app/', include('example_app.urls', namespace='example_app') ), url( r'^admin/', admin.site.urls ), ] urlpatterns += [ url( r'^login/$', views.login, {'template_name': 'example_app/login.html'}, name='login'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Remove unneeded app_name from test project to be django 2 compatible
Remove unneeded app_name from test project to be django 2 compatible
Python
mit
crunchr/silk,mtford90/silk,jazzband/silk,crunchr/silk,mtford90/silk,jazzband/silk,crunchr/silk,django-silk/silk,django-silk/silk,jazzband/silk,django-silk/silk,crunchr/silk,mtford90/silk,jazzband/silk,mtford90/silk,django-silk/silk
from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.contrib.auth import views urlpatterns = [ url( r'^silk/', - include('silk.urls', namespace='silk', app_name='silk') + include('silk.urls', namespace='silk') ), url( r'^example_app/', - include('example_app.urls', namespace='example_app', app_name='example_app') + include('example_app.urls', namespace='example_app') ), - url(r'^admin/', include(admin.site.urls)), + url( + r'^admin/', + admin.site.urls + ), ] urlpatterns += [ url( r'^login/$', views.login, {'template_name': 'example_app/login.html'}, name='login'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Remove unneeded app_name from test project to be django 2 compatible
## Code Before: from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.contrib.auth import views urlpatterns = [ url( r'^silk/', include('silk.urls', namespace='silk', app_name='silk') ), url( r'^example_app/', include('example_app.urls', namespace='example_app', app_name='example_app') ), url(r'^admin/', include(admin.site.urls)), ] urlpatterns += [ url( r'^login/$', views.login, {'template_name': 'example_app/login.html'}, name='login'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ## Instruction: Remove unneeded app_name from test project to be django 2 compatible ## Code After: from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.contrib.auth import views urlpatterns = [ url( r'^silk/', include('silk.urls', namespace='silk') ), url( r'^example_app/', include('example_app.urls', namespace='example_app') ), url( r'^admin/', admin.site.urls ), ] urlpatterns += [ url( r'^login/$', views.login, {'template_name': 'example_app/login.html'}, name='login'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.static import static from django.contrib.auth import views urlpatterns = [ url( r'^silk/', - include('silk.urls', namespace='silk', app_name='silk') ? ----------------- + include('silk.urls', namespace='silk') ), url( r'^example_app/', - include('example_app.urls', namespace='example_app', app_name='example_app') ? ------------------------ + include('example_app.urls', namespace='example_app') ), - url(r'^admin/', include(admin.site.urls)), + url( + r'^admin/', + admin.site.urls + ), ] urlpatterns += [ url( r'^login/$', views.login, {'template_name': 'example_app/login.html'}, name='login'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + \ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
d565786278eaf32761957dd1e064a5d549ef3ab4
praw/models/reddit/mixins/savable.py
praw/models/reddit/mixins/savable.py
"""Provide the SavableMixin class.""" from ....const import API_PATH class SavableMixin(object): """Interface for RedditBase classes that can be saved.""" def save(self, category=None): """Save the object. :param category: The category to save to (Default: None). """ self._reddit.post(API_PATH['save'], data={'category': category, 'id': self.fullname}) def unsave(self): """Unsave the object.""" self._reddit.post(API_PATH['unsave'], data={'id': self.fullname})
"""Provide the SavableMixin class.""" from ....const import API_PATH class SavableMixin(object): """Interface for RedditBase classes that can be saved.""" def save(self, category=None): """Save the object. :param category: (Gold) The category to save to (Default: None). If your user does not have gold this value is ignored by Reddit. """ self._reddit.post(API_PATH['save'], data={'category': category, 'id': self.fullname}) def unsave(self): """Unsave the object.""" self._reddit.post(API_PATH['unsave'], data={'id': self.fullname})
Clarify that category is a gold feature for saving an item
Clarify that category is a gold feature for saving an item
Python
bsd-2-clause
13steinj/praw,RGood/praw,RGood/praw,darthkedrik/praw,darthkedrik/praw,leviroth/praw,gschizas/praw,leviroth/praw,gschizas/praw,praw-dev/praw,nmtake/praw,praw-dev/praw,nmtake/praw,13steinj/praw
"""Provide the SavableMixin class.""" from ....const import API_PATH class SavableMixin(object): """Interface for RedditBase classes that can be saved.""" def save(self, category=None): """Save the object. - :param category: The category to save to (Default: None). + :param category: (Gold) The category to save to (Default: + None). If your user does not have gold this value is ignored by + Reddit. """ self._reddit.post(API_PATH['save'], data={'category': category, 'id': self.fullname}) def unsave(self): """Unsave the object.""" self._reddit.post(API_PATH['unsave'], data={'id': self.fullname})
Clarify that category is a gold feature for saving an item
## Code Before: """Provide the SavableMixin class.""" from ....const import API_PATH class SavableMixin(object): """Interface for RedditBase classes that can be saved.""" def save(self, category=None): """Save the object. :param category: The category to save to (Default: None). """ self._reddit.post(API_PATH['save'], data={'category': category, 'id': self.fullname}) def unsave(self): """Unsave the object.""" self._reddit.post(API_PATH['unsave'], data={'id': self.fullname}) ## Instruction: Clarify that category is a gold feature for saving an item ## Code After: """Provide the SavableMixin class.""" from ....const import API_PATH class SavableMixin(object): """Interface for RedditBase classes that can be saved.""" def save(self, category=None): """Save the object. :param category: (Gold) The category to save to (Default: None). If your user does not have gold this value is ignored by Reddit. """ self._reddit.post(API_PATH['save'], data={'category': category, 'id': self.fullname}) def unsave(self): """Unsave the object.""" self._reddit.post(API_PATH['unsave'], data={'id': self.fullname})
"""Provide the SavableMixin class.""" from ....const import API_PATH class SavableMixin(object): """Interface for RedditBase classes that can be saved.""" def save(self, category=None): """Save the object. - :param category: The category to save to (Default: None). ? ------- + :param category: (Gold) The category to save to (Default: ? +++++++ + None). If your user does not have gold this value is ignored by + Reddit. """ self._reddit.post(API_PATH['save'], data={'category': category, 'id': self.fullname}) def unsave(self): """Unsave the object.""" self._reddit.post(API_PATH['unsave'], data={'id': self.fullname})
cc1e5bc1ae3b91973d9fa30ab8e0f9cb3c147a9e
ddt.py
ddt.py
from functools import wraps __version__ = '0.1.1' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): setattr(func, MAGIC, values) return func return wrapper def ddt(cls): """ Class decorator for subclasses of ``unittest.TestCase``. Apply this decorator to the test case class, and then decorate test methods with ``@data``. For each method decorated with ``@data``, this will effectively create as many methods as data items are passed as parameters to ``@data``. """ def feed_data(func, *args, **kwargs): """ This internal method decorator feeds the test data item to the test. """ @wraps(func) def wrapper(self): return func(self, *args, **kwargs) return wrapper for name, f in cls.__dict__.items(): if hasattr(f, MAGIC): i = 0 for v in getattr(f, MAGIC): setattr(cls, "{0}_{1}".format(name, v), feed_data(f, v)) i = i + 1 delattr(cls, name) return cls
from functools import wraps __version__ = '0.1.1' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): setattr(func, MAGIC, values) return func return wrapper def ddt(cls): """ Class decorator for subclasses of ``unittest.TestCase``. Apply this decorator to the test case class, and then decorate test methods with ``@data``. For each method decorated with ``@data``, this will effectively create as many methods as data items are passed as parameters to ``@data``. """ def feed_data(func, *args, **kwargs): """ This internal method decorator feeds the test data item to the test. """ @wraps(func) def wrapper(self): return func(self, *args, **kwargs) return wrapper for name, f in cls.__dict__.items(): if hasattr(f, MAGIC): i = 0 for v in getattr(f, MAGIC): test_name = getattr(v, "__name__", "{0}_{1}".format(name, v)) setattr(cls, test_name, feed_data(f, v)) i = i + 1 delattr(cls, name) return cls
Use __name__ from data object to set the test method name, if available.
Use __name__ from data object to set the test method name, if available. Allows to provide user-friendly names for the user instead of the default raw data formatting.
Python
mit
domidimi/ddt,edx/ddt,domidimi/ddt,datadriventests/ddt,edx/ddt,datadriventests/ddt
from functools import wraps __version__ = '0.1.1' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): setattr(func, MAGIC, values) return func return wrapper def ddt(cls): """ Class decorator for subclasses of ``unittest.TestCase``. Apply this decorator to the test case class, and then decorate test methods with ``@data``. For each method decorated with ``@data``, this will effectively create as many methods as data items are passed as parameters to ``@data``. """ def feed_data(func, *args, **kwargs): """ This internal method decorator feeds the test data item to the test. """ @wraps(func) def wrapper(self): return func(self, *args, **kwargs) return wrapper for name, f in cls.__dict__.items(): if hasattr(f, MAGIC): i = 0 for v in getattr(f, MAGIC): + test_name = getattr(v, "__name__", "{0}_{1}".format(name, v)) + setattr(cls, test_name, feed_data(f, v)) - setattr(cls, - "{0}_{1}".format(name, v), - feed_data(f, v)) i = i + 1 delattr(cls, name) return cls
Use __name__ from data object to set the test method name, if available.
## Code Before: from functools import wraps __version__ = '0.1.1' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): setattr(func, MAGIC, values) return func return wrapper def ddt(cls): """ Class decorator for subclasses of ``unittest.TestCase``. Apply this decorator to the test case class, and then decorate test methods with ``@data``. For each method decorated with ``@data``, this will effectively create as many methods as data items are passed as parameters to ``@data``. """ def feed_data(func, *args, **kwargs): """ This internal method decorator feeds the test data item to the test. """ @wraps(func) def wrapper(self): return func(self, *args, **kwargs) return wrapper for name, f in cls.__dict__.items(): if hasattr(f, MAGIC): i = 0 for v in getattr(f, MAGIC): setattr(cls, "{0}_{1}".format(name, v), feed_data(f, v)) i = i + 1 delattr(cls, name) return cls ## Instruction: Use __name__ from data object to set the test method name, if available. ## Code After: from functools import wraps __version__ = '0.1.1' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): setattr(func, MAGIC, values) return func return wrapper def ddt(cls): """ Class decorator for subclasses of ``unittest.TestCase``. Apply this decorator to the test case class, and then decorate test methods with ``@data``. For each method decorated with ``@data``, this will effectively create as many methods as data items are passed as parameters to ``@data``. """ def feed_data(func, *args, **kwargs): """ This internal method decorator feeds the test data item to the test. """ @wraps(func) def wrapper(self): return func(self, *args, **kwargs) return wrapper for name, f in cls.__dict__.items(): if hasattr(f, MAGIC): i = 0 for v in getattr(f, MAGIC): test_name = getattr(v, "__name__", "{0}_{1}".format(name, v)) setattr(cls, test_name, feed_data(f, v)) i = i + 1 delattr(cls, name) return cls
from functools import wraps __version__ = '0.1.1' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): setattr(func, MAGIC, values) return func return wrapper def ddt(cls): """ Class decorator for subclasses of ``unittest.TestCase``. Apply this decorator to the test case class, and then decorate test methods with ``@data``. For each method decorated with ``@data``, this will effectively create as many methods as data items are passed as parameters to ``@data``. """ def feed_data(func, *args, **kwargs): """ This internal method decorator feeds the test data item to the test. """ @wraps(func) def wrapper(self): return func(self, *args, **kwargs) return wrapper for name, f in cls.__dict__.items(): if hasattr(f, MAGIC): i = 0 for v in getattr(f, MAGIC): + test_name = getattr(v, "__name__", "{0}_{1}".format(name, v)) + setattr(cls, test_name, feed_data(f, v)) - setattr(cls, - "{0}_{1}".format(name, v), - feed_data(f, v)) i = i + 1 delattr(cls, name) return cls