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
4ed8f05fa43f29a1881a23ae99fdc3ad8cd661b0
grammpy/StringGrammar.py
grammpy/StringGrammar.py
from .RawGrammar import RawGrammar as Grammar class StringGrammar(Grammar): @staticmethod def __to_string_arr(t): if isinstance(t, str): return [t] return t def remove_term(self, term=None): return super().remove_term(StringGrammar.__to_string_arr(term)) def add_term(self, term): return super().add_term(StringGrammar.__to_string_arr(term)) def term(self, term=None): return super().term(StringGrammar.__to_string_arr(term)) def get_term(self, term=None): return super().get_term(StringGrammar.__to_string_arr(term)) def have_term(self, term): return super().have_term(StringGrammar.__to_string_arr(term))
from .RawGrammar import RawGrammar as Grammar class StringGrammar(Grammar): @staticmethod def __to_string_arr(t): if isinstance(t, str): return [t] return t def remove_term(self, term=None): return super().remove_term(StringGrammar.__to_string_arr(term)) def add_term(self, term): return super().add_term(StringGrammar.__to_string_arr(term)) def term(self, term=None): return super().term(StringGrammar.__to_string_arr(term)) def get_term(self, term=None): res = super().get_term(StringGrammar.__to_string_arr(term)) if isinstance(term, str): return res[0] return res def have_term(self, term): return super().have_term(StringGrammar.__to_string_arr(term))
Correct return of Terminal instance when parameter is string
Correct return of Terminal instance when parameter is string
Python
mit
PatrikValkovic/grammpy
from .RawGrammar import RawGrammar as Grammar class StringGrammar(Grammar): @staticmethod def __to_string_arr(t): if isinstance(t, str): return [t] return t def remove_term(self, term=None): return super().remove_term(StringGrammar.__to_string_arr(term)) def add_term(self, term): return super().add_term(StringGrammar.__to_string_arr(term)) def term(self, term=None): return super().term(StringGrammar.__to_string_arr(term)) def get_term(self, term=None): - return super().get_term(StringGrammar.__to_string_arr(term)) + res = super().get_term(StringGrammar.__to_string_arr(term)) + if isinstance(term, str): + return res[0] + return res def have_term(self, term): return super().have_term(StringGrammar.__to_string_arr(term))
Correct return of Terminal instance when parameter is string
## Code Before: from .RawGrammar import RawGrammar as Grammar class StringGrammar(Grammar): @staticmethod def __to_string_arr(t): if isinstance(t, str): return [t] return t def remove_term(self, term=None): return super().remove_term(StringGrammar.__to_string_arr(term)) def add_term(self, term): return super().add_term(StringGrammar.__to_string_arr(term)) def term(self, term=None): return super().term(StringGrammar.__to_string_arr(term)) def get_term(self, term=None): return super().get_term(StringGrammar.__to_string_arr(term)) def have_term(self, term): return super().have_term(StringGrammar.__to_string_arr(term)) ## Instruction: Correct return of Terminal instance when parameter is string ## Code After: from .RawGrammar import RawGrammar as Grammar class StringGrammar(Grammar): @staticmethod def __to_string_arr(t): if isinstance(t, str): return [t] return t def remove_term(self, term=None): return super().remove_term(StringGrammar.__to_string_arr(term)) def add_term(self, term): return super().add_term(StringGrammar.__to_string_arr(term)) def term(self, term=None): return super().term(StringGrammar.__to_string_arr(term)) def get_term(self, term=None): res = super().get_term(StringGrammar.__to_string_arr(term)) if isinstance(term, str): return res[0] return res def have_term(self, term): return super().have_term(StringGrammar.__to_string_arr(term))
from .RawGrammar import RawGrammar as Grammar class StringGrammar(Grammar): @staticmethod def __to_string_arr(t): if isinstance(t, str): return [t] return t def remove_term(self, term=None): return super().remove_term(StringGrammar.__to_string_arr(term)) def add_term(self, term): return super().add_term(StringGrammar.__to_string_arr(term)) def term(self, term=None): return super().term(StringGrammar.__to_string_arr(term)) def get_term(self, term=None): - return super().get_term(StringGrammar.__to_string_arr(term)) ? ^^^^ + res = super().get_term(StringGrammar.__to_string_arr(term)) ? ^^^ + if isinstance(term, str): + return res[0] + return res def have_term(self, term): return super().have_term(StringGrammar.__to_string_arr(term))
e0de6546fb58af113d18cf7e836407e3f8a1a985
contrib/bosco/bosco-cluster-remote-hosts.py
contrib/bosco/bosco-cluster-remote-hosts.py
import os import subprocess import sys try: import classad import htcondor except ImportError: sys.exit("ERROR: Could not load HTCondor Python bindings. " "Ensure the 'htcondor' and 'classad' are in PYTHONPATH") jre = classad.parseAds('JOB_ROUTER_ENTRIES') grs = ( x["GridResource"] for x in jre ) rhosts = ( x.split()[1:3] for x in grs ) for batchtype, rhost in rhosts: subprocess.call(['bosco_cluster', '-o', os.getenv("OVERRIDE_DIR"), rhost, batchtype])
import os import subprocess import sys try: import classad except ImportError: sys.exit("ERROR: Could not load HTCondor Python bindings. " "Ensure the 'htcondor' and 'classad' are in PYTHONPATH") jre = classad.parseAds('JOB_ROUTER_ENTRIES') grs = ( x["GridResource"] for x in jre ) rhosts = ( x.split()[1:3] for x in grs ) for batchtype, rhost in rhosts: subprocess.call(['bosco_cluster', '-o', os.getenv("OVERRIDE_DIR"), rhost, batchtype])
Delete unused import htcondor (SOFTWARE-4687)
Delete unused import htcondor (SOFTWARE-4687)
Python
apache-2.0
brianhlin/htcondor-ce,matyasselmeci/htcondor-ce,matyasselmeci/htcondor-ce,brianhlin/htcondor-ce,matyasselmeci/htcondor-ce,brianhlin/htcondor-ce
import os import subprocess import sys try: import classad - import htcondor except ImportError: sys.exit("ERROR: Could not load HTCondor Python bindings. " "Ensure the 'htcondor' and 'classad' are in PYTHONPATH") jre = classad.parseAds('JOB_ROUTER_ENTRIES') grs = ( x["GridResource"] for x in jre ) rhosts = ( x.split()[1:3] for x in grs ) for batchtype, rhost in rhosts: subprocess.call(['bosco_cluster', '-o', os.getenv("OVERRIDE_DIR"), rhost, batchtype])
Delete unused import htcondor (SOFTWARE-4687)
## Code Before: import os import subprocess import sys try: import classad import htcondor except ImportError: sys.exit("ERROR: Could not load HTCondor Python bindings. " "Ensure the 'htcondor' and 'classad' are in PYTHONPATH") jre = classad.parseAds('JOB_ROUTER_ENTRIES') grs = ( x["GridResource"] for x in jre ) rhosts = ( x.split()[1:3] for x in grs ) for batchtype, rhost in rhosts: subprocess.call(['bosco_cluster', '-o', os.getenv("OVERRIDE_DIR"), rhost, batchtype]) ## Instruction: Delete unused import htcondor (SOFTWARE-4687) ## Code After: import os import subprocess import sys try: import classad except ImportError: sys.exit("ERROR: Could not load HTCondor Python bindings. " "Ensure the 'htcondor' and 'classad' are in PYTHONPATH") jre = classad.parseAds('JOB_ROUTER_ENTRIES') grs = ( x["GridResource"] for x in jre ) rhosts = ( x.split()[1:3] for x in grs ) for batchtype, rhost in rhosts: subprocess.call(['bosco_cluster', '-o', os.getenv("OVERRIDE_DIR"), rhost, batchtype])
import os import subprocess import sys try: import classad - import htcondor except ImportError: sys.exit("ERROR: Could not load HTCondor Python bindings. " "Ensure the 'htcondor' and 'classad' are in PYTHONPATH") jre = classad.parseAds('JOB_ROUTER_ENTRIES') grs = ( x["GridResource"] for x in jre ) rhosts = ( x.split()[1:3] for x in grs ) for batchtype, rhost in rhosts: subprocess.call(['bosco_cluster', '-o', os.getenv("OVERRIDE_DIR"), rhost, batchtype])
15996286496d913c25290362ba2dba2d349bd5f6
imageManagerUtils/settings.py
imageManagerUtils/settings.py
import os import sys import subprocess # This path is the location of the caller script MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) # Set up the path to settings.sh settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh') if not os.path.isfile(settings_path): print('Cannot find settings.sh in ' + MAIN_SCRIPT_PATH) exit(1) # This is a tricky way to read bash envs in the script env_str = subprocess.check_output('source {} && env'.format(settings_path), shell=True) # Transform to list of python strings (utf-8 encodings) env_str = env_str.decode('utf-8').split('\n') # Transform from a list to a list of pairs and filter out invalid formats env_list = [kv.split('=') for kv in env_str if len(kv.split('=')) == 2] # Transform from a list to a dictionary env_dict = {kv[0]: kv[1] for kv in env_list} # Update the os.environ globally os.environ.update(env_dict)
import os import sys import subprocess # This path is the location of the caller script MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) # Set up the path to settings.sh settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh') if not os.path.isfile(settings_path): print('Cannot find settings.sh in ' + MAIN_SCRIPT_PATH) exit(1) # This is a tricky way to read bash envs in the script env_str = subprocess.check_output('source {} && env'.format(settings_path), shell=True, executable='/bin/bash') # Transform to list of python strings (utf-8 encodings) env_str = env_str.decode('utf-8').split('\n') # Transform from a list to a list of pairs and filter out invalid formats env_list = [kv.split('=') for kv in env_str if len(kv.split('=')) == 2] # Transform from a list to a dictionary env_dict = {kv[0]: kv[1] for kv in env_list} # Update the os.environ globally os.environ.update(env_dict)
Fix bug of invoking /bin/sh on several OSs
Fix bug of invoking /bin/sh on several OSs
Python
mit
snippits/qemu_image,snippits/qemu_image,snippits/qemu_image
import os import sys import subprocess # This path is the location of the caller script MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) # Set up the path to settings.sh settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh') if not os.path.isfile(settings_path): print('Cannot find settings.sh in ' + MAIN_SCRIPT_PATH) exit(1) # This is a tricky way to read bash envs in the script - env_str = subprocess.check_output('source {} && env'.format(settings_path), shell=True) + env_str = subprocess.check_output('source {} && env'.format(settings_path), shell=True, executable='/bin/bash') # Transform to list of python strings (utf-8 encodings) env_str = env_str.decode('utf-8').split('\n') # Transform from a list to a list of pairs and filter out invalid formats env_list = [kv.split('=') for kv in env_str if len(kv.split('=')) == 2] # Transform from a list to a dictionary env_dict = {kv[0]: kv[1] for kv in env_list} # Update the os.environ globally os.environ.update(env_dict)
Fix bug of invoking /bin/sh on several OSs
## Code Before: import os import sys import subprocess # This path is the location of the caller script MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) # Set up the path to settings.sh settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh') if not os.path.isfile(settings_path): print('Cannot find settings.sh in ' + MAIN_SCRIPT_PATH) exit(1) # This is a tricky way to read bash envs in the script env_str = subprocess.check_output('source {} && env'.format(settings_path), shell=True) # Transform to list of python strings (utf-8 encodings) env_str = env_str.decode('utf-8').split('\n') # Transform from a list to a list of pairs and filter out invalid formats env_list = [kv.split('=') for kv in env_str if len(kv.split('=')) == 2] # Transform from a list to a dictionary env_dict = {kv[0]: kv[1] for kv in env_list} # Update the os.environ globally os.environ.update(env_dict) ## Instruction: Fix bug of invoking /bin/sh on several OSs ## Code After: import os import sys import subprocess # This path is the location of the caller script MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) # Set up the path to settings.sh settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh') if not os.path.isfile(settings_path): print('Cannot find settings.sh in ' + MAIN_SCRIPT_PATH) exit(1) # This is a tricky way to read bash envs in the script env_str = subprocess.check_output('source {} && env'.format(settings_path), shell=True, executable='/bin/bash') # Transform to list of python strings (utf-8 encodings) env_str = env_str.decode('utf-8').split('\n') # Transform from a list to a list of pairs and filter out invalid formats env_list = [kv.split('=') for kv in env_str if len(kv.split('=')) == 2] # Transform from a list to a dictionary env_dict = {kv[0]: kv[1] for kv in env_list} # Update the os.environ globally os.environ.update(env_dict)
import os import sys import subprocess # This path is the location of the caller script MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) # Set up the path to settings.sh settings_path = os.path.join(MAIN_SCRIPT_PATH, 'settings.sh') if not os.path.isfile(settings_path): print('Cannot find settings.sh in ' + MAIN_SCRIPT_PATH) exit(1) # This is a tricky way to read bash envs in the script - env_str = subprocess.check_output('source {} && env'.format(settings_path), shell=True) + env_str = subprocess.check_output('source {} && env'.format(settings_path), shell=True, executable='/bin/bash') ? ++++++++++++++++++++++++ # Transform to list of python strings (utf-8 encodings) env_str = env_str.decode('utf-8').split('\n') # Transform from a list to a list of pairs and filter out invalid formats env_list = [kv.split('=') for kv in env_str if len(kv.split('=')) == 2] # Transform from a list to a dictionary env_dict = {kv[0]: kv[1] for kv in env_list} # Update the os.environ globally os.environ.update(env_dict)
cddb0ae5c9c2d96c5902943f8b341ab2b698235f
paveldedik/forms.py
paveldedik/forms.py
from flask.ext.mongoengine.wtf import model_form from paveldedik.models import User, Post post_args = { 'title': {'label': u'Title'}, 'leading': {'label': u'Leading'}, 'content': {'label': u'Content'}, } UserForm = model_form(User) PostForm = model_form(Post, field_args=post_args)
from flask.ext.mongoengine.wtf import model_form from paveldedik.models import User, Post #: Model the user form. Additional field arguments can be included using #: the key-word argument ``field_args``. For more information about using #: WTForms follow `this link<http://flask.pocoo.org/snippets/60/>`_. UserForm = model_form(User) #: Model the post form. The attribute ``post_is`` must be excluded so that #: the field is not required during form validation and it is not rewritten #: when calling `populate_obj` on the :class:`models.Post` instance. PostForm = model_form(Post, exclude=['post_id'])
Exclude post_id from the wtform.
Exclude post_id from the wtform.
Python
mit
paveldedik/blog,paveldedik/blog
from flask.ext.mongoengine.wtf import model_form from paveldedik.models import User, Post + #: Model the user form. Additional field arguments can be included using + #: the key-word argument ``field_args``. For more information about using + #: WTForms follow `this link<http://flask.pocoo.org/snippets/60/>`_. - post_args = { - 'title': {'label': u'Title'}, - 'leading': {'label': u'Leading'}, - 'content': {'label': u'Content'}, - } - - UserForm = model_form(User) + #: Model the post form. The attribute ``post_is`` must be excluded so that + #: the field is not required during form validation and it is not rewritten + #: when calling `populate_obj` on the :class:`models.Post` instance. - PostForm = model_form(Post, field_args=post_args) + PostForm = model_form(Post, exclude=['post_id'])
Exclude post_id from the wtform.
## Code Before: from flask.ext.mongoengine.wtf import model_form from paveldedik.models import User, Post post_args = { 'title': {'label': u'Title'}, 'leading': {'label': u'Leading'}, 'content': {'label': u'Content'}, } UserForm = model_form(User) PostForm = model_form(Post, field_args=post_args) ## Instruction: Exclude post_id from the wtform. ## Code After: from flask.ext.mongoengine.wtf import model_form from paveldedik.models import User, Post #: Model the user form. Additional field arguments can be included using #: the key-word argument ``field_args``. For more information about using #: WTForms follow `this link<http://flask.pocoo.org/snippets/60/>`_. UserForm = model_form(User) #: Model the post form. The attribute ``post_is`` must be excluded so that #: the field is not required during form validation and it is not rewritten #: when calling `populate_obj` on the :class:`models.Post` instance. PostForm = model_form(Post, exclude=['post_id'])
from flask.ext.mongoengine.wtf import model_form from paveldedik.models import User, Post + #: Model the user form. Additional field arguments can be included using + #: the key-word argument ``field_args``. For more information about using + #: WTForms follow `this link<http://flask.pocoo.org/snippets/60/>`_. - post_args = { - 'title': {'label': u'Title'}, - 'leading': {'label': u'Leading'}, - 'content': {'label': u'Content'}, - } - - UserForm = model_form(User) + #: Model the post form. The attribute ``post_is`` must be excluded so that + #: the field is not required during form validation and it is not rewritten + #: when calling `populate_obj` on the :class:`models.Post` instance. - PostForm = model_form(Post, field_args=post_args) ? -- ^^^^^ ^^^^ + PostForm = model_form(Post, exclude=['post_id']) ? ++ + ^ ++ ^^^^
5f688e5a99c2e4ec476f28306c2cca375934bba7
nvidia_commands_layer.py
nvidia_commands_layer.py
import subprocess class NvidiaCommandsLayerException(Exception): pass class NvidiaCommandsLayer(object): @staticmethod def set_fan_percentage( value: int ) -> None: if value < 0 or value > 100: raise NvidiaCommandsLayerException('Cannot set a value outside 0 - 100') result = subprocess.run( [ 'nvidia-settings', '-a', '"[gpu:0]/GPUFanControlState=1"', '-a', '"[fan:0]/GPUTargetFanSpeed={}"'.format(value) ], stdout=subprocess.PIPE ) if result.returncode != 0: raise NvidiaCommandsLayerException('Could not set the fan speed') @staticmethod def read_temperature( ) -> int: result = subprocess.run( [ 'nvidia-smi', '--query-gpu=temperature.gpu', '--format=csv,noheader,nounits' ], stdout=subprocess.PIPE ) if result.returncode == 0: # the result is a string with a '\n' at the end, convert it to a decimal return int(result.stdout[:-1]) else: raise NvidiaCommandsLayerException('Could not read the temperature')
import subprocess class NvidiaCommandsLayerException(Exception): pass class NvidiaCommandsLayer(object): @staticmethod def set_fan_percentage( value: int ) -> None: if value < 0 or value > 100: raise NvidiaCommandsLayerException('Cannot set a value outside 0 - 100') result = subprocess.run( 'nvidia-settings ' '-a "[gpu:0]/GPUFanControlState=1" ' '-a "[fan:0]/GPUTargetFanSpeed={}"'.format(value), stdout=subprocess.PIPE, shell=True ) if result.returncode != 0: raise NvidiaCommandsLayerException('Could not set the fan speed') @staticmethod def read_temperature( ) -> int: result = subprocess.run( [ 'nvidia-smi', '--query-gpu=temperature.gpu', '--format=csv,noheader,nounits' ], stdout=subprocess.PIPE ) if result.returncode == 0: # the result is a string with a '\n' at the end, convert it to a decimal return int(result.stdout[:-1]) else: raise NvidiaCommandsLayerException('Could not read the temperature')
Fix script not working from bash
Fix script not working from bash
Python
mit
radu-nedelcu/nvidia-fan-controller,radu-nedelcu/nvidia-fan-controller
import subprocess class NvidiaCommandsLayerException(Exception): pass class NvidiaCommandsLayer(object): @staticmethod def set_fan_percentage( value: int ) -> None: if value < 0 or value > 100: raise NvidiaCommandsLayerException('Cannot set a value outside 0 - 100') result = subprocess.run( - [ - 'nvidia-settings', + 'nvidia-settings ' - '-a', - '"[gpu:0]/GPUFanControlState=1"', + '-a "[gpu:0]/GPUFanControlState=1" ' - '-a', - '"[fan:0]/GPUTargetFanSpeed={}"'.format(value) + '-a "[fan:0]/GPUTargetFanSpeed={}"'.format(value), - ], - stdout=subprocess.PIPE + stdout=subprocess.PIPE, + shell=True ) if result.returncode != 0: raise NvidiaCommandsLayerException('Could not set the fan speed') @staticmethod def read_temperature( ) -> int: result = subprocess.run( [ 'nvidia-smi', '--query-gpu=temperature.gpu', '--format=csv,noheader,nounits' ], stdout=subprocess.PIPE ) if result.returncode == 0: # the result is a string with a '\n' at the end, convert it to a decimal return int(result.stdout[:-1]) else: raise NvidiaCommandsLayerException('Could not read the temperature')
Fix script not working from bash
## Code Before: import subprocess class NvidiaCommandsLayerException(Exception): pass class NvidiaCommandsLayer(object): @staticmethod def set_fan_percentage( value: int ) -> None: if value < 0 or value > 100: raise NvidiaCommandsLayerException('Cannot set a value outside 0 - 100') result = subprocess.run( [ 'nvidia-settings', '-a', '"[gpu:0]/GPUFanControlState=1"', '-a', '"[fan:0]/GPUTargetFanSpeed={}"'.format(value) ], stdout=subprocess.PIPE ) if result.returncode != 0: raise NvidiaCommandsLayerException('Could not set the fan speed') @staticmethod def read_temperature( ) -> int: result = subprocess.run( [ 'nvidia-smi', '--query-gpu=temperature.gpu', '--format=csv,noheader,nounits' ], stdout=subprocess.PIPE ) if result.returncode == 0: # the result is a string with a '\n' at the end, convert it to a decimal return int(result.stdout[:-1]) else: raise NvidiaCommandsLayerException('Could not read the temperature') ## Instruction: Fix script not working from bash ## Code After: import subprocess class NvidiaCommandsLayerException(Exception): pass class NvidiaCommandsLayer(object): @staticmethod def set_fan_percentage( value: int ) -> None: if value < 0 or value > 100: raise NvidiaCommandsLayerException('Cannot set a value outside 0 - 100') result = subprocess.run( 'nvidia-settings ' '-a "[gpu:0]/GPUFanControlState=1" ' '-a "[fan:0]/GPUTargetFanSpeed={}"'.format(value), stdout=subprocess.PIPE, shell=True ) if result.returncode != 0: raise NvidiaCommandsLayerException('Could not set the fan speed') @staticmethod def read_temperature( ) -> int: result = subprocess.run( [ 'nvidia-smi', '--query-gpu=temperature.gpu', '--format=csv,noheader,nounits' ], stdout=subprocess.PIPE ) if result.returncode == 0: # the result is a string with a '\n' at the end, convert it to a decimal return int(result.stdout[:-1]) else: raise NvidiaCommandsLayerException('Could not read the temperature')
import subprocess class NvidiaCommandsLayerException(Exception): pass class NvidiaCommandsLayer(object): @staticmethod def set_fan_percentage( value: int ) -> None: if value < 0 or value > 100: raise NvidiaCommandsLayerException('Cannot set a value outside 0 - 100') result = subprocess.run( - [ - 'nvidia-settings', ? ----- - + 'nvidia-settings ' ? + - '-a', - '"[gpu:0]/GPUFanControlState=1"', ? ------ - + '-a "[gpu:0]/GPUFanControlState=1" ' ? +++ + - '-a', - '"[fan:0]/GPUTargetFanSpeed={}"'.format(value) ? ------ + '-a "[fan:0]/GPUTargetFanSpeed={}"'.format(value), ? +++ + - ], - stdout=subprocess.PIPE + stdout=subprocess.PIPE, ? + + shell=True ) if result.returncode != 0: raise NvidiaCommandsLayerException('Could not set the fan speed') @staticmethod def read_temperature( ) -> int: result = subprocess.run( [ 'nvidia-smi', '--query-gpu=temperature.gpu', '--format=csv,noheader,nounits' ], stdout=subprocess.PIPE ) if result.returncode == 0: # the result is a string with a '\n' at the end, convert it to a decimal return int(result.stdout[:-1]) else: raise NvidiaCommandsLayerException('Could not read the temperature')
7f974b87c278ef009535271461b5e49686057a9a
avatar/management/commands/rebuild_avatars.py
avatar/management/commands/rebuild_avatars.py
from django.core.management.base import NoArgsCommand from avatar.conf import settings from avatar.models import Avatar class Command(NoArgsCommand): help = ("Regenerates avatar thumbnails for the sizes specified in " "settings.AVATAR_AUTO_GENERATE_SIZES.") def handle_noargs(self, **options): for avatar in Avatar.objects.all(): for size in settings.AVATAR_AUTO_GENERATE_SIZES: if options['verbosity'] != 0: print("Rebuilding Avatar id=%s at size %s." % (avatar.id, size)) avatar.create_thumbnail(size)
from django.core.management.base import BaseCommand from avatar.conf import settings from avatar.models import Avatar class Command(BaseCommand): help = ("Regenerates avatar thumbnails for the sizes specified in " "settings.AVATAR_AUTO_GENERATE_SIZES.") def handle(self, *args, **options): for avatar in Avatar.objects.all(): for size in settings.AVATAR_AUTO_GENERATE_SIZES: if options['verbosity'] != 0: print("Rebuilding Avatar id=%s at size %s." % (avatar.id, size)) avatar.create_thumbnail(size)
Fix for django >= 1.10
Fix for django >= 1.10 The class django.core.management.NoArgsCommand is removed.
Python
bsd-3-clause
grantmcconnaughey/django-avatar,jezdez/django-avatar,grantmcconnaughey/django-avatar,ad-m/django-avatar,ad-m/django-avatar,jezdez/django-avatar
- from django.core.management.base import NoArgsCommand + from django.core.management.base import BaseCommand from avatar.conf import settings from avatar.models import Avatar - class Command(NoArgsCommand): + class Command(BaseCommand): help = ("Regenerates avatar thumbnails for the sizes specified in " "settings.AVATAR_AUTO_GENERATE_SIZES.") - def handle_noargs(self, **options): + def handle(self, *args, **options): for avatar in Avatar.objects.all(): for size in settings.AVATAR_AUTO_GENERATE_SIZES: if options['verbosity'] != 0: print("Rebuilding Avatar id=%s at size %s." % (avatar.id, size)) avatar.create_thumbnail(size)
Fix for django >= 1.10
## Code Before: from django.core.management.base import NoArgsCommand from avatar.conf import settings from avatar.models import Avatar class Command(NoArgsCommand): help = ("Regenerates avatar thumbnails for the sizes specified in " "settings.AVATAR_AUTO_GENERATE_SIZES.") def handle_noargs(self, **options): for avatar in Avatar.objects.all(): for size in settings.AVATAR_AUTO_GENERATE_SIZES: if options['verbosity'] != 0: print("Rebuilding Avatar id=%s at size %s." % (avatar.id, size)) avatar.create_thumbnail(size) ## Instruction: Fix for django >= 1.10 ## Code After: from django.core.management.base import BaseCommand from avatar.conf import settings from avatar.models import Avatar class Command(BaseCommand): help = ("Regenerates avatar thumbnails for the sizes specified in " "settings.AVATAR_AUTO_GENERATE_SIZES.") def handle(self, *args, **options): for avatar in Avatar.objects.all(): for size in settings.AVATAR_AUTO_GENERATE_SIZES: if options['verbosity'] != 0: print("Rebuilding Avatar id=%s at size %s." % (avatar.id, size)) avatar.create_thumbnail(size)
- from django.core.management.base import NoArgsCommand ? ^^^^^ + from django.core.management.base import BaseCommand ? ^^ + from avatar.conf import settings from avatar.models import Avatar - class Command(NoArgsCommand): ? ^^^^^ + class Command(BaseCommand): ? ^^ + help = ("Regenerates avatar thumbnails for the sizes specified in " "settings.AVATAR_AUTO_GENERATE_SIZES.") - def handle_noargs(self, **options): ? ------- + def handle(self, *args, **options): ? +++++++ for avatar in Avatar.objects.all(): for size in settings.AVATAR_AUTO_GENERATE_SIZES: if options['verbosity'] != 0: print("Rebuilding Avatar id=%s at size %s." % (avatar.id, size)) avatar.create_thumbnail(size)
3026d78dc6e2a0f6f391819370f2369df94e77eb
ckanext/nhm/settings.py
ckanext/nhm/settings.py
from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this list as a source for options COLLECTION_CONTACTS = OrderedDict([ ('Data Portal / Other', 'data@nhm.ac.uk'), ('Algae, Fungi & Plants', 'm.carine@nhm.ac.uk'), ('Economic & Environmental Earth Sciences', 'g.miller@nhm.ac.uk'), ('Fossil Invertebrates & Plants', 'z.hughes@nhm.ac.uk'), ('Fossil Vertebrates & Anthropology', 'm.richter@nhm.ac.uk'), ('Insects', 'g.broad@nhm.ac.uk'), ('Invertebrates', 'm.lowe@nhm.ac.uk'), ('Library & Archives', 'library@nhm.ac.uk'), ('Mineral & Planetary Sciences', 'm.rumsey@nhm.ac.uk'), ('Vertebrates', 'simon.loader@nhm.ac.uk'), ])
from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this list as a source for options COLLECTION_CONTACTS = OrderedDict([ ('Algae, Fungi & Plants', 'm.carine@nhm.ac.uk'), ('Economic & Environmental Earth Sciences', 'g.miller@nhm.ac.uk'), ('Fossil Invertebrates & Plants', 'z.hughes@nhm.ac.uk'), ('Fossil Vertebrates & Anthropology', 'm.richter@nhm.ac.uk'), ('Insects', 'g.broad@nhm.ac.uk'), ('Invertebrates', 'm.lowe@nhm.ac.uk'), ('Library & Archives', 'library@nhm.ac.uk'), ('Mineral & Planetary Sciences', 'm.rumsey@nhm.ac.uk'), ('Vertebrates', 'simon.loader@nhm.ac.uk'), ('Data Portal / Other', 'data@nhm.ac.uk'), ])
Move Data Portal / Other to bottom of contact select
Move Data Portal / Other to bottom of contact select
Python
mit
NaturalHistoryMuseum/ckanext-nhm,NaturalHistoryMuseum/ckanext-nhm,NaturalHistoryMuseum/ckanext-nhm
from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this list as a source for options COLLECTION_CONTACTS = OrderedDict([ - ('Data Portal / Other', 'data@nhm.ac.uk'), ('Algae, Fungi & Plants', 'm.carine@nhm.ac.uk'), ('Economic & Environmental Earth Sciences', 'g.miller@nhm.ac.uk'), ('Fossil Invertebrates & Plants', 'z.hughes@nhm.ac.uk'), ('Fossil Vertebrates & Anthropology', 'm.richter@nhm.ac.uk'), ('Insects', 'g.broad@nhm.ac.uk'), ('Invertebrates', 'm.lowe@nhm.ac.uk'), ('Library & Archives', 'library@nhm.ac.uk'), ('Mineral & Planetary Sciences', 'm.rumsey@nhm.ac.uk'), ('Vertebrates', 'simon.loader@nhm.ac.uk'), + ('Data Portal / Other', 'data@nhm.ac.uk'), ])
Move Data Portal / Other to bottom of contact select
## Code Before: from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this list as a source for options COLLECTION_CONTACTS = OrderedDict([ ('Data Portal / Other', 'data@nhm.ac.uk'), ('Algae, Fungi & Plants', 'm.carine@nhm.ac.uk'), ('Economic & Environmental Earth Sciences', 'g.miller@nhm.ac.uk'), ('Fossil Invertebrates & Plants', 'z.hughes@nhm.ac.uk'), ('Fossil Vertebrates & Anthropology', 'm.richter@nhm.ac.uk'), ('Insects', 'g.broad@nhm.ac.uk'), ('Invertebrates', 'm.lowe@nhm.ac.uk'), ('Library & Archives', 'library@nhm.ac.uk'), ('Mineral & Planetary Sciences', 'm.rumsey@nhm.ac.uk'), ('Vertebrates', 'simon.loader@nhm.ac.uk'), ]) ## Instruction: Move Data Portal / Other to bottom of contact select ## Code After: from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this list as a source for options COLLECTION_CONTACTS = OrderedDict([ ('Algae, Fungi & Plants', 'm.carine@nhm.ac.uk'), ('Economic & Environmental Earth Sciences', 'g.miller@nhm.ac.uk'), ('Fossil Invertebrates & Plants', 'z.hughes@nhm.ac.uk'), ('Fossil Vertebrates & Anthropology', 'm.richter@nhm.ac.uk'), ('Insects', 'g.broad@nhm.ac.uk'), ('Invertebrates', 'm.lowe@nhm.ac.uk'), ('Library & Archives', 'library@nhm.ac.uk'), ('Mineral & Planetary Sciences', 'm.rumsey@nhm.ac.uk'), ('Vertebrates', 'simon.loader@nhm.ac.uk'), ('Data Portal / Other', 'data@nhm.ac.uk'), ])
from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this list as a source for options COLLECTION_CONTACTS = OrderedDict([ - ('Data Portal / Other', 'data@nhm.ac.uk'), ('Algae, Fungi & Plants', 'm.carine@nhm.ac.uk'), ('Economic & Environmental Earth Sciences', 'g.miller@nhm.ac.uk'), ('Fossil Invertebrates & Plants', 'z.hughes@nhm.ac.uk'), ('Fossil Vertebrates & Anthropology', 'm.richter@nhm.ac.uk'), ('Insects', 'g.broad@nhm.ac.uk'), ('Invertebrates', 'm.lowe@nhm.ac.uk'), ('Library & Archives', 'library@nhm.ac.uk'), ('Mineral & Planetary Sciences', 'm.rumsey@nhm.ac.uk'), ('Vertebrates', 'simon.loader@nhm.ac.uk'), + ('Data Portal / Other', 'data@nhm.ac.uk'), ])
6f80a7e5f8dea031db1c7cc676f8c96faf5fc458
test/test_links.py
test/test_links.py
import pytest @pytest.mark.parametrize("name, linked_to", [ ("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"), ("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"), ("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"), ("/home/wicksy/.aws", "/git/wicksy/configfiles/dotfiles/.aws"), ("/home/wicksy/.config", "/git/wicksy/configfiles/dotfiles/.config"), ("/home/wicksy/.gitconfig", "/git/wicksy/configfiles/dotfiles/.gitconfig"), ("/home/wicksy/.ssh/config", "/git/wicksy/configfiles/dotfiles/.ssh/config"), ]) def test_links(File, name, linked_to): assert File(name).exists assert File(name).is_symlink assert File(name).linked_to == str(linked_to)
import pytest @pytest.mark.parametrize("name, linked_to", [ ("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"), ("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"), ("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"), ("/home/wicksy/.aws", "/git/wicksy/configfiles/dotfiles/.aws"), ("/home/wicksy/.config", "/git/wicksy/configfiles/dotfiles/.config"), ("/home/wicksy/.gitconfig", "/git/wicksy/configfiles/dotfiles/.gitconfig"), ("/home/wicksy/.ssh/config", "/git/wicksy/configfiles/dotfiles/.ssh/config"), ]) def test_links(host, name, linked_to): file = host.file(name) assert file.exists assert file.is_symlink assert file.linked_to == str(linked_to)
Change test function as existing method deprecated
Change test function as existing method deprecated
Python
mit
wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build,wicksy/laptop-build
import pytest @pytest.mark.parametrize("name, linked_to", [ ("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"), ("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"), ("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"), ("/home/wicksy/.aws", "/git/wicksy/configfiles/dotfiles/.aws"), ("/home/wicksy/.config", "/git/wicksy/configfiles/dotfiles/.config"), ("/home/wicksy/.gitconfig", "/git/wicksy/configfiles/dotfiles/.gitconfig"), ("/home/wicksy/.ssh/config", "/git/wicksy/configfiles/dotfiles/.ssh/config"), ]) - def test_links(File, name, linked_to): + def test_links(host, name, linked_to): + file = host.file(name) - assert File(name).exists + assert file.exists - assert File(name).is_symlink + assert file.is_symlink - assert File(name).linked_to == str(linked_to) + assert file.linked_to == str(linked_to)
Change test function as existing method deprecated
## Code Before: import pytest @pytest.mark.parametrize("name, linked_to", [ ("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"), ("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"), ("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"), ("/home/wicksy/.aws", "/git/wicksy/configfiles/dotfiles/.aws"), ("/home/wicksy/.config", "/git/wicksy/configfiles/dotfiles/.config"), ("/home/wicksy/.gitconfig", "/git/wicksy/configfiles/dotfiles/.gitconfig"), ("/home/wicksy/.ssh/config", "/git/wicksy/configfiles/dotfiles/.ssh/config"), ]) def test_links(File, name, linked_to): assert File(name).exists assert File(name).is_symlink assert File(name).linked_to == str(linked_to) ## Instruction: Change test function as existing method deprecated ## Code After: import pytest @pytest.mark.parametrize("name, linked_to", [ ("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"), ("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"), ("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"), ("/home/wicksy/.aws", "/git/wicksy/configfiles/dotfiles/.aws"), ("/home/wicksy/.config", "/git/wicksy/configfiles/dotfiles/.config"), ("/home/wicksy/.gitconfig", "/git/wicksy/configfiles/dotfiles/.gitconfig"), ("/home/wicksy/.ssh/config", "/git/wicksy/configfiles/dotfiles/.ssh/config"), ]) def test_links(host, name, linked_to): file = host.file(name) assert file.exists assert file.is_symlink assert file.linked_to == str(linked_to)
import pytest @pytest.mark.parametrize("name, linked_to", [ ("/home/wicksy/vagrant/Vagrantfile", "/git/wicksy/configfiles/vagrant/Vagrantfile"), ("/home/wicksy/.vimrc", "/git/wicksy/configfiles/dotfiles/.vimrc"), ("/home/wicksy/.bashrc", "/git/wicksy/configfiles/dotfiles/.bashrc"), ("/home/wicksy/.aws", "/git/wicksy/configfiles/dotfiles/.aws"), ("/home/wicksy/.config", "/git/wicksy/configfiles/dotfiles/.config"), ("/home/wicksy/.gitconfig", "/git/wicksy/configfiles/dotfiles/.gitconfig"), ("/home/wicksy/.ssh/config", "/git/wicksy/configfiles/dotfiles/.ssh/config"), ]) - def test_links(File, name, linked_to): ? ^^^^ + def test_links(host, name, linked_to): ? ^^^^ + file = host.file(name) - assert File(name).exists ? ^ ------ + assert file.exists ? ^ - assert File(name).is_symlink ? ^ ------ + assert file.is_symlink ? ^ - assert File(name).linked_to == str(linked_to) ? ^ ------ + assert file.linked_to == str(linked_to) ? ^
78585c783013c6f06f7e20eee6a654759b70e99c
tests/test_ttfmt.py
tests/test_ttfmt.py
import unittest class TestTtFmt(unittest.TestCase): def testName(self): pass if __name__ == "__main__": unittest.main()
import unittest import tt.fmttools.ttfmt as ttfmt class TestTtFmt(unittest.TestCase): def test_get_vars(self): data_provider = { # Simple test cases "F = A and B" : ["F", "A", "B"], "F = A and B or C" : ["F", "A", "B", "C"], } for eq in data_provider: self.assertListEqual(data_provider[eq], ttfmt.get_vars(eq)) if __name__ == "__main__": unittest.main()
Add basic tests for ttfmt get_vars method
Add basic tests for ttfmt get_vars method
Python
mit
welchbj/tt,welchbj/tt,welchbj/tt
import unittest + + import tt.fmttools.ttfmt as ttfmt class TestTtFmt(unittest.TestCase): - def testName(self): + def test_get_vars(self): + data_provider = { + # Simple test cases + "F = A and B" : ["F", "A", "B"], + "F = A and B or C" : ["F", "A", "B", "C"], + } - pass + + for eq in data_provider: + self.assertListEqual(data_provider[eq], ttfmt.get_vars(eq)) if __name__ == "__main__": unittest.main()
Add basic tests for ttfmt get_vars method
## Code Before: import unittest class TestTtFmt(unittest.TestCase): def testName(self): pass if __name__ == "__main__": unittest.main() ## Instruction: Add basic tests for ttfmt get_vars method ## Code After: import unittest import tt.fmttools.ttfmt as ttfmt class TestTtFmt(unittest.TestCase): def test_get_vars(self): data_provider = { # Simple test cases "F = A and B" : ["F", "A", "B"], "F = A and B or C" : ["F", "A", "B", "C"], } for eq in data_provider: self.assertListEqual(data_provider[eq], ttfmt.get_vars(eq)) if __name__ == "__main__": unittest.main()
import unittest + + import tt.fmttools.ttfmt as ttfmt class TestTtFmt(unittest.TestCase): - def testName(self): ? ^ ^^ + def test_get_vars(self): ? ^^^^^^ ^^ + data_provider = { + # Simple test cases + "F = A and B" : ["F", "A", "B"], + "F = A and B or C" : ["F", "A", "B", "C"], + } - pass ? ---- + + for eq in data_provider: + self.assertListEqual(data_provider[eq], ttfmt.get_vars(eq)) if __name__ == "__main__": unittest.main()
e2bb78a1587b7d5c0416c3632ca9674339826d55
src/yawf/creation.py
src/yawf/creation.py
from django.db import transaction from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR from yawf import get_workflow, get_workflow_by_instance from yawf import dispatch from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError @transaction.commit_on_success def create(workflow_type, sender, raw_parameters): workflow = get_workflow(workflow_type) if workflow is None: raise WorkflowNotLoadedError(workflow_type) form = workflow.create_form_cls(raw_parameters) if form.is_valid(): instance = workflow.instance_fabric(sender, form.cleaned_data) # Ensure that we will create, not update instance.id = None # Set workflow type setattr(instance, WORKFLOW_TYPE_ATTR, workflow_type) instance.save() workflow.post_create_hook(sender, form.cleaned_data, instance) return instance else: raise CreateValidationError(form.errors) def start_workflow(obj, sender, start_message_params): workflow = get_workflow_by_instance(obj) if isinstance(workflow.start_workflow, basestring): return dispatch.dispatch(obj, sender, workflow.start_workflow) elif callable(workflow.start_workflow): start_message_id = workflow.start_workflow(obj, sender) return dispatch.dispatch(obj, sender, start_message_id, start_message_params) else: return dispatch.dispatch(obj, sender, DEFAULT_START_MESSAGE)
from django.db import transaction from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR from yawf import get_workflow, get_workflow_by_instance from yawf import dispatch from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError @transaction.commit_on_success def create(workflow_type, sender, raw_parameters): workflow = get_workflow(workflow_type) if workflow is None: raise WorkflowNotLoadedError(workflow_type) form = workflow.create_form_cls(raw_parameters) if form.is_valid(): instance = workflow.instance_fabric(sender, form.cleaned_data) # Ensure that we will create, not update instance.id = None # Set workflow type setattr(instance, WORKFLOW_TYPE_ATTR, workflow_type) instance.save() workflow.post_create_hook(sender, form.cleaned_data, instance) return instance else: raise CreateValidationError(form.errors) def start_workflow(obj, sender, start_message_params=None): if start_message_params is None: start_message_params = {} workflow = get_workflow_by_instance(obj) if isinstance(workflow.start_workflow, basestring): return dispatch.dispatch(obj, sender, workflow.start_workflow) elif callable(workflow.start_workflow): start_message_id = workflow.start_workflow(obj, sender) return dispatch.dispatch(obj, sender, start_message_id, start_message_params) else: return dispatch.dispatch(obj, sender, DEFAULT_START_MESSAGE)
Make start_message_params optional in start_workflow()
Make start_message_params optional in start_workflow()
Python
mit
freevoid/yawf
from django.db import transaction from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR from yawf import get_workflow, get_workflow_by_instance from yawf import dispatch from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError @transaction.commit_on_success def create(workflow_type, sender, raw_parameters): workflow = get_workflow(workflow_type) if workflow is None: raise WorkflowNotLoadedError(workflow_type) form = workflow.create_form_cls(raw_parameters) if form.is_valid(): instance = workflow.instance_fabric(sender, form.cleaned_data) # Ensure that we will create, not update instance.id = None # Set workflow type setattr(instance, WORKFLOW_TYPE_ATTR, workflow_type) instance.save() workflow.post_create_hook(sender, form.cleaned_data, instance) return instance else: raise CreateValidationError(form.errors) - def start_workflow(obj, sender, start_message_params): + def start_workflow(obj, sender, start_message_params=None): + if start_message_params is None: + start_message_params = {} workflow = get_workflow_by_instance(obj) if isinstance(workflow.start_workflow, basestring): return dispatch.dispatch(obj, sender, workflow.start_workflow) elif callable(workflow.start_workflow): start_message_id = workflow.start_workflow(obj, sender) return dispatch.dispatch(obj, sender, start_message_id, start_message_params) else: return dispatch.dispatch(obj, sender, DEFAULT_START_MESSAGE)
Make start_message_params optional in start_workflow()
## Code Before: from django.db import transaction from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR from yawf import get_workflow, get_workflow_by_instance from yawf import dispatch from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError @transaction.commit_on_success def create(workflow_type, sender, raw_parameters): workflow = get_workflow(workflow_type) if workflow is None: raise WorkflowNotLoadedError(workflow_type) form = workflow.create_form_cls(raw_parameters) if form.is_valid(): instance = workflow.instance_fabric(sender, form.cleaned_data) # Ensure that we will create, not update instance.id = None # Set workflow type setattr(instance, WORKFLOW_TYPE_ATTR, workflow_type) instance.save() workflow.post_create_hook(sender, form.cleaned_data, instance) return instance else: raise CreateValidationError(form.errors) def start_workflow(obj, sender, start_message_params): workflow = get_workflow_by_instance(obj) if isinstance(workflow.start_workflow, basestring): return dispatch.dispatch(obj, sender, workflow.start_workflow) elif callable(workflow.start_workflow): start_message_id = workflow.start_workflow(obj, sender) return dispatch.dispatch(obj, sender, start_message_id, start_message_params) else: return dispatch.dispatch(obj, sender, DEFAULT_START_MESSAGE) ## Instruction: Make start_message_params optional in start_workflow() ## Code After: from django.db import transaction from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR from yawf import get_workflow, get_workflow_by_instance from yawf import dispatch from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError @transaction.commit_on_success def create(workflow_type, sender, raw_parameters): workflow = get_workflow(workflow_type) if workflow is None: raise WorkflowNotLoadedError(workflow_type) form = workflow.create_form_cls(raw_parameters) if form.is_valid(): instance = workflow.instance_fabric(sender, form.cleaned_data) # Ensure that we will create, not update instance.id = None # Set workflow type setattr(instance, WORKFLOW_TYPE_ATTR, workflow_type) instance.save() workflow.post_create_hook(sender, form.cleaned_data, instance) return instance else: raise CreateValidationError(form.errors) def start_workflow(obj, sender, start_message_params=None): if start_message_params is None: start_message_params = {} workflow = get_workflow_by_instance(obj) if isinstance(workflow.start_workflow, basestring): return dispatch.dispatch(obj, sender, workflow.start_workflow) elif callable(workflow.start_workflow): start_message_id = workflow.start_workflow(obj, sender) return dispatch.dispatch(obj, sender, start_message_id, start_message_params) else: return dispatch.dispatch(obj, sender, DEFAULT_START_MESSAGE)
from django.db import transaction from yawf.config import DEFAULT_START_MESSAGE, WORKFLOW_TYPE_ATTR from yawf import get_workflow, get_workflow_by_instance from yawf import dispatch from yawf.exceptions import WorkflowNotLoadedError, CreateValidationError @transaction.commit_on_success def create(workflow_type, sender, raw_parameters): workflow = get_workflow(workflow_type) if workflow is None: raise WorkflowNotLoadedError(workflow_type) form = workflow.create_form_cls(raw_parameters) if form.is_valid(): instance = workflow.instance_fabric(sender, form.cleaned_data) # Ensure that we will create, not update instance.id = None # Set workflow type setattr(instance, WORKFLOW_TYPE_ATTR, workflow_type) instance.save() workflow.post_create_hook(sender, form.cleaned_data, instance) return instance else: raise CreateValidationError(form.errors) - def start_workflow(obj, sender, start_message_params): + def start_workflow(obj, sender, start_message_params=None): ? +++++ + if start_message_params is None: + start_message_params = {} workflow = get_workflow_by_instance(obj) if isinstance(workflow.start_workflow, basestring): return dispatch.dispatch(obj, sender, workflow.start_workflow) elif callable(workflow.start_workflow): start_message_id = workflow.start_workflow(obj, sender) return dispatch.dispatch(obj, sender, start_message_id, start_message_params) else: return dispatch.dispatch(obj, sender, DEFAULT_START_MESSAGE)
8c8fbb8c3cf53ce0b193926fc89e426fb360eb81
database_import.py
database_import.py
import sys import csv from sqlalchemy.exc import IntegrityError from openledger.models import db, Image filename = sys.argv[1] fields = ('ImageID', 'Subset', 'OriginalURL', 'OriginalLandingURL', 'License', 'AuthorProfileURL', 'Author', 'Title') with open(filename) as csvfile: db.create_all() reader = csv.DictReader(csvfile) for row in reader: image = Image() image.google_imageid = row['ImageID'] image.image_url = row['OriginalURL'] image.original_landing_url = row['OriginalLandingURL'] image.license_url = row['License'] image.author_url = row['AuthorProfileURL'] image.author = row['Author'] image.title = row['Title'] db.session.add(image) try: db.session.commit() print("Adding image ", row['ImageID']) except IntegrityError: db.session.rollback()
import csv import argparse from sqlalchemy.exc import IntegrityError from openledger.models import db, Image def import_from_open_images(filename): fields = ('ImageID', 'Subset', 'OriginalURL', 'OriginalLandingURL', 'License', 'AuthorProfileURL', 'Author', 'Title') with open(filename) as csvfile: db.create_all() reader = csv.DictReader(csvfile) for row in reader: image = Image() image.google_imageid = row['ImageID'] image.image_url = row['OriginalURL'] image.original_landing_url = row['OriginalLandingURL'] image.license_url = row['License'] image.author_url = row['AuthorProfileURL'] image.author = row['Author'] image.title = row['Title'] db.session.add(image) try: db.session.commit() print("Adding image ", row['ImageID']) except IntegrityError: db.session.rollback() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--open-images-path", dest="openimages_path", help="The location of the Google Open Images csv file") parser.add_argument("--flickr-100m-path", dest="flickr100m_path", help="The location of the Flickr 100M tsv directory") args = parser.parse_args() if args.openimages_path: import_from_open_images(args.openimages_path)
Tidy up database import to take arguments for multiple sources
Tidy up database import to take arguments for multiple sources
Python
mit
creativecommons/open-ledger,creativecommons/open-ledger,creativecommons/open-ledger
- import sys import csv + import argparse + from sqlalchemy.exc import IntegrityError from openledger.models import db, Image - filename = sys.argv[1] + def import_from_open_images(filename): - fields = ('ImageID', 'Subset', 'OriginalURL', 'OriginalLandingURL', 'License', + fields = ('ImageID', 'Subset', 'OriginalURL', 'OriginalLandingURL', 'License', - 'AuthorProfileURL', 'Author', 'Title') + 'AuthorProfileURL', 'Author', 'Title') - with open(filename) as csvfile: + with open(filename) as csvfile: - db.create_all() + db.create_all() - reader = csv.DictReader(csvfile) + reader = csv.DictReader(csvfile) - for row in reader: + for row in reader: - image = Image() + image = Image() - image.google_imageid = row['ImageID'] + image.google_imageid = row['ImageID'] - image.image_url = row['OriginalURL'] + image.image_url = row['OriginalURL'] - image.original_landing_url = row['OriginalLandingURL'] + image.original_landing_url = row['OriginalLandingURL'] - image.license_url = row['License'] + image.license_url = row['License'] - image.author_url = row['AuthorProfileURL'] + image.author_url = row['AuthorProfileURL'] - image.author = row['Author'] + image.author = row['Author'] - image.title = row['Title'] + image.title = row['Title'] - db.session.add(image) + db.session.add(image) - try: + try: - db.session.commit() + db.session.commit() - print("Adding image ", row['ImageID']) + print("Adding image ", row['ImageID']) - except IntegrityError: + except IntegrityError: - db.session.rollback() + db.session.rollback() + if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument("--open-images-path", + dest="openimages_path", + help="The location of the Google Open Images csv file") + parser.add_argument("--flickr-100m-path", + dest="flickr100m_path", + help="The location of the Flickr 100M tsv directory") + args = parser.parse_args() + if args.openimages_path: + import_from_open_images(args.openimages_path) +
Tidy up database import to take arguments for multiple sources
## Code Before: import sys import csv from sqlalchemy.exc import IntegrityError from openledger.models import db, Image filename = sys.argv[1] fields = ('ImageID', 'Subset', 'OriginalURL', 'OriginalLandingURL', 'License', 'AuthorProfileURL', 'Author', 'Title') with open(filename) as csvfile: db.create_all() reader = csv.DictReader(csvfile) for row in reader: image = Image() image.google_imageid = row['ImageID'] image.image_url = row['OriginalURL'] image.original_landing_url = row['OriginalLandingURL'] image.license_url = row['License'] image.author_url = row['AuthorProfileURL'] image.author = row['Author'] image.title = row['Title'] db.session.add(image) try: db.session.commit() print("Adding image ", row['ImageID']) except IntegrityError: db.session.rollback() ## Instruction: Tidy up database import to take arguments for multiple sources ## Code After: import csv import argparse from sqlalchemy.exc import IntegrityError from openledger.models import db, Image def import_from_open_images(filename): fields = ('ImageID', 'Subset', 'OriginalURL', 'OriginalLandingURL', 'License', 'AuthorProfileURL', 'Author', 'Title') with open(filename) as csvfile: db.create_all() reader = csv.DictReader(csvfile) for row in reader: image = Image() image.google_imageid = row['ImageID'] image.image_url = row['OriginalURL'] image.original_landing_url = row['OriginalLandingURL'] image.license_url = row['License'] image.author_url = row['AuthorProfileURL'] image.author = row['Author'] image.title = row['Title'] db.session.add(image) try: db.session.commit() print("Adding image ", row['ImageID']) except IntegrityError: db.session.rollback() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--open-images-path", dest="openimages_path", help="The location of the Google Open Images csv file") parser.add_argument("--flickr-100m-path", dest="flickr100m_path", help="The location of the Flickr 100M tsv directory") args = parser.parse_args() if args.openimages_path: import_from_open_images(args.openimages_path)
- import sys import csv + import argparse + from sqlalchemy.exc import IntegrityError from openledger.models import db, Image - filename = sys.argv[1] + def import_from_open_images(filename): - fields = ('ImageID', 'Subset', 'OriginalURL', 'OriginalLandingURL', 'License', + fields = ('ImageID', 'Subset', 'OriginalURL', 'OriginalLandingURL', 'License', ? ++++ - 'AuthorProfileURL', 'Author', 'Title') + 'AuthorProfileURL', 'Author', 'Title') ? ++++ - with open(filename) as csvfile: + with open(filename) as csvfile: ? ++++ - db.create_all() + db.create_all() ? ++++ - reader = csv.DictReader(csvfile) + reader = csv.DictReader(csvfile) ? ++++ - for row in reader: + for row in reader: ? ++++ - image = Image() + image = Image() ? ++++ - image.google_imageid = row['ImageID'] + image.google_imageid = row['ImageID'] ? ++++ - image.image_url = row['OriginalURL'] + image.image_url = row['OriginalURL'] ? ++++ - image.original_landing_url = row['OriginalLandingURL'] + image.original_landing_url = row['OriginalLandingURL'] ? ++++ - image.license_url = row['License'] + image.license_url = row['License'] ? ++++ - image.author_url = row['AuthorProfileURL'] + image.author_url = row['AuthorProfileURL'] ? ++++ - image.author = row['Author'] + image.author = row['Author'] ? ++++ - image.title = row['Title'] + image.title = row['Title'] ? ++++ - db.session.add(image) + db.session.add(image) ? ++++ - try: + try: ? ++++ - db.session.commit() + db.session.commit() ? ++++ - print("Adding image ", row['ImageID']) + print("Adding image ", row['ImageID']) ? ++++ - except IntegrityError: + except IntegrityError: ? ++++ - db.session.rollback() + db.session.rollback() ? ++++ + + if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument("--open-images-path", + dest="openimages_path", + help="The location of the Google Open Images csv file") + parser.add_argument("--flickr-100m-path", + dest="flickr100m_path", + help="The location of the Flickr 100M tsv directory") + args = parser.parse_args() + if args.openimages_path: + import_from_open_images(args.openimages_path)
828844ddb6a19ea15c920043f41ba09eb815c597
django_rq/templatetags/django_rq.py
django_rq/templatetags/django_rq.py
from django import template from django.utils import timezone register = template.Library() @register.filter def to_localtime(time): ''' A function to convert naive datetime to localtime base on settings ''' utc_time = time.replace(tzinfo=timezone.utc) to_zone = timezone.get_default_timezone() return utc_time.astimezone(to_zone)
from django import template from django.utils import timezone register = template.Library() @register.filter def to_localtime(time): ''' A function to convert naive datetime to localtime base on settings ''' if not time: return None utc_time = time.replace(tzinfo=timezone.utc) to_zone = timezone.get_default_timezone() return utc_time.astimezone(to_zone)
Fix issue displaying deferred queue
Fix issue displaying deferred queue
Python
mit
ui/django-rq,ui/django-rq,1024inc/django-rq,1024inc/django-rq
from django import template from django.utils import timezone register = template.Library() @register.filter def to_localtime(time): ''' A function to convert naive datetime to localtime base on settings ''' + + if not time: + return None + utc_time = time.replace(tzinfo=timezone.utc) to_zone = timezone.get_default_timezone() return utc_time.astimezone(to_zone)
Fix issue displaying deferred queue
## Code Before: from django import template from django.utils import timezone register = template.Library() @register.filter def to_localtime(time): ''' A function to convert naive datetime to localtime base on settings ''' utc_time = time.replace(tzinfo=timezone.utc) to_zone = timezone.get_default_timezone() return utc_time.astimezone(to_zone) ## Instruction: Fix issue displaying deferred queue ## Code After: from django import template from django.utils import timezone register = template.Library() @register.filter def to_localtime(time): ''' A function to convert naive datetime to localtime base on settings ''' if not time: return None utc_time = time.replace(tzinfo=timezone.utc) to_zone = timezone.get_default_timezone() return utc_time.astimezone(to_zone)
from django import template from django.utils import timezone register = template.Library() @register.filter def to_localtime(time): ''' A function to convert naive datetime to localtime base on settings ''' + + if not time: + return None + utc_time = time.replace(tzinfo=timezone.utc) to_zone = timezone.get_default_timezone() return utc_time.astimezone(to_zone)
d99bdbd710c6b3bf0e1eeed5d2cf8f26790040ef
alembic/versions/38f01b0893b8_add_call_in_campaign_id_to_.py
alembic/versions/38f01b0893b8_add_call_in_campaign_id_to_.py
# revision identifiers, used by Alembic. revision = '38f01b0893b8' down_revision = '3c34cfd19bf8' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): with op.batch_alter_table('campaign_phone') as batch_op: batch_op.add_column(sa.Column('call_in_campaign_id', sa.Integer(), sa.ForeignKey('campaign_campaign.id'), nullable=True)) def downgrade(): with op.batch_alter_table('campaign_phone') as batch_op: batch_op.drop_column('call_in_campaign_id')
# revision identifiers, used by Alembic. revision = '38f01b0893b8' down_revision = '3c34cfd19bf8' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): with op.batch_alter_table('campaign_phone') as batch_op: batch_op.add_column(sa.Column('call_in_campaign_id', sa.Integer(), sa.ForeignKey('campaign_campaign.id'), nullable=True)) connection = op.get_bind() campaign_call_in_numbers = connection.execute( """SELECT campaign_phone_numbers.campaign_id, campaign_phone_numbers.phone_id FROM campaign_phone_numbers INNER JOIN campaign_phone ON campaign_phone_numbers.phone_id = campaign_phone.id WHERE campaign_phone.call_in_allowed""" ) for (campaign_id, phone_id) in campaign_call_in_numbers: connection.execute("""UPDATE campaign_phone SET call_in_campaign_id = """+str(campaign_id)+""" WHERE campaign_phone.id = """+str(phone_id)) def downgrade(): with op.batch_alter_table('campaign_phone') as batch_op: batch_op.drop_column('call_in_campaign_id')
Initialize call_in_campaign_id column after adding
Initialize call_in_campaign_id column after adding
Python
agpl-3.0
OpenSourceActivismTech/call-power,spacedogXYZ/call-power,spacedogXYZ/call-power,18mr/call-congress,spacedogXYZ/call-power,OpenSourceActivismTech/call-power,spacedogXYZ/call-power,OpenSourceActivismTech/call-power,18mr/call-congress,18mr/call-congress,18mr/call-congress,OpenSourceActivismTech/call-power
# revision identifiers, used by Alembic. revision = '38f01b0893b8' down_revision = '3c34cfd19bf8' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): with op.batch_alter_table('campaign_phone') as batch_op: batch_op.add_column(sa.Column('call_in_campaign_id', sa.Integer(), sa.ForeignKey('campaign_campaign.id'), nullable=True)) + connection = op.get_bind() + campaign_call_in_numbers = connection.execute( + """SELECT campaign_phone_numbers.campaign_id, campaign_phone_numbers.phone_id + FROM campaign_phone_numbers + INNER JOIN campaign_phone ON campaign_phone_numbers.phone_id = campaign_phone.id + WHERE campaign_phone.call_in_allowed""" + ) + + for (campaign_id, phone_id) in campaign_call_in_numbers: + connection.execute("""UPDATE campaign_phone + SET call_in_campaign_id = """+str(campaign_id)+""" + WHERE campaign_phone.id = """+str(phone_id)) + def downgrade(): with op.batch_alter_table('campaign_phone') as batch_op: batch_op.drop_column('call_in_campaign_id')
Initialize call_in_campaign_id column after adding
## Code Before: # revision identifiers, used by Alembic. revision = '38f01b0893b8' down_revision = '3c34cfd19bf8' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): with op.batch_alter_table('campaign_phone') as batch_op: batch_op.add_column(sa.Column('call_in_campaign_id', sa.Integer(), sa.ForeignKey('campaign_campaign.id'), nullable=True)) def downgrade(): with op.batch_alter_table('campaign_phone') as batch_op: batch_op.drop_column('call_in_campaign_id') ## Instruction: Initialize call_in_campaign_id column after adding ## Code After: # revision identifiers, used by Alembic. revision = '38f01b0893b8' down_revision = '3c34cfd19bf8' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): with op.batch_alter_table('campaign_phone') as batch_op: batch_op.add_column(sa.Column('call_in_campaign_id', sa.Integer(), sa.ForeignKey('campaign_campaign.id'), nullable=True)) connection = op.get_bind() campaign_call_in_numbers = connection.execute( """SELECT campaign_phone_numbers.campaign_id, campaign_phone_numbers.phone_id FROM campaign_phone_numbers INNER JOIN campaign_phone ON campaign_phone_numbers.phone_id = campaign_phone.id WHERE campaign_phone.call_in_allowed""" ) for (campaign_id, phone_id) in campaign_call_in_numbers: connection.execute("""UPDATE campaign_phone SET call_in_campaign_id = """+str(campaign_id)+""" WHERE campaign_phone.id = """+str(phone_id)) def downgrade(): with op.batch_alter_table('campaign_phone') as batch_op: batch_op.drop_column('call_in_campaign_id')
# revision identifiers, used by Alembic. revision = '38f01b0893b8' down_revision = '3c34cfd19bf8' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): with op.batch_alter_table('campaign_phone') as batch_op: batch_op.add_column(sa.Column('call_in_campaign_id', sa.Integer(), sa.ForeignKey('campaign_campaign.id'), nullable=True)) + connection = op.get_bind() + campaign_call_in_numbers = connection.execute( + """SELECT campaign_phone_numbers.campaign_id, campaign_phone_numbers.phone_id + FROM campaign_phone_numbers + INNER JOIN campaign_phone ON campaign_phone_numbers.phone_id = campaign_phone.id + WHERE campaign_phone.call_in_allowed""" + ) + + for (campaign_id, phone_id) in campaign_call_in_numbers: + connection.execute("""UPDATE campaign_phone + SET call_in_campaign_id = """+str(campaign_id)+""" + WHERE campaign_phone.id = """+str(phone_id)) + def downgrade(): with op.batch_alter_table('campaign_phone') as batch_op: batch_op.drop_column('call_in_campaign_id')
28f25bb7ca5a415bbc3ca2aabd7e290339140a9f
tests/test_dns.py
tests/test_dns.py
from .utils import TestCase, skipUnless from dynsupdate import client import os class DnsTests(TestCase): @skipUnless(os.getenv("SLOW"), "To slow") def test_build_resolver(self): domain = 'google-public-dns-a.google.com' res = client.NameUpdate.build_resolver(domain) self.assertListEqual(res.nameservers, ['8.8.8.8'])
from .utils import TestCase, skipUnless, mock from dynsupdate import client import os class DnsTests(TestCase): @skipUnless(os.getenv("SLOW"), "To slow") def test_build_resolver(self): domain = 'google-public-dns-a.google.com' res = client.NameUpdate.build_resolver(domain) self.assertListEqual(res.nameservers, ['8.8.8.8']) @mock.patch('dns.resolver.query') @mock.patch('dns.resolver.Resolver') def test_build_resolver_fake(self, mock_resolver, mock_query): mock_rdata = mock.Mock() mock_rdata.address = "127.0.0.1" mock_query.return_value = iter([mock_rdata]) res = client.NameUpdate.build_resolver("ns1.fake.com", port=999) mock_query.assert_called_with("ns1.fake.com", "A") print(mock_resolver.mock_calls) mock_resolver.return_value.nameservers.append \ .assert_called_with("127.0.0.1") self.assertEqual(res.port, 999)
Add mocked test of build_resolver
Add mocked test of build_resolver
Python
bsd-3-clause
bacher09/dynsupdate
- from .utils import TestCase, skipUnless + from .utils import TestCase, skipUnless, mock from dynsupdate import client import os class DnsTests(TestCase): @skipUnless(os.getenv("SLOW"), "To slow") def test_build_resolver(self): domain = 'google-public-dns-a.google.com' res = client.NameUpdate.build_resolver(domain) self.assertListEqual(res.nameservers, ['8.8.8.8']) + @mock.patch('dns.resolver.query') + @mock.patch('dns.resolver.Resolver') + def test_build_resolver_fake(self, mock_resolver, mock_query): + mock_rdata = mock.Mock() + mock_rdata.address = "127.0.0.1" + mock_query.return_value = iter([mock_rdata]) + res = client.NameUpdate.build_resolver("ns1.fake.com", port=999) + mock_query.assert_called_with("ns1.fake.com", "A") + print(mock_resolver.mock_calls) + mock_resolver.return_value.nameservers.append \ + .assert_called_with("127.0.0.1") + + self.assertEqual(res.port, 999) +
Add mocked test of build_resolver
## Code Before: from .utils import TestCase, skipUnless from dynsupdate import client import os class DnsTests(TestCase): @skipUnless(os.getenv("SLOW"), "To slow") def test_build_resolver(self): domain = 'google-public-dns-a.google.com' res = client.NameUpdate.build_resolver(domain) self.assertListEqual(res.nameservers, ['8.8.8.8']) ## Instruction: Add mocked test of build_resolver ## Code After: from .utils import TestCase, skipUnless, mock from dynsupdate import client import os class DnsTests(TestCase): @skipUnless(os.getenv("SLOW"), "To slow") def test_build_resolver(self): domain = 'google-public-dns-a.google.com' res = client.NameUpdate.build_resolver(domain) self.assertListEqual(res.nameservers, ['8.8.8.8']) @mock.patch('dns.resolver.query') @mock.patch('dns.resolver.Resolver') def test_build_resolver_fake(self, mock_resolver, mock_query): mock_rdata = mock.Mock() mock_rdata.address = "127.0.0.1" mock_query.return_value = iter([mock_rdata]) res = client.NameUpdate.build_resolver("ns1.fake.com", port=999) mock_query.assert_called_with("ns1.fake.com", "A") print(mock_resolver.mock_calls) mock_resolver.return_value.nameservers.append \ .assert_called_with("127.0.0.1") self.assertEqual(res.port, 999)
- from .utils import TestCase, skipUnless + from .utils import TestCase, skipUnless, mock ? ++++++ from dynsupdate import client import os class DnsTests(TestCase): @skipUnless(os.getenv("SLOW"), "To slow") def test_build_resolver(self): domain = 'google-public-dns-a.google.com' res = client.NameUpdate.build_resolver(domain) self.assertListEqual(res.nameservers, ['8.8.8.8']) + + @mock.patch('dns.resolver.query') + @mock.patch('dns.resolver.Resolver') + def test_build_resolver_fake(self, mock_resolver, mock_query): + mock_rdata = mock.Mock() + mock_rdata.address = "127.0.0.1" + mock_query.return_value = iter([mock_rdata]) + res = client.NameUpdate.build_resolver("ns1.fake.com", port=999) + mock_query.assert_called_with("ns1.fake.com", "A") + print(mock_resolver.mock_calls) + mock_resolver.return_value.nameservers.append \ + .assert_called_with("127.0.0.1") + + self.assertEqual(res.port, 999)
1c254d8869482241de14255c25edd875ca369e46
fortuitus/frunner/factories.py
fortuitus/frunner/factories.py
import factory from fortuitus.feditor.factories import TestProjectF from fortuitus.frunner import models class TestRunF(factory.Factory): FACTORY_FOR = models.TestRun project = factory.SubFactory(TestProjectF) class TestCaseF(factory.Factory): FACTORY_FOR = models.TestCase testrun = factory.SubFactory(TestRunF) name = factory.Sequence(lambda n: 'TestCase #%s' % n) order = 1 login_type = models.models_base.LoginType.NONE class TestCaseStepF(factory.Factory): FACTORY_FOR = models.TestCaseStep testcase = factory.SubFactory(TestCaseF) order = 1 method = models.models_base.Method.GET url = 'user_list.json' class TestCaseAssertF(factory.Factory): FACTORY_FOR = models.TestCaseAssert step = factory.SubFactory(TestCaseStepF) order = 1 lhs = '' rhs = '' operator = models.models_base.method_choices[0][0]
import factory from fortuitus.feditor.factories import TestProjectF from fortuitus.frunner import models class TestRunF(factory.Factory): FACTORY_FOR = models.TestRun project = factory.SubFactory(TestProjectF) base_url = 'http://api.example.com/' class TestCaseF(factory.Factory): FACTORY_FOR = models.TestCase testrun = factory.SubFactory(TestRunF) name = factory.Sequence(lambda n: 'TestCase #%s' % n) order = 1 login_type = models.models_base.LoginType.NONE class TestCaseStepF(factory.Factory): FACTORY_FOR = models.TestCaseStep testcase = factory.SubFactory(TestCaseF) order = 1 method = models.models_base.Method.GET url = 'user_list.json' class TestCaseAssertF(factory.Factory): FACTORY_FOR = models.TestCaseAssert step = factory.SubFactory(TestCaseStepF) order = 1 lhs = '' rhs = '' operator = models.models_base.method_choices[0][0]
Fix TestRun factory missing base_url
Fix TestRun factory missing base_url
Python
mit
elegion/djangodash2012,elegion/djangodash2012
import factory from fortuitus.feditor.factories import TestProjectF from fortuitus.frunner import models class TestRunF(factory.Factory): FACTORY_FOR = models.TestRun project = factory.SubFactory(TestProjectF) + base_url = 'http://api.example.com/' class TestCaseF(factory.Factory): FACTORY_FOR = models.TestCase testrun = factory.SubFactory(TestRunF) name = factory.Sequence(lambda n: 'TestCase #%s' % n) order = 1 login_type = models.models_base.LoginType.NONE class TestCaseStepF(factory.Factory): FACTORY_FOR = models.TestCaseStep testcase = factory.SubFactory(TestCaseF) order = 1 method = models.models_base.Method.GET url = 'user_list.json' class TestCaseAssertF(factory.Factory): FACTORY_FOR = models.TestCaseAssert step = factory.SubFactory(TestCaseStepF) order = 1 lhs = '' rhs = '' operator = models.models_base.method_choices[0][0]
Fix TestRun factory missing base_url
## Code Before: import factory from fortuitus.feditor.factories import TestProjectF from fortuitus.frunner import models class TestRunF(factory.Factory): FACTORY_FOR = models.TestRun project = factory.SubFactory(TestProjectF) class TestCaseF(factory.Factory): FACTORY_FOR = models.TestCase testrun = factory.SubFactory(TestRunF) name = factory.Sequence(lambda n: 'TestCase #%s' % n) order = 1 login_type = models.models_base.LoginType.NONE class TestCaseStepF(factory.Factory): FACTORY_FOR = models.TestCaseStep testcase = factory.SubFactory(TestCaseF) order = 1 method = models.models_base.Method.GET url = 'user_list.json' class TestCaseAssertF(factory.Factory): FACTORY_FOR = models.TestCaseAssert step = factory.SubFactory(TestCaseStepF) order = 1 lhs = '' rhs = '' operator = models.models_base.method_choices[0][0] ## Instruction: Fix TestRun factory missing base_url ## Code After: import factory from fortuitus.feditor.factories import TestProjectF from fortuitus.frunner import models class TestRunF(factory.Factory): FACTORY_FOR = models.TestRun project = factory.SubFactory(TestProjectF) base_url = 'http://api.example.com/' class TestCaseF(factory.Factory): FACTORY_FOR = models.TestCase testrun = factory.SubFactory(TestRunF) name = factory.Sequence(lambda n: 'TestCase #%s' % n) order = 1 login_type = models.models_base.LoginType.NONE class TestCaseStepF(factory.Factory): FACTORY_FOR = models.TestCaseStep testcase = factory.SubFactory(TestCaseF) order = 1 method = models.models_base.Method.GET url = 'user_list.json' class TestCaseAssertF(factory.Factory): FACTORY_FOR = models.TestCaseAssert step = factory.SubFactory(TestCaseStepF) order = 1 lhs = '' rhs = '' operator = models.models_base.method_choices[0][0]
import factory from fortuitus.feditor.factories import TestProjectF from fortuitus.frunner import models class TestRunF(factory.Factory): FACTORY_FOR = models.TestRun project = factory.SubFactory(TestProjectF) + base_url = 'http://api.example.com/' class TestCaseF(factory.Factory): FACTORY_FOR = models.TestCase testrun = factory.SubFactory(TestRunF) name = factory.Sequence(lambda n: 'TestCase #%s' % n) order = 1 login_type = models.models_base.LoginType.NONE class TestCaseStepF(factory.Factory): FACTORY_FOR = models.TestCaseStep testcase = factory.SubFactory(TestCaseF) order = 1 method = models.models_base.Method.GET url = 'user_list.json' class TestCaseAssertF(factory.Factory): FACTORY_FOR = models.TestCaseAssert step = factory.SubFactory(TestCaseStepF) order = 1 lhs = '' rhs = '' operator = models.models_base.method_choices[0][0]
c3ed431f97e4ca24a00ff979a5204d65b251dd87
greenlight/views/__init__.py
greenlight/views/__init__.py
from .base import APIView from django.http import Http404 from three import Three class QCThree(Three): def __init__(self): self.endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/" self.format = "json" self.jurisdiction = "ville.quebec.qc.ca" QC_three = QCThree() class ServicesView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.services()) class RequestsView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.requests()) class RequestView(APIView): def get(self, request, id): requests = QC_three.request(id) if requests: return self.OkAPIResponse(requests[0]) else: raise Http404
from three import Three from django.http import Http404 from .base import APIView QC_three = Three( endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/", format = "json", jurisdiction = "ville.quebec.qc.ca", ) class ServicesView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.services()) class RequestsView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.requests()) class RequestView(APIView): def get(self, request, id): requests = QC_three.request(id) if requests: return self.OkAPIResponse(requests[0]) else: raise Http404
Initialize the three API wrapper differently to fix a bug.
Initialize the three API wrapper differently to fix a bug.
Python
mit
ironweb/lesfeuxverts-backend
- from .base import APIView + from three import Three from django.http import Http404 - from three import Three + from .base import APIView + QC_three = Three( - class QCThree(Three): - def __init__(self): - self.endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/" + endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/", - self.format = "json" + format = "json", - self.jurisdiction = "ville.quebec.qc.ca" + jurisdiction = "ville.quebec.qc.ca", + ) - QC_three = QCThree() class ServicesView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.services()) class RequestsView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.requests()) class RequestView(APIView): def get(self, request, id): requests = QC_three.request(id) if requests: return self.OkAPIResponse(requests[0]) else: raise Http404
Initialize the three API wrapper differently to fix a bug.
## Code Before: from .base import APIView from django.http import Http404 from three import Three class QCThree(Three): def __init__(self): self.endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/" self.format = "json" self.jurisdiction = "ville.quebec.qc.ca" QC_three = QCThree() class ServicesView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.services()) class RequestsView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.requests()) class RequestView(APIView): def get(self, request, id): requests = QC_three.request(id) if requests: return self.OkAPIResponse(requests[0]) else: raise Http404 ## Instruction: Initialize the three API wrapper differently to fix a bug. ## Code After: from three import Three from django.http import Http404 from .base import APIView QC_three = Three( endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/", format = "json", jurisdiction = "ville.quebec.qc.ca", ) class ServicesView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.services()) class RequestsView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.requests()) class RequestView(APIView): def get(self, request, id): requests = QC_three.request(id) if requests: return self.OkAPIResponse(requests[0]) else: raise Http404
- from .base import APIView + from three import Three from django.http import Http404 - from three import Three + from .base import APIView + QC_three = Three( - class QCThree(Three): - def __init__(self): - self.endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/" ? ------ + endpoint = "http://dev-api.ville.quebec.qc.ca/open311/v2/", ? + - self.format = "json" ? ------ + format = "json", ? + - self.jurisdiction = "ville.quebec.qc.ca" ? ------ + jurisdiction = "ville.quebec.qc.ca", ? + + ) - QC_three = QCThree() class ServicesView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.services()) class RequestsView(APIView): def get(self, request): return self.OkAPIResponse(QC_three.requests()) class RequestView(APIView): def get(self, request, id): requests = QC_three.request(id) if requests: return self.OkAPIResponse(requests[0]) else: raise Http404
0933e4c671ca1297378b2ad388933e11265321d0
traptor/dd_monitoring.py
traptor/dd_monitoring.py
import os from datadog import initialize traptor_type = os.environ['TRAPTOR_TYPE'] traptor_id = os.environ['TRAPTOR_ID'] DEFAULT_TAGS = [ 'traptor_type:{}'.format(traptor_type), 'traptor_id:{}'.format(traptor_id), ] options = { 'statsd_host': os.environ['STATSD_HOST_IP'], } initialize(**options) from datadog import statsd DATADOG_METRICS = { 'tweet_process_success': 'traptor.src.tweet_process.success', 'tweet_process_failure': 'traptor.src.tweet_process.failure', 'tweet_to_kafka_success': 'traptor.src.tweet_to_kafka.success', 'tweet_to_kafka_failure': 'traptor.src.tweet_to_kafka.failure', } def increment(metric_name): return statsd.increment(DATADOG_METRICS[metric_name], tags=DEFAULT_TAGS) def gauge(metric_name, value): return statsd.gauge(DATADOG_METRICS[metric_name], value, tags=DEFAULT_TAGS)
import os from datadog import initialize traptor_type = os.getenv('TRAPTOR_TYPE', 'track') traptor_id = os.getenv('TRAPTOR_ID', '0') DEFAULT_TAGS = [ 'traptor_type:{}'.format(traptor_type), 'traptor_id:{}'.format(traptor_id), ] options = { 'statsd_host': os.getenv('STATSD_HOST_IP', '127.0.0.1') } initialize(**options) from datadog import statsd DATADOG_METRICS = { 'tweet_process_success': 'traptor.src.tweet_process.success', 'tweet_process_failure': 'traptor.src.tweet_process.failure', 'tweet_to_kafka_success': 'traptor.src.tweet_to_kafka.success', 'tweet_to_kafka_failure': 'traptor.src.tweet_to_kafka.failure', } def increment(metric_name): return statsd.increment(DATADOG_METRICS[metric_name], tags=DEFAULT_TAGS) def gauge(metric_name, value): return statsd.gauge(DATADOG_METRICS[metric_name], value, tags=DEFAULT_TAGS)
Use getenv instead of environment dict
Use getenv instead of environment dict
Python
mit
istresearch/traptor,istresearch/traptor
import os from datadog import initialize - traptor_type = os.environ['TRAPTOR_TYPE'] + traptor_type = os.getenv('TRAPTOR_TYPE', 'track') - traptor_id = os.environ['TRAPTOR_ID'] + traptor_id = os.getenv('TRAPTOR_ID', '0') DEFAULT_TAGS = [ 'traptor_type:{}'.format(traptor_type), 'traptor_id:{}'.format(traptor_id), ] options = { - 'statsd_host': os.environ['STATSD_HOST_IP'], + 'statsd_host': os.getenv('STATSD_HOST_IP', '127.0.0.1') } initialize(**options) from datadog import statsd DATADOG_METRICS = { 'tweet_process_success': 'traptor.src.tweet_process.success', 'tweet_process_failure': 'traptor.src.tweet_process.failure', 'tweet_to_kafka_success': 'traptor.src.tweet_to_kafka.success', 'tweet_to_kafka_failure': 'traptor.src.tweet_to_kafka.failure', } def increment(metric_name): return statsd.increment(DATADOG_METRICS[metric_name], tags=DEFAULT_TAGS) def gauge(metric_name, value): return statsd.gauge(DATADOG_METRICS[metric_name], value, tags=DEFAULT_TAGS)
Use getenv instead of environment dict
## Code Before: import os from datadog import initialize traptor_type = os.environ['TRAPTOR_TYPE'] traptor_id = os.environ['TRAPTOR_ID'] DEFAULT_TAGS = [ 'traptor_type:{}'.format(traptor_type), 'traptor_id:{}'.format(traptor_id), ] options = { 'statsd_host': os.environ['STATSD_HOST_IP'], } initialize(**options) from datadog import statsd DATADOG_METRICS = { 'tweet_process_success': 'traptor.src.tweet_process.success', 'tweet_process_failure': 'traptor.src.tweet_process.failure', 'tweet_to_kafka_success': 'traptor.src.tweet_to_kafka.success', 'tweet_to_kafka_failure': 'traptor.src.tweet_to_kafka.failure', } def increment(metric_name): return statsd.increment(DATADOG_METRICS[metric_name], tags=DEFAULT_TAGS) def gauge(metric_name, value): return statsd.gauge(DATADOG_METRICS[metric_name], value, tags=DEFAULT_TAGS) ## Instruction: Use getenv instead of environment dict ## Code After: import os from datadog import initialize traptor_type = os.getenv('TRAPTOR_TYPE', 'track') traptor_id = os.getenv('TRAPTOR_ID', '0') DEFAULT_TAGS = [ 'traptor_type:{}'.format(traptor_type), 'traptor_id:{}'.format(traptor_id), ] options = { 'statsd_host': os.getenv('STATSD_HOST_IP', '127.0.0.1') } initialize(**options) from datadog import statsd DATADOG_METRICS = { 'tweet_process_success': 'traptor.src.tweet_process.success', 'tweet_process_failure': 'traptor.src.tweet_process.failure', 'tweet_to_kafka_success': 'traptor.src.tweet_to_kafka.success', 'tweet_to_kafka_failure': 'traptor.src.tweet_to_kafka.failure', } def increment(metric_name): return statsd.increment(DATADOG_METRICS[metric_name], tags=DEFAULT_TAGS) def gauge(metric_name, value): return statsd.gauge(DATADOG_METRICS[metric_name], value, tags=DEFAULT_TAGS)
import os from datadog import initialize - traptor_type = os.environ['TRAPTOR_TYPE'] ? ^^^^^ ^ + traptor_type = os.getenv('TRAPTOR_TYPE', 'track') ? +++ ^ ^^^^^^^^^^ - traptor_id = os.environ['TRAPTOR_ID'] ? ^^^^^ ^ + traptor_id = os.getenv('TRAPTOR_ID', '0') ? +++ ^ ^^^^^^ DEFAULT_TAGS = [ 'traptor_type:{}'.format(traptor_type), 'traptor_id:{}'.format(traptor_id), ] options = { - 'statsd_host': os.environ['STATSD_HOST_IP'], ? ^^^^^ - + 'statsd_host': os.getenv('STATSD_HOST_IP', '127.0.0.1') ? +++ ^ +++++++++++++ } initialize(**options) from datadog import statsd DATADOG_METRICS = { 'tweet_process_success': 'traptor.src.tweet_process.success', 'tweet_process_failure': 'traptor.src.tweet_process.failure', 'tweet_to_kafka_success': 'traptor.src.tweet_to_kafka.success', 'tweet_to_kafka_failure': 'traptor.src.tweet_to_kafka.failure', } def increment(metric_name): return statsd.increment(DATADOG_METRICS[metric_name], tags=DEFAULT_TAGS) def gauge(metric_name, value): return statsd.gauge(DATADOG_METRICS[metric_name], value, tags=DEFAULT_TAGS)
add508b780d16fd2da2fd0639304935b762c001f
tests/cupy_tests/binary_tests/test_packing.py
tests/cupy_tests/binary_tests/test_packing.py
import unittest from cupy import testing @testing.gpu class TestPacking(unittest.TestCase): _multiprocess_can_split_ = True
import numpy import unittest from cupy import testing @testing.gpu class TestPacking(unittest.TestCase): _multiprocess_can_split_ = True @testing.for_int_dtypes() @testing.numpy_cupy_array_equal() def check_packbits(self, data, xp, dtype): a = xp.array(data, dtype=dtype) return xp.packbits(a) @testing.numpy_cupy_array_equal() def check_unpackbits(self, data, xp): a = xp.array(data, dtype=xp.uint8) return xp.unpackbits(a) def test_packbits(self): self.check_packbits([]) self.check_packbits([0]) self.check_packbits([1]) self.check_packbits([0, 1]) self.check_packbits([1, 0, 1, 1, 0, 1, 1, 1]) self.check_packbits([1, 0, 1, 1, 0, 1, 1, 1, 1]) self.check_packbits(numpy.arange(24).reshape((2, 3, 4)) % 2) def test_unpackbits(self): self.check_unpackbits([]) self.check_unpackbits([0]) self.check_unpackbits([1]) self.check_unpackbits([255]) self.check_unpackbits([100, 200, 123, 213])
Add tests for packbits and unpackbits
Add tests for packbits and unpackbits
Python
mit
okuta/chainer,niboshi/chainer,ktnyt/chainer,chainer/chainer,ktnyt/chainer,jnishi/chainer,ysekky/chainer,pfnet/chainer,wkentaro/chainer,keisuke-umezawa/chainer,ktnyt/chainer,chainer/chainer,hvy/chainer,jnishi/chainer,anaruse/chainer,wkentaro/chainer,keisuke-umezawa/chainer,ronekko/chainer,niboshi/chainer,chainer/chainer,kashif/chainer,okuta/chainer,rezoo/chainer,keisuke-umezawa/chainer,cupy/cupy,chainer/chainer,hvy/chainer,jnishi/chainer,ktnyt/chainer,niboshi/chainer,cupy/cupy,keisuke-umezawa/chainer,okuta/chainer,okuta/chainer,jnishi/chainer,hvy/chainer,wkentaro/chainer,delta2323/chainer,cupy/cupy,kiyukuta/chainer,tkerola/chainer,cupy/cupy,niboshi/chainer,hvy/chainer,aonotas/chainer,wkentaro/chainer
+ import numpy import unittest from cupy import testing @testing.gpu class TestPacking(unittest.TestCase): _multiprocess_can_split_ = True + @testing.for_int_dtypes() + @testing.numpy_cupy_array_equal() + def check_packbits(self, data, xp, dtype): + a = xp.array(data, dtype=dtype) + return xp.packbits(a) + + @testing.numpy_cupy_array_equal() + def check_unpackbits(self, data, xp): + a = xp.array(data, dtype=xp.uint8) + return xp.unpackbits(a) + + def test_packbits(self): + self.check_packbits([]) + self.check_packbits([0]) + self.check_packbits([1]) + self.check_packbits([0, 1]) + self.check_packbits([1, 0, 1, 1, 0, 1, 1, 1]) + self.check_packbits([1, 0, 1, 1, 0, 1, 1, 1, 1]) + self.check_packbits(numpy.arange(24).reshape((2, 3, 4)) % 2) + + def test_unpackbits(self): + self.check_unpackbits([]) + self.check_unpackbits([0]) + self.check_unpackbits([1]) + self.check_unpackbits([255]) + self.check_unpackbits([100, 200, 123, 213]) +
Add tests for packbits and unpackbits
## Code Before: import unittest from cupy import testing @testing.gpu class TestPacking(unittest.TestCase): _multiprocess_can_split_ = True ## Instruction: Add tests for packbits and unpackbits ## Code After: import numpy import unittest from cupy import testing @testing.gpu class TestPacking(unittest.TestCase): _multiprocess_can_split_ = True @testing.for_int_dtypes() @testing.numpy_cupy_array_equal() def check_packbits(self, data, xp, dtype): a = xp.array(data, dtype=dtype) return xp.packbits(a) @testing.numpy_cupy_array_equal() def check_unpackbits(self, data, xp): a = xp.array(data, dtype=xp.uint8) return xp.unpackbits(a) def test_packbits(self): self.check_packbits([]) self.check_packbits([0]) self.check_packbits([1]) self.check_packbits([0, 1]) self.check_packbits([1, 0, 1, 1, 0, 1, 1, 1]) self.check_packbits([1, 0, 1, 1, 0, 1, 1, 1, 1]) self.check_packbits(numpy.arange(24).reshape((2, 3, 4)) % 2) def test_unpackbits(self): self.check_unpackbits([]) self.check_unpackbits([0]) self.check_unpackbits([1]) self.check_unpackbits([255]) self.check_unpackbits([100, 200, 123, 213])
+ import numpy import unittest from cupy import testing @testing.gpu class TestPacking(unittest.TestCase): _multiprocess_can_split_ = True + + @testing.for_int_dtypes() + @testing.numpy_cupy_array_equal() + def check_packbits(self, data, xp, dtype): + a = xp.array(data, dtype=dtype) + return xp.packbits(a) + + @testing.numpy_cupy_array_equal() + def check_unpackbits(self, data, xp): + a = xp.array(data, dtype=xp.uint8) + return xp.unpackbits(a) + + def test_packbits(self): + self.check_packbits([]) + self.check_packbits([0]) + self.check_packbits([1]) + self.check_packbits([0, 1]) + self.check_packbits([1, 0, 1, 1, 0, 1, 1, 1]) + self.check_packbits([1, 0, 1, 1, 0, 1, 1, 1, 1]) + self.check_packbits(numpy.arange(24).reshape((2, 3, 4)) % 2) + + def test_unpackbits(self): + self.check_unpackbits([]) + self.check_unpackbits([0]) + self.check_unpackbits([1]) + self.check_unpackbits([255]) + self.check_unpackbits([100, 200, 123, 213])
4a4dbfd142e2f8fca3e82d7790ace4ed88bb0b3f
djangocms_spa/urls.py
djangocms_spa/urls.py
from django.conf.urls import url from .views import SpaCmsPageDetailApiView urlpatterns = [ url(r'^(?P<language_code>[\w-]+)/pages/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail_home'), url(r'^(?P<language_code>[\w-]+)/pages/(?P<path>.*)/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail'), ]
from django.conf.urls import url from .views import SpaCmsPageDetailApiView urlpatterns = [ url(r'^pages/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail_home'), url(r'^pages/(?P<path>.*)/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail'), ]
Remove language code from path
Remove language code from path We no longer need the language detection in the URL. The locale middleware already handles the language properly and we can consume it from the request.
Python
mit
dreipol/djangocms-spa,dreipol/djangocms-spa
from django.conf.urls import url from .views import SpaCmsPageDetailApiView urlpatterns = [ - url(r'^(?P<language_code>[\w-]+)/pages/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail_home'), + url(r'^pages/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail_home'), - url(r'^(?P<language_code>[\w-]+)/pages/(?P<path>.*)/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail'), + url(r'^pages/(?P<path>.*)/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail'), ]
Remove language code from path
## Code Before: from django.conf.urls import url from .views import SpaCmsPageDetailApiView urlpatterns = [ url(r'^(?P<language_code>[\w-]+)/pages/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail_home'), url(r'^(?P<language_code>[\w-]+)/pages/(?P<path>.*)/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail'), ] ## Instruction: Remove language code from path ## Code After: from django.conf.urls import url from .views import SpaCmsPageDetailApiView urlpatterns = [ url(r'^pages/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail_home'), url(r'^pages/(?P<path>.*)/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail'), ]
from django.conf.urls import url from .views import SpaCmsPageDetailApiView urlpatterns = [ - url(r'^(?P<language_code>[\w-]+)/pages/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail_home'), ? -------------------------- + url(r'^pages/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail_home'), - url(r'^(?P<language_code>[\w-]+)/pages/(?P<path>.*)/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail'), ? -------------------------- + url(r'^pages/(?P<path>.*)/$', SpaCmsPageDetailApiView.as_view(), name='cms_page_detail'), ]
e2efb3855cd7888b778c3c7ff343c2bdcb942ab0
pushmanager/testing/__init__.py
pushmanager/testing/__init__.py
import testify # don't want all of testify's modules, just its goodies from testify.__init__ import * from mocksettings import MockedSettings from testservlet import AsyncTestCase from testservlet import ServletTestMixin from testservlet import TemplateTestCase from testdb import * __all__ = [ AsyncTestCase, MockedSettings, testify, ServletTestMixin, TemplateTestCase ]
from testify import TestCase from testify import teardown from testify import class_teardown from testify import class_setup_teardown from testify import setup_teardown from testify import setup from testify import class_setup from testify import assert_equal from testify import assert_exactly_one from testify import assert_dicts_equal from testify import assert_in from testify import assert_is from testify import assert_length from testify import assert_not_equal from testify import assert_not_in from testify import assert_raises from testify import assert_sorted_equal __all__ = [ assert_equal, assert_exactly_one, assert_dicts_equal, assert_in, assert_is, assert_length, assert_not_equal, assert_not_in, assert_raises, assert_sorted_equal, class_setup, class_setup_teardown, class_teardown, setup, setup_teardown, teardown, TestCase, ]
Make pushmanager.testing more explicit in imports
Make pushmanager.testing more explicit in imports
Python
apache-2.0
Yelp/pushmanager,YelpArchive/pushmanager,asottile/pushmanager,Yelp/pushmanager,asottile/pushmanager,YelpArchive/pushmanager,YelpArchive/pushmanager,asottile/pushmanager,Yelp/pushmanager,Yelp/pushmanager,YelpArchive/pushmanager
- - import testify - - # don't want all of testify's modules, just its goodies - from testify.__init__ import * - - from mocksettings import MockedSettings - from testservlet import AsyncTestCase + from testify import TestCase - from testservlet import ServletTestMixin - from testservlet import TemplateTestCase + from testify import teardown + from testify import class_teardown + from testify import class_setup_teardown + from testify import setup_teardown - from testdb import * + from testify import setup + from testify import class_setup + from testify import assert_equal + from testify import assert_exactly_one + from testify import assert_dicts_equal + from testify import assert_in + from testify import assert_is + from testify import assert_length + from testify import assert_not_equal + from testify import assert_not_in + from testify import assert_raises + from testify import assert_sorted_equal __all__ = [ + assert_equal, + assert_exactly_one, + assert_dicts_equal, + assert_in, + assert_is, + assert_length, + assert_not_equal, + assert_not_in, + assert_raises, + assert_sorted_equal, + class_setup, + class_setup_teardown, + class_teardown, + setup, + setup_teardown, + teardown, - AsyncTestCase, + TestCase, - MockedSettings, - testify, - ServletTestMixin, - TemplateTestCase ]
Make pushmanager.testing more explicit in imports
## Code Before: import testify # don't want all of testify's modules, just its goodies from testify.__init__ import * from mocksettings import MockedSettings from testservlet import AsyncTestCase from testservlet import ServletTestMixin from testservlet import TemplateTestCase from testdb import * __all__ = [ AsyncTestCase, MockedSettings, testify, ServletTestMixin, TemplateTestCase ] ## Instruction: Make pushmanager.testing more explicit in imports ## Code After: from testify import TestCase from testify import teardown from testify import class_teardown from testify import class_setup_teardown from testify import setup_teardown from testify import setup from testify import class_setup from testify import assert_equal from testify import assert_exactly_one from testify import assert_dicts_equal from testify import assert_in from testify import assert_is from testify import assert_length from testify import assert_not_equal from testify import assert_not_in from testify import assert_raises from testify import assert_sorted_equal __all__ = [ assert_equal, assert_exactly_one, assert_dicts_equal, assert_in, assert_is, assert_length, assert_not_equal, assert_not_in, assert_raises, assert_sorted_equal, class_setup, class_setup_teardown, class_teardown, setup, setup_teardown, teardown, TestCase, ]
- - import testify - - # don't want all of testify's modules, just its goodies - from testify.__init__ import * - - from mocksettings import MockedSettings - from testservlet import AsyncTestCase ? ^^^^^^^ ----- + from testify import TestCase ? ^^^ - from testservlet import ServletTestMixin - from testservlet import TemplateTestCase + from testify import teardown + from testify import class_teardown + from testify import class_setup_teardown + from testify import setup_teardown - from testdb import * ? ^^ ^ + from testify import setup ? ^^^ ^^^^^ + from testify import class_setup + from testify import assert_equal + from testify import assert_exactly_one + from testify import assert_dicts_equal + from testify import assert_in + from testify import assert_is + from testify import assert_length + from testify import assert_not_equal + from testify import assert_not_in + from testify import assert_raises + from testify import assert_sorted_equal __all__ = [ + assert_equal, + assert_exactly_one, + assert_dicts_equal, + assert_in, + assert_is, + assert_length, + assert_not_equal, + assert_not_in, + assert_raises, + assert_sorted_equal, + class_setup, + class_setup_teardown, + class_teardown, + setup, + setup_teardown, + teardown, - AsyncTestCase, ? ----- + TestCase, - MockedSettings, - testify, - ServletTestMixin, - TemplateTestCase ]
1124da4ea6c30f0c36854ec938aa9ea60cca73d4
djangoappengine/db/expressions.py
djangoappengine/db/expressions.py
from django.db.models.sql.expressions import SQLEvaluator from django.db.models.expressions import ExpressionNode OPERATION_MAP = { ExpressionNode.ADD: lambda x, y: x + y, ExpressionNode.SUB: lambda x, y: x - y, ExpressionNode.MUL: lambda x, y: x * y, ExpressionNode.DIV: lambda x, y: x / y, ExpressionNode.MOD: lambda x, y: x % y, ExpressionNode.BITAND: lambda x, y: x & y, ExpressionNode.BITOR: lambda x, y: x | y, } class ExpressionEvaluator(SQLEvaluator): def __init__(self, expression, query, entity, allow_joins=True): super(ExpressionEvaluator, self).__init__(expression, query, allow_joins) self.entity = entity ################################################## # Vistor methods for final expression evaluation # ################################################## def evaluate_node(self, node, qn, connection): values = [] for child in node.children: if hasattr(child, 'evaluate'): value = child.evaluate(self, qn, connection) else: value = child if value is not None: values.append(value) return OPERATION_MAP[node.connector](*values) def evaluate_leaf(self, node, qn, connection): return self.entity[qn(self.cols[node][1])]
from django.db.models.sql.expressions import SQLEvaluator from django.db.models.expressions import ExpressionNode OPERATION_MAP = { ExpressionNode.ADD: lambda x, y: x + y, ExpressionNode.SUB: lambda x, y: x - y, ExpressionNode.MUL: lambda x, y: x * y, ExpressionNode.DIV: lambda x, y: x / y, ExpressionNode.MOD: lambda x, y: x % y, ExpressionNode.BITAND: lambda x, y: x & y, ExpressionNode.BITOR: lambda x, y: x | y, } class ExpressionEvaluator(SQLEvaluator): def __init__(self, expression, query, entity, allow_joins=True): super(ExpressionEvaluator, self).__init__(expression, query, allow_joins) self.entity = entity ################################################## # Vistor methods for final expression evaluation # ################################################## def evaluate_node(self, node, qn, connection): values = [] for child in node.children: if hasattr(child, 'evaluate'): value = child.evaluate(self, qn, connection) else: value = child if value is not None: values.append(value) return OPERATION_MAP[node.connector](*values) def evaluate_leaf(self, node, qn, connection): col = None for n, c in self.cols: if n is node: col = c break if col is None: raise ValueError("Given node not found") return self.entity[qn(col[1])]
Fix ExpressionEvalutator for Django 1.5 changes to cols property
Fix ExpressionEvalutator for Django 1.5 changes to cols property
Python
bsd-3-clause
django-nonrel/djangoappengine,Implisit/djangoappengine,dwdraju/djangoappengine
from django.db.models.sql.expressions import SQLEvaluator from django.db.models.expressions import ExpressionNode OPERATION_MAP = { ExpressionNode.ADD: lambda x, y: x + y, ExpressionNode.SUB: lambda x, y: x - y, ExpressionNode.MUL: lambda x, y: x * y, ExpressionNode.DIV: lambda x, y: x / y, ExpressionNode.MOD: lambda x, y: x % y, ExpressionNode.BITAND: lambda x, y: x & y, ExpressionNode.BITOR: lambda x, y: x | y, } class ExpressionEvaluator(SQLEvaluator): def __init__(self, expression, query, entity, allow_joins=True): super(ExpressionEvaluator, self).__init__(expression, query, allow_joins) self.entity = entity ################################################## # Vistor methods for final expression evaluation # ################################################## def evaluate_node(self, node, qn, connection): values = [] for child in node.children: if hasattr(child, 'evaluate'): value = child.evaluate(self, qn, connection) else: value = child if value is not None: values.append(value) return OPERATION_MAP[node.connector](*values) def evaluate_leaf(self, node, qn, connection): + col = None + for n, c in self.cols: + if n is node: + col = c + break + if col is None: + raise ValueError("Given node not found") - return self.entity[qn(self.cols[node][1])] + return self.entity[qn(col[1])]
Fix ExpressionEvalutator for Django 1.5 changes to cols property
## Code Before: from django.db.models.sql.expressions import SQLEvaluator from django.db.models.expressions import ExpressionNode OPERATION_MAP = { ExpressionNode.ADD: lambda x, y: x + y, ExpressionNode.SUB: lambda x, y: x - y, ExpressionNode.MUL: lambda x, y: x * y, ExpressionNode.DIV: lambda x, y: x / y, ExpressionNode.MOD: lambda x, y: x % y, ExpressionNode.BITAND: lambda x, y: x & y, ExpressionNode.BITOR: lambda x, y: x | y, } class ExpressionEvaluator(SQLEvaluator): def __init__(self, expression, query, entity, allow_joins=True): super(ExpressionEvaluator, self).__init__(expression, query, allow_joins) self.entity = entity ################################################## # Vistor methods for final expression evaluation # ################################################## def evaluate_node(self, node, qn, connection): values = [] for child in node.children: if hasattr(child, 'evaluate'): value = child.evaluate(self, qn, connection) else: value = child if value is not None: values.append(value) return OPERATION_MAP[node.connector](*values) def evaluate_leaf(self, node, qn, connection): return self.entity[qn(self.cols[node][1])] ## Instruction: Fix ExpressionEvalutator for Django 1.5 changes to cols property ## Code After: from django.db.models.sql.expressions import SQLEvaluator from django.db.models.expressions import ExpressionNode OPERATION_MAP = { ExpressionNode.ADD: lambda x, y: x + y, ExpressionNode.SUB: lambda x, y: x - y, ExpressionNode.MUL: lambda x, y: x * y, ExpressionNode.DIV: lambda x, y: x / y, ExpressionNode.MOD: lambda x, y: x % y, ExpressionNode.BITAND: lambda x, y: x & y, ExpressionNode.BITOR: lambda x, y: x | y, } class ExpressionEvaluator(SQLEvaluator): def __init__(self, expression, query, entity, allow_joins=True): super(ExpressionEvaluator, self).__init__(expression, query, allow_joins) self.entity = entity ################################################## # Vistor methods for final expression evaluation # ################################################## def evaluate_node(self, node, qn, connection): values = [] for child in node.children: if hasattr(child, 'evaluate'): value = child.evaluate(self, qn, connection) else: value = child if value is not None: values.append(value) return OPERATION_MAP[node.connector](*values) def evaluate_leaf(self, node, qn, connection): col = None for n, c in self.cols: if n is node: col = c break if col is None: raise ValueError("Given node not found") return self.entity[qn(col[1])]
from django.db.models.sql.expressions import SQLEvaluator from django.db.models.expressions import ExpressionNode OPERATION_MAP = { ExpressionNode.ADD: lambda x, y: x + y, ExpressionNode.SUB: lambda x, y: x - y, ExpressionNode.MUL: lambda x, y: x * y, ExpressionNode.DIV: lambda x, y: x / y, ExpressionNode.MOD: lambda x, y: x % y, ExpressionNode.BITAND: lambda x, y: x & y, ExpressionNode.BITOR: lambda x, y: x | y, } class ExpressionEvaluator(SQLEvaluator): def __init__(self, expression, query, entity, allow_joins=True): super(ExpressionEvaluator, self).__init__(expression, query, allow_joins) self.entity = entity ################################################## # Vistor methods for final expression evaluation # ################################################## def evaluate_node(self, node, qn, connection): values = [] for child in node.children: if hasattr(child, 'evaluate'): value = child.evaluate(self, qn, connection) else: value = child if value is not None: values.append(value) return OPERATION_MAP[node.connector](*values) def evaluate_leaf(self, node, qn, connection): + col = None + for n, c in self.cols: + if n is node: + col = c + break + if col is None: + raise ValueError("Given node not found") - return self.entity[qn(self.cols[node][1])] ? ----- ------- + return self.entity[qn(col[1])]
93cb07ed61f17a1debbe353963120ab117598f3f
src/yunohost/utils/yunopaste.py
src/yunohost/utils/yunopaste.py
import requests import json import errno from moulinette.core import MoulinetteError def yunopaste(data): paste_server = "https://paste.yunohost.org" try: r = requests.post("%s/documents" % paste_server, data=data, timeout=30) except Exception as e: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s" % str(e)) if r.status_code != 200: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s" % r.text) try: url = json.loads(r.text)["key"] except: raise MoulinetteError(errno.EIO, "Uhoh, couldn't parse the answer from paste.yunohost.org : %s" % r.text) return "%s/raw/%s" % (paste_server, url)
import requests import json import errno from moulinette.core import MoulinetteError def yunopaste(data): paste_server = "https://paste.yunohost.org" try: r = requests.post("%s/documents" % paste_server, data=data, timeout=30) except Exception as e: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s" % str(e)) if r.status_code != 200: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s, %s" % (r.status_code, r.text)) try: url = json.loads(r.text)["key"] except: raise MoulinetteError(errno.EIO, "Uhoh, couldn't parse the answer from paste.yunohost.org : %s" % r.text) return "%s/raw/%s" % (paste_server, url)
Add status code to error message
Add status code to error message
Python
agpl-3.0
YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/moulinette-yunohost,YunoHost/yunohost,YunoHost/yunohost
import requests import json import errno from moulinette.core import MoulinetteError def yunopaste(data): paste_server = "https://paste.yunohost.org" try: r = requests.post("%s/documents" % paste_server, data=data, timeout=30) except Exception as e: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s" % str(e)) if r.status_code != 200: raise MoulinetteError(errno.EIO, - "Something wrong happened while trying to paste data on paste.yunohost.org : %s" % r.text) + "Something wrong happened while trying to paste data on paste.yunohost.org : %s, %s" % (r.status_code, r.text)) try: url = json.loads(r.text)["key"] except: raise MoulinetteError(errno.EIO, "Uhoh, couldn't parse the answer from paste.yunohost.org : %s" % r.text) return "%s/raw/%s" % (paste_server, url)
Add status code to error message
## Code Before: import requests import json import errno from moulinette.core import MoulinetteError def yunopaste(data): paste_server = "https://paste.yunohost.org" try: r = requests.post("%s/documents" % paste_server, data=data, timeout=30) except Exception as e: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s" % str(e)) if r.status_code != 200: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s" % r.text) try: url = json.loads(r.text)["key"] except: raise MoulinetteError(errno.EIO, "Uhoh, couldn't parse the answer from paste.yunohost.org : %s" % r.text) return "%s/raw/%s" % (paste_server, url) ## Instruction: Add status code to error message ## Code After: import requests import json import errno from moulinette.core import MoulinetteError def yunopaste(data): paste_server = "https://paste.yunohost.org" try: r = requests.post("%s/documents" % paste_server, data=data, timeout=30) except Exception as e: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s" % str(e)) if r.status_code != 200: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s, %s" % (r.status_code, r.text)) try: url = json.loads(r.text)["key"] except: raise MoulinetteError(errno.EIO, "Uhoh, couldn't parse the answer from paste.yunohost.org : %s" % r.text) return "%s/raw/%s" % (paste_server, url)
import requests import json import errno from moulinette.core import MoulinetteError def yunopaste(data): paste_server = "https://paste.yunohost.org" try: r = requests.post("%s/documents" % paste_server, data=data, timeout=30) except Exception as e: raise MoulinetteError(errno.EIO, "Something wrong happened while trying to paste data on paste.yunohost.org : %s" % str(e)) if r.status_code != 200: raise MoulinetteError(errno.EIO, - "Something wrong happened while trying to paste data on paste.yunohost.org : %s" % r.text) + "Something wrong happened while trying to paste data on paste.yunohost.org : %s, %s" % (r.status_code, r.text)) ? ++++ ++++++++++++++++ + try: url = json.loads(r.text)["key"] except: raise MoulinetteError(errno.EIO, "Uhoh, couldn't parse the answer from paste.yunohost.org : %s" % r.text) return "%s/raw/%s" % (paste_server, url)
ec7e03b778c8f6b47af4647d440b4838221a4e33
jose/constants.py
jose/constants.py
import hashlib class Algorithms(object): NONE = 'none' HS256 = 'HS256' HS384 = 'HS384' HS512 = 'HS512' RS256 = 'RS256' RS384 = 'RS384' RS512 = 'RS512' ES256 = 'ES256' ES384 = 'ES384' ES512 = 'ES512' HMAC = set([HS256, HS384, HS512]) RSA = set([RS256, RS384, RS512]) EC = set([ES256, ES384, ES512]) SUPPORTED = HMAC.union(RSA).union(EC) ALL = SUPPORTED.union([NONE]) HASHES = { HS256: hashlib.sha256, HS384: hashlib.sha384, HS512: hashlib.sha512, RS256: hashlib.sha256, RS384: hashlib.sha384, RS512: hashlib.sha512, ES256: hashlib.sha256, ES384: hashlib.sha384, ES512: hashlib.sha512, } KEYS = {} ALGORITHMS = Algorithms()
import hashlib class Algorithms(object): NONE = 'none' HS256 = 'HS256' HS384 = 'HS384' HS512 = 'HS512' RS256 = 'RS256' RS384 = 'RS384' RS512 = 'RS512' ES256 = 'ES256' ES384 = 'ES384' ES512 = 'ES512' HMAC = {HS256, HS384, HS512} RSA = {RS256, RS384, RS512} EC = {ES256, ES384, ES512} SUPPORTED = HMAC.union(RSA).union(EC) ALL = SUPPORTED.union([NONE]) HASHES = { HS256: hashlib.sha256, HS384: hashlib.sha384, HS512: hashlib.sha512, RS256: hashlib.sha256, RS384: hashlib.sha384, RS512: hashlib.sha512, ES256: hashlib.sha256, ES384: hashlib.sha384, ES512: hashlib.sha512, } KEYS = {} ALGORITHMS = Algorithms()
Replace function calls with set literals
Replace function calls with set literals
Python
mit
mpdavis/python-jose
import hashlib class Algorithms(object): NONE = 'none' HS256 = 'HS256' HS384 = 'HS384' HS512 = 'HS512' RS256 = 'RS256' RS384 = 'RS384' RS512 = 'RS512' ES256 = 'ES256' ES384 = 'ES384' ES512 = 'ES512' - HMAC = set([HS256, HS384, HS512]) + HMAC = {HS256, HS384, HS512} - RSA = set([RS256, RS384, RS512]) + RSA = {RS256, RS384, RS512} - EC = set([ES256, ES384, ES512]) + EC = {ES256, ES384, ES512} SUPPORTED = HMAC.union(RSA).union(EC) ALL = SUPPORTED.union([NONE]) HASHES = { HS256: hashlib.sha256, HS384: hashlib.sha384, HS512: hashlib.sha512, RS256: hashlib.sha256, RS384: hashlib.sha384, RS512: hashlib.sha512, ES256: hashlib.sha256, ES384: hashlib.sha384, ES512: hashlib.sha512, } KEYS = {} ALGORITHMS = Algorithms()
Replace function calls with set literals
## Code Before: import hashlib class Algorithms(object): NONE = 'none' HS256 = 'HS256' HS384 = 'HS384' HS512 = 'HS512' RS256 = 'RS256' RS384 = 'RS384' RS512 = 'RS512' ES256 = 'ES256' ES384 = 'ES384' ES512 = 'ES512' HMAC = set([HS256, HS384, HS512]) RSA = set([RS256, RS384, RS512]) EC = set([ES256, ES384, ES512]) SUPPORTED = HMAC.union(RSA).union(EC) ALL = SUPPORTED.union([NONE]) HASHES = { HS256: hashlib.sha256, HS384: hashlib.sha384, HS512: hashlib.sha512, RS256: hashlib.sha256, RS384: hashlib.sha384, RS512: hashlib.sha512, ES256: hashlib.sha256, ES384: hashlib.sha384, ES512: hashlib.sha512, } KEYS = {} ALGORITHMS = Algorithms() ## Instruction: Replace function calls with set literals ## Code After: import hashlib class Algorithms(object): NONE = 'none' HS256 = 'HS256' HS384 = 'HS384' HS512 = 'HS512' RS256 = 'RS256' RS384 = 'RS384' RS512 = 'RS512' ES256 = 'ES256' ES384 = 'ES384' ES512 = 'ES512' HMAC = {HS256, HS384, HS512} RSA = {RS256, RS384, RS512} EC = {ES256, ES384, ES512} SUPPORTED = HMAC.union(RSA).union(EC) ALL = SUPPORTED.union([NONE]) HASHES = { HS256: hashlib.sha256, HS384: hashlib.sha384, HS512: hashlib.sha512, RS256: hashlib.sha256, RS384: hashlib.sha384, RS512: hashlib.sha512, ES256: hashlib.sha256, ES384: hashlib.sha384, ES512: hashlib.sha512, } KEYS = {} ALGORITHMS = Algorithms()
import hashlib class Algorithms(object): NONE = 'none' HS256 = 'HS256' HS384 = 'HS384' HS512 = 'HS512' RS256 = 'RS256' RS384 = 'RS384' RS512 = 'RS512' ES256 = 'ES256' ES384 = 'ES384' ES512 = 'ES512' - HMAC = set([HS256, HS384, HS512]) ? ^^^^^ ^^ + HMAC = {HS256, HS384, HS512} ? ^ ^ - RSA = set([RS256, RS384, RS512]) ? ^^^^^ ^^ + RSA = {RS256, RS384, RS512} ? ^ ^ - EC = set([ES256, ES384, ES512]) ? ^^^^^ ^^ + EC = {ES256, ES384, ES512} ? ^ ^ SUPPORTED = HMAC.union(RSA).union(EC) ALL = SUPPORTED.union([NONE]) HASHES = { HS256: hashlib.sha256, HS384: hashlib.sha384, HS512: hashlib.sha512, RS256: hashlib.sha256, RS384: hashlib.sha384, RS512: hashlib.sha512, ES256: hashlib.sha256, ES384: hashlib.sha384, ES512: hashlib.sha512, } KEYS = {} ALGORITHMS = Algorithms()
87e5d0e5e92ed5f94e4238e73453934abc7835dd
src/tutorials/code/python/chat/5.py
src/tutorials/code/python/chat/5.py
from chatty import create import config from tornado.ioloop import PeriodicCallback, IOLoop from functools import partial if __name__ == "__main__": chat = create(config) # Tell chat to authenticate with the beam server. It'll throw # a chatty.errors.NotAuthenticatedError if it fails. chat.authenticate(config.CHANNEL) # Listen for incoming messages. When they come in, just print them. chat.on("message", partial(print, "RECEIVE:")) # Create a timer that sends the message "Hi!" every second. PeriodicCallback( lambda: chat.message('Hi!'), 1000 ).start() # Start the tornado event loop. IOLoop.instance().start()
from chatty import create import config from tornado.ioloop import PeriodicCallback, IOLoop if __name__ == "__main__": chat = create(config) # Tell chat to authenticate with the beam server. It'll throw # a chatty.errors.NotAuthenticatedError if it fails. chat.authenticate(config.CHANNEL) # Handle incoming messages. def on_message(message): print("RECEIVE:", message) # Listen for incoming messages. When they come in, just print them. chat.on("message", on_message) # Create a timer that sends the message "Hi!" every second. PeriodicCallback( lambda: chat.message('Hi!'), 1000 ).start() # Start the tornado event loop. IOLoop.instance().start()
Replace partial with a function definition
Replace partial with a function definition Fix indentation, as well.
Python
mit
WatchBeam/developers,WatchBeam/developers,WatchBeam/developers,WatchBeam/developers,WatchBeam/developers
from chatty import create import config from tornado.ioloop import PeriodicCallback, IOLoop - from functools import partial if __name__ == "__main__": chat = create(config) - # Tell chat to authenticate with the beam server. It'll throw + # Tell chat to authenticate with the beam server. It'll throw - # a chatty.errors.NotAuthenticatedError if it fails. + # a chatty.errors.NotAuthenticatedError if it fails. - chat.authenticate(config.CHANNEL) + chat.authenticate(config.CHANNEL) + # Handle incoming messages. + def on_message(message): + print("RECEIVE:", message) + - # Listen for incoming messages. When they come in, just print them. + # Listen for incoming messages. When they come in, just print them. - chat.on("message", partial(print, "RECEIVE:")) + chat.on("message", on_message) - # Create a timer that sends the message "Hi!" every second. + # Create a timer that sends the message "Hi!" every second. - PeriodicCallback( + PeriodicCallback( - lambda: chat.message('Hi!'), + lambda: chat.message('Hi!'), - 1000 + 1000 - ).start() + ).start() - # Start the tornado event loop. + # Start the tornado event loop. - IOLoop.instance().start() + IOLoop.instance().start() +
Replace partial with a function definition
## Code Before: from chatty import create import config from tornado.ioloop import PeriodicCallback, IOLoop from functools import partial if __name__ == "__main__": chat = create(config) # Tell chat to authenticate with the beam server. It'll throw # a chatty.errors.NotAuthenticatedError if it fails. chat.authenticate(config.CHANNEL) # Listen for incoming messages. When they come in, just print them. chat.on("message", partial(print, "RECEIVE:")) # Create a timer that sends the message "Hi!" every second. PeriodicCallback( lambda: chat.message('Hi!'), 1000 ).start() # Start the tornado event loop. IOLoop.instance().start() ## Instruction: Replace partial with a function definition ## Code After: from chatty import create import config from tornado.ioloop import PeriodicCallback, IOLoop if __name__ == "__main__": chat = create(config) # Tell chat to authenticate with the beam server. It'll throw # a chatty.errors.NotAuthenticatedError if it fails. chat.authenticate(config.CHANNEL) # Handle incoming messages. def on_message(message): print("RECEIVE:", message) # Listen for incoming messages. When they come in, just print them. chat.on("message", on_message) # Create a timer that sends the message "Hi!" every second. PeriodicCallback( lambda: chat.message('Hi!'), 1000 ).start() # Start the tornado event loop. IOLoop.instance().start()
from chatty import create import config from tornado.ioloop import PeriodicCallback, IOLoop - from functools import partial if __name__ == "__main__": chat = create(config) - # Tell chat to authenticate with the beam server. It'll throw + # Tell chat to authenticate with the beam server. It'll throw ? ++++ - # a chatty.errors.NotAuthenticatedError if it fails. + # a chatty.errors.NotAuthenticatedError if it fails. ? ++++ - chat.authenticate(config.CHANNEL) + chat.authenticate(config.CHANNEL) ? ++++ + # Handle incoming messages. + def on_message(message): + print("RECEIVE:", message) + - # Listen for incoming messages. When they come in, just print them. + # Listen for incoming messages. When they come in, just print them. ? ++++ - chat.on("message", partial(print, "RECEIVE:")) + chat.on("message", on_message) - # Create a timer that sends the message "Hi!" every second. + # Create a timer that sends the message "Hi!" every second. ? ++++ - PeriodicCallback( + PeriodicCallback( ? ++++ - lambda: chat.message('Hi!'), + lambda: chat.message('Hi!'), ? ++++ - 1000 + 1000 ? ++++ - ).start() + ).start() ? ++++ - # Start the tornado event loop. + # Start the tornado event loop. ? ++++ - IOLoop.instance().start() + IOLoop.instance().start() ? ++++
411117bf057e8835b6c9140b6a86b7ea85c6e80d
taskrunner/runners/result.py
taskrunner/runners/result.py
class Result: def __init__(self, return_code, stdout, stderr): self.return_code = return_code self.stdout = stdout self.stderr = stderr self.succeeded = self.return_code == 0 self.failed = not self.succeeded self.stdout_lines = stdout.splitlines() if stdout else [] self.stderr_lines = stderr.splitlines() if stderr else []
from ..util import cached_property class Result: def __init__(self, return_code, stdout, stderr): self.return_code = return_code self.stdout = stdout self.stderr = stderr self.succeeded = self.return_code == 0 self.failed = not self.succeeded @cached_property def stdout_lines(self): return self.stdout.splitlines() if self.stdout else [] @cached_property def stderr_lines(self): return self.stderr.splitlines() if self.stderr else []
Make Result.stdout_lines and stderr_lines cached properties
Make Result.stdout_lines and stderr_lines cached properties I guess it probably doesn't matter much for performance, but we might as well avoid splitting output into lines eagerly since it's typically not used.
Python
mit
wylee/runcommands,wylee/runcommands
+ from ..util import cached_property + class Result: def __init__(self, return_code, stdout, stderr): self.return_code = return_code self.stdout = stdout self.stderr = stderr self.succeeded = self.return_code == 0 self.failed = not self.succeeded - self.stdout_lines = stdout.splitlines() if stdout else [] - self.stderr_lines = stderr.splitlines() if stderr else [] + @cached_property + def stdout_lines(self): + return self.stdout.splitlines() if self.stdout else [] + + @cached_property + def stderr_lines(self): + return self.stderr.splitlines() if self.stderr else [] +
Make Result.stdout_lines and stderr_lines cached properties
## Code Before: class Result: def __init__(self, return_code, stdout, stderr): self.return_code = return_code self.stdout = stdout self.stderr = stderr self.succeeded = self.return_code == 0 self.failed = not self.succeeded self.stdout_lines = stdout.splitlines() if stdout else [] self.stderr_lines = stderr.splitlines() if stderr else [] ## Instruction: Make Result.stdout_lines and stderr_lines cached properties ## Code After: from ..util import cached_property class Result: def __init__(self, return_code, stdout, stderr): self.return_code = return_code self.stdout = stdout self.stderr = stderr self.succeeded = self.return_code == 0 self.failed = not self.succeeded @cached_property def stdout_lines(self): return self.stdout.splitlines() if self.stdout else [] @cached_property def stderr_lines(self): return self.stderr.splitlines() if self.stderr else []
+ from ..util import cached_property + class Result: def __init__(self, return_code, stdout, stderr): self.return_code = return_code self.stdout = stdout self.stderr = stderr self.succeeded = self.return_code == 0 self.failed = not self.succeeded + + @cached_property + def stdout_lines(self): - self.stdout_lines = stdout.splitlines() if stdout else [] ? --------------- + return self.stdout.splitlines() if self.stdout else [] ? +++++++ +++++ + + @cached_property + def stderr_lines(self): - self.stderr_lines = stderr.splitlines() if stderr else [] ? --------------- + return self.stderr.splitlines() if self.stderr else [] ? +++++++ +++++
6443a0fed1b915745c591f425027d07216d28e12
podium/urls.py
podium/urls.py
from django.conf.urls import url, include from django.contrib import admin from .talks import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^talks/', include('podium.talks.urls')), url(r'^$', views.session_list_view), ]
from django.conf.urls import url, include from django.contrib import admin from .talks import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^talks/', include('podium.talks.urls')), url(r'^', include('podium.talks.urls')), ]
Use include, not a view, for the root URL.
Use include, not a view, for the root URL.
Python
mit
pyatl/podium-django,pyatl/podium-django,pyatl/podium-django
from django.conf.urls import url, include from django.contrib import admin from .talks import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^talks/', include('podium.talks.urls')), - url(r'^$', views.session_list_view), + url(r'^', include('podium.talks.urls')), ]
Use include, not a view, for the root URL.
## Code Before: from django.conf.urls import url, include from django.contrib import admin from .talks import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^talks/', include('podium.talks.urls')), url(r'^$', views.session_list_view), ] ## Instruction: Use include, not a view, for the root URL. ## Code After: from django.conf.urls import url, include from django.contrib import admin from .talks import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^talks/', include('podium.talks.urls')), url(r'^', include('podium.talks.urls')), ]
from django.conf.urls import url, include from django.contrib import admin from .talks import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^talks/', include('podium.talks.urls')), - url(r'^$', views.session_list_view), + url(r'^', include('podium.talks.urls')), ]
d8c8b5ffc1f79fc106dc9e41cc6f1ae4f40d0535
src/mpi4py/futures/_core.py
src/mpi4py/futures/_core.py
try: from concurrent.futures import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, TimeoutError, Future, Executor, wait, as_completed, ) try: # Python 3.7 from concurrent.futures import BrokenExecutor except ImportError: # pragma: no cover BrokenExecutor = RuntimeError try: # Python 3.8 from concurrent.futures import InvalidStateError except ImportError: # pragma: no cover InvalidStateError = CancelledError.__base__ except ImportError: # pragma: no cover from ._base import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, TimeoutError, InvalidStateError, BrokenExecutor, Future, Executor, wait, as_completed, )
try: from concurrent.futures import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, TimeoutError, Future, Executor, wait, as_completed, ) try: # Python 3.7 from concurrent.futures import BrokenExecutor except ImportError: # pragma: no cover class BrokenExecutor(RuntimeError): """The executor has become non-functional.""" try: # Python 3.8 from concurrent.futures import InvalidStateError except ImportError: # pragma: no cover # pylint: disable=too-few-public-methods # pylint: disable=useless-object-inheritance class InvalidStateError(CancelledError.__base__): """The operation is not allowed in this state.""" except ImportError: # pragma: no cover from ._base import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, TimeoutError, InvalidStateError, BrokenExecutor, Future, Executor, wait, as_completed, )
Fix backward compatibility exception types
mpi4py.futures: Fix backward compatibility exception types
Python
bsd-2-clause
mpi4py/mpi4py,mpi4py/mpi4py,mpi4py/mpi4py
try: from concurrent.futures import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, TimeoutError, Future, Executor, wait, as_completed, ) try: # Python 3.7 from concurrent.futures import BrokenExecutor except ImportError: # pragma: no cover - BrokenExecutor = RuntimeError + class BrokenExecutor(RuntimeError): + """The executor has become non-functional.""" try: # Python 3.8 from concurrent.futures import InvalidStateError except ImportError: # pragma: no cover + # pylint: disable=too-few-public-methods + # pylint: disable=useless-object-inheritance - InvalidStateError = CancelledError.__base__ + class InvalidStateError(CancelledError.__base__): + """The operation is not allowed in this state.""" except ImportError: # pragma: no cover from ._base import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, TimeoutError, InvalidStateError, BrokenExecutor, Future, Executor, wait, as_completed, )
Fix backward compatibility exception types
## Code Before: try: from concurrent.futures import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, TimeoutError, Future, Executor, wait, as_completed, ) try: # Python 3.7 from concurrent.futures import BrokenExecutor except ImportError: # pragma: no cover BrokenExecutor = RuntimeError try: # Python 3.8 from concurrent.futures import InvalidStateError except ImportError: # pragma: no cover InvalidStateError = CancelledError.__base__ except ImportError: # pragma: no cover from ._base import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, TimeoutError, InvalidStateError, BrokenExecutor, Future, Executor, wait, as_completed, ) ## Instruction: Fix backward compatibility exception types ## Code After: try: from concurrent.futures import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, TimeoutError, Future, Executor, wait, as_completed, ) try: # Python 3.7 from concurrent.futures import BrokenExecutor except ImportError: # pragma: no cover class BrokenExecutor(RuntimeError): """The executor has become non-functional.""" try: # Python 3.8 from concurrent.futures import InvalidStateError except ImportError: # pragma: no cover # pylint: disable=too-few-public-methods # pylint: disable=useless-object-inheritance class InvalidStateError(CancelledError.__base__): """The operation is not allowed in this state.""" except ImportError: # pragma: no cover from ._base import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, TimeoutError, InvalidStateError, BrokenExecutor, Future, Executor, wait, as_completed, )
try: from concurrent.futures import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, TimeoutError, Future, Executor, wait, as_completed, ) try: # Python 3.7 from concurrent.futures import BrokenExecutor except ImportError: # pragma: no cover - BrokenExecutor = RuntimeError ? ^^^ + class BrokenExecutor(RuntimeError): ? ++++++ ^ ++ + """The executor has become non-functional.""" try: # Python 3.8 from concurrent.futures import InvalidStateError except ImportError: # pragma: no cover + # pylint: disable=too-few-public-methods + # pylint: disable=useless-object-inheritance - InvalidStateError = CancelledError.__base__ ? ^^^ + class InvalidStateError(CancelledError.__base__): ? ++++++ ^ ++ + """The operation is not allowed in this state.""" except ImportError: # pragma: no cover from ._base import ( FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED, CancelledError, TimeoutError, InvalidStateError, BrokenExecutor, Future, Executor, wait, as_completed, )
62ba442ac447dbb4482dd15f70075d224d0e5a0e
scripts/test_conda_build_log.py
scripts/test_conda_build_log.py
import pytest import log_parser import os @pytest.fixture def parsed_log(): logname = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'build.log') gen = list(log_parser.read_log_from_script(logname)) parsed = {built_name: log_parser.parse_conda_build(lines) for name, built_name, lines in gen} return parsed def test_parse_conda_build(parsed_log): # make sure that we have at least one thing that was parsed assert len(parsed_log) >= 1 def test_parse_init(parsed_log): # make sure we are getting the build command out of every single entry for pkg_name, parsed in parsed_log.items(): parsed_init = log_parser.parse_init(parsed['init']) assert 'build_command' in parsed_init def test_parse_build(parsed_log): # make sure we are getting either an error or the build string out of the # build section for pkg_name, parsed in parsed_log.items(): if 'build' not in parsed: # not all packages will successfully build continue # if there is a build section, then parse it parsed_build = log_parser.parse_build(parsed['build']) if parsed_build['built_name'] == 'failed': assert parsed_build['error'] != [] else: assert parsed_build['error'] == []
import pytest import log_parser import os @pytest.fixture def parsed_log(): logname = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'build.log') gen = list(log_parser.read_log_from_script(logname)) parsed = {built_name: log_parser.parse_conda_build(lines) for name, built_name, lines in gen} return parsed def test_parse_conda_build(parsed_log): # make sure that we have at least one thing that was parsed assert len(parsed_log) >= 1 def test_parse_init(parsed_log): # make sure we are getting the build command out of every single entry for pkg_name, parsed in parsed_log.items(): parsed_init = log_parser.parse_init(parsed['init']) assert 'build_command' in parsed_init assert 'err' in parsed_init def test_parse_build(parsed_log): # make sure we are getting either an error or the build string out of the # build section for pkg_name, parsed in parsed_log.items(): if 'build' not in parsed: # not all packages will successfully build continue # if there is a build section, then parse it parsed_build = log_parser.parse_build(parsed['build']) if parsed_build['built_name'] == 'failed': assert parsed_build['error'] != [] else: assert parsed_build['error'] == []
Make sure there is an error field
TST: Make sure there is an error field
Python
bsd-3-clause
NSLS-II/lightsource2-recipes,NSLS-II/auto-build-tagged-recipes,NSLS-II/lightsource2-recipes,NSLS-II/auto-build-tagged-recipes,NSLS-II/lightsource2-recipes,NSLS-II/lightsource2-recipes
import pytest import log_parser import os @pytest.fixture def parsed_log(): logname = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'build.log') gen = list(log_parser.read_log_from_script(logname)) parsed = {built_name: log_parser.parse_conda_build(lines) for name, built_name, lines in gen} return parsed def test_parse_conda_build(parsed_log): # make sure that we have at least one thing that was parsed assert len(parsed_log) >= 1 def test_parse_init(parsed_log): # make sure we are getting the build command out of every single entry for pkg_name, parsed in parsed_log.items(): parsed_init = log_parser.parse_init(parsed['init']) assert 'build_command' in parsed_init + assert 'err' in parsed_init def test_parse_build(parsed_log): # make sure we are getting either an error or the build string out of the # build section for pkg_name, parsed in parsed_log.items(): if 'build' not in parsed: # not all packages will successfully build continue # if there is a build section, then parse it parsed_build = log_parser.parse_build(parsed['build']) if parsed_build['built_name'] == 'failed': assert parsed_build['error'] != [] else: assert parsed_build['error'] == []
Make sure there is an error field
## Code Before: import pytest import log_parser import os @pytest.fixture def parsed_log(): logname = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'build.log') gen = list(log_parser.read_log_from_script(logname)) parsed = {built_name: log_parser.parse_conda_build(lines) for name, built_name, lines in gen} return parsed def test_parse_conda_build(parsed_log): # make sure that we have at least one thing that was parsed assert len(parsed_log) >= 1 def test_parse_init(parsed_log): # make sure we are getting the build command out of every single entry for pkg_name, parsed in parsed_log.items(): parsed_init = log_parser.parse_init(parsed['init']) assert 'build_command' in parsed_init def test_parse_build(parsed_log): # make sure we are getting either an error or the build string out of the # build section for pkg_name, parsed in parsed_log.items(): if 'build' not in parsed: # not all packages will successfully build continue # if there is a build section, then parse it parsed_build = log_parser.parse_build(parsed['build']) if parsed_build['built_name'] == 'failed': assert parsed_build['error'] != [] else: assert parsed_build['error'] == [] ## Instruction: Make sure there is an error field ## Code After: import pytest import log_parser import os @pytest.fixture def parsed_log(): logname = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'build.log') gen = list(log_parser.read_log_from_script(logname)) parsed = {built_name: log_parser.parse_conda_build(lines) for name, built_name, lines in gen} return parsed def test_parse_conda_build(parsed_log): # make sure that we have at least one thing that was parsed assert len(parsed_log) >= 1 def test_parse_init(parsed_log): # make sure we are getting the build command out of every single entry for pkg_name, parsed in parsed_log.items(): parsed_init = log_parser.parse_init(parsed['init']) assert 'build_command' in parsed_init assert 'err' in parsed_init def test_parse_build(parsed_log): # make sure we are getting either an error or the build string out of the # build section for pkg_name, parsed in parsed_log.items(): if 'build' not in parsed: # not all packages will successfully build continue # if there is a build section, then parse it parsed_build = log_parser.parse_build(parsed['build']) if parsed_build['built_name'] == 'failed': assert parsed_build['error'] != [] else: assert parsed_build['error'] == []
import pytest import log_parser import os @pytest.fixture def parsed_log(): logname = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'build.log') gen = list(log_parser.read_log_from_script(logname)) parsed = {built_name: log_parser.parse_conda_build(lines) for name, built_name, lines in gen} return parsed def test_parse_conda_build(parsed_log): # make sure that we have at least one thing that was parsed assert len(parsed_log) >= 1 def test_parse_init(parsed_log): # make sure we are getting the build command out of every single entry for pkg_name, parsed in parsed_log.items(): parsed_init = log_parser.parse_init(parsed['init']) assert 'build_command' in parsed_init + assert 'err' in parsed_init def test_parse_build(parsed_log): # make sure we are getting either an error or the build string out of the # build section for pkg_name, parsed in parsed_log.items(): if 'build' not in parsed: # not all packages will successfully build continue # if there is a build section, then parse it parsed_build = log_parser.parse_build(parsed['build']) if parsed_build['built_name'] == 'failed': assert parsed_build['error'] != [] else: assert parsed_build['error'] == []
91ef89371f7ba99346ba982a3fdb7fc2105a9840
superdesk/users/__init__.py
superdesk/users/__init__.py
from .users import RolesResource, UsersResource from .services import DBUsersService, RolesService, is_admin # noqa import superdesk def init_app(app): endpoint_name = 'users' service = DBUsersService(endpoint_name, backend=superdesk.get_backend()) UsersResource(endpoint_name, app=app, service=service) endpoint_name = 'roles' service = RolesService(endpoint_name, backend=superdesk.get_backend()) RolesResource(endpoint_name, app=app, service=service) superdesk.privilege(name='users', label='User Management', description='User can manage users.') superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.') # Registering with intrinsic privileges because: A user should be allowed to update their own profile. superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])
from .users import RolesResource, UsersResource from .services import UsersService, DBUsersService, RolesService, is_admin # noqa import superdesk def init_app(app): endpoint_name = 'users' service = DBUsersService(endpoint_name, backend=superdesk.get_backend()) UsersResource(endpoint_name, app=app, service=service) endpoint_name = 'roles' service = RolesService(endpoint_name, backend=superdesk.get_backend()) RolesResource(endpoint_name, app=app, service=service) superdesk.privilege(name='users', label='User Management', description='User can manage users.') superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.') # Registering with intrinsic privileges because: A user should be allowed to update their own profile. superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])
Make UsersResource reusable for LDAP
Make UsersResource reusable for LDAP
Python
agpl-3.0
ioanpocol/superdesk-core,plamut/superdesk-core,akintolga/superdesk-core,ancafarcas/superdesk-core,ancafarcas/superdesk-core,nistormihai/superdesk-core,superdesk/superdesk-core,sivakuna-aap/superdesk-core,superdesk/superdesk-core,mdhaman/superdesk-core,petrjasek/superdesk-core,mdhaman/superdesk-core,mugurrus/superdesk-core,mugurrus/superdesk-core,mdhaman/superdesk-core,superdesk/superdesk-core,ioanpocol/superdesk-core,sivakuna-aap/superdesk-core,marwoodandrew/superdesk-core,plamut/superdesk-core,superdesk/superdesk-core,petrjasek/superdesk-core,ioanpocol/superdesk-core,marwoodandrew/superdesk-core,hlmnrmr/superdesk-core,akintolga/superdesk-core,nistormihai/superdesk-core,hlmnrmr/superdesk-core,mugurrus/superdesk-core,petrjasek/superdesk-core,petrjasek/superdesk-core
from .users import RolesResource, UsersResource - from .services import DBUsersService, RolesService, is_admin # noqa + from .services import UsersService, DBUsersService, RolesService, is_admin # noqa import superdesk def init_app(app): endpoint_name = 'users' service = DBUsersService(endpoint_name, backend=superdesk.get_backend()) UsersResource(endpoint_name, app=app, service=service) endpoint_name = 'roles' service = RolesService(endpoint_name, backend=superdesk.get_backend()) RolesResource(endpoint_name, app=app, service=service) superdesk.privilege(name='users', label='User Management', description='User can manage users.') superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.') # Registering with intrinsic privileges because: A user should be allowed to update their own profile. superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])
Make UsersResource reusable for LDAP
## Code Before: from .users import RolesResource, UsersResource from .services import DBUsersService, RolesService, is_admin # noqa import superdesk def init_app(app): endpoint_name = 'users' service = DBUsersService(endpoint_name, backend=superdesk.get_backend()) UsersResource(endpoint_name, app=app, service=service) endpoint_name = 'roles' service = RolesService(endpoint_name, backend=superdesk.get_backend()) RolesResource(endpoint_name, app=app, service=service) superdesk.privilege(name='users', label='User Management', description='User can manage users.') superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.') # Registering with intrinsic privileges because: A user should be allowed to update their own profile. superdesk.intrinsic_privilege(resource_name='users', method=['PATCH']) ## Instruction: Make UsersResource reusable for LDAP ## Code After: from .users import RolesResource, UsersResource from .services import UsersService, DBUsersService, RolesService, is_admin # noqa import superdesk def init_app(app): endpoint_name = 'users' service = DBUsersService(endpoint_name, backend=superdesk.get_backend()) UsersResource(endpoint_name, app=app, service=service) endpoint_name = 'roles' service = RolesService(endpoint_name, backend=superdesk.get_backend()) RolesResource(endpoint_name, app=app, service=service) superdesk.privilege(name='users', label='User Management', description='User can manage users.') superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.') # Registering with intrinsic privileges because: A user should be allowed to update their own profile. superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])
from .users import RolesResource, UsersResource - from .services import DBUsersService, RolesService, is_admin # noqa + from .services import UsersService, DBUsersService, RolesService, is_admin # noqa ? ++++++++++++++ import superdesk def init_app(app): endpoint_name = 'users' service = DBUsersService(endpoint_name, backend=superdesk.get_backend()) UsersResource(endpoint_name, app=app, service=service) endpoint_name = 'roles' service = RolesService(endpoint_name, backend=superdesk.get_backend()) RolesResource(endpoint_name, app=app, service=service) superdesk.privilege(name='users', label='User Management', description='User can manage users.') superdesk.privilege(name='roles', label='Roles Management', description='User can manage roles.') # Registering with intrinsic privileges because: A user should be allowed to update their own profile. superdesk.intrinsic_privilege(resource_name='users', method=['PATCH'])
7895b0a39694e88ed1bdd425c69fb747b7531c59
indico/testing/mocks.py
indico/testing/mocks.py
class MockConferenceHolder: # This class is monkeypatched on top of the real conferenceholder _events = {} def __init__(self): pass @classmethod def add(cls, event): if event.id in cls._events: __tracebackhide__ = True raise Exception("Event '{}' already exists".format(event.id)) cls._events[event.id] = event @classmethod def remove(cls, event): del cls._events[event.id] @classmethod def getById(cls, id_): return cls._events.get(id_) class MockConference(object): def __repr__(self): return '<MockConference({})>'.format(self.id) def getId(self): return self.id
class MockConferenceHolder: # This class is monkeypatched on top of the real conferenceholder _events = {} def __init__(self): pass @classmethod def add(cls, event): if event.id in cls._events: __tracebackhide__ = True raise Exception("Event '{}' already exists".format(event.id)) cls._events[int(event.id)] = event @classmethod def remove(cls, event): del cls._events[int(event.id)] @classmethod def getById(cls, id_, quiet=None): return cls._events.get(int(id_)) class MockConference(object): def __repr__(self): return '<MockConference({})>'.format(self.id) def getId(self): return self.id
Fix str/int usage in MockConferenceHolder
Fix str/int usage in MockConferenceHolder
Python
mit
indico/indico,ThiefMaster/indico,indico/indico,OmeGak/indico,ThiefMaster/indico,OmeGak/indico,mic4ael/indico,DirkHoffmann/indico,mvidalgarcia/indico,mvidalgarcia/indico,OmeGak/indico,pferreir/indico,ThiefMaster/indico,mic4ael/indico,pferreir/indico,DirkHoffmann/indico,ThiefMaster/indico,OmeGak/indico,mic4ael/indico,indico/indico,mvidalgarcia/indico,pferreir/indico,mic4ael/indico,pferreir/indico,mvidalgarcia/indico,DirkHoffmann/indico,DirkHoffmann/indico,indico/indico
class MockConferenceHolder: # This class is monkeypatched on top of the real conferenceholder _events = {} def __init__(self): pass @classmethod def add(cls, event): if event.id in cls._events: __tracebackhide__ = True raise Exception("Event '{}' already exists".format(event.id)) - cls._events[event.id] = event + cls._events[int(event.id)] = event @classmethod def remove(cls, event): - del cls._events[event.id] + del cls._events[int(event.id)] @classmethod - def getById(cls, id_): + def getById(cls, id_, quiet=None): - return cls._events.get(id_) + return cls._events.get(int(id_)) class MockConference(object): def __repr__(self): return '<MockConference({})>'.format(self.id) def getId(self): return self.id
Fix str/int usage in MockConferenceHolder
## Code Before: class MockConferenceHolder: # This class is monkeypatched on top of the real conferenceholder _events = {} def __init__(self): pass @classmethod def add(cls, event): if event.id in cls._events: __tracebackhide__ = True raise Exception("Event '{}' already exists".format(event.id)) cls._events[event.id] = event @classmethod def remove(cls, event): del cls._events[event.id] @classmethod def getById(cls, id_): return cls._events.get(id_) class MockConference(object): def __repr__(self): return '<MockConference({})>'.format(self.id) def getId(self): return self.id ## Instruction: Fix str/int usage in MockConferenceHolder ## Code After: class MockConferenceHolder: # This class is monkeypatched on top of the real conferenceholder _events = {} def __init__(self): pass @classmethod def add(cls, event): if event.id in cls._events: __tracebackhide__ = True raise Exception("Event '{}' already exists".format(event.id)) cls._events[int(event.id)] = event @classmethod def remove(cls, event): del cls._events[int(event.id)] @classmethod def getById(cls, id_, quiet=None): return cls._events.get(int(id_)) class MockConference(object): def __repr__(self): return '<MockConference({})>'.format(self.id) def getId(self): return self.id
class MockConferenceHolder: # This class is monkeypatched on top of the real conferenceholder _events = {} def __init__(self): pass @classmethod def add(cls, event): if event.id in cls._events: __tracebackhide__ = True raise Exception("Event '{}' already exists".format(event.id)) - cls._events[event.id] = event + cls._events[int(event.id)] = event ? ++++ + @classmethod def remove(cls, event): - del cls._events[event.id] + del cls._events[int(event.id)] ? ++++ + @classmethod - def getById(cls, id_): + def getById(cls, id_, quiet=None): ? ++++++++++++ - return cls._events.get(id_) + return cls._events.get(int(id_)) ? ++++ + class MockConference(object): def __repr__(self): return '<MockConference({})>'.format(self.id) def getId(self): return self.id
f8aae767944cb6fe6163eb3eb99d08b12458060f
GoogleCalendarV3/setup.py
GoogleCalendarV3/setup.py
from distutils.core import setup setup( name='GoogleCalendarV3', version='0.1.1', author='Ashutosh Priyadarshy', author_email='static@siftcal.com', packages=['google_calendar_v3', 'google_calendar_v3.test'], scripts=['bin/example.py'], url='http://www.github.com/priyadarshy/google-calendar-v3/', license='LICENSE.txt', description='Python Client for Google Calendar API V3.', long_description=open('README.txt').read(), install_requires=[ "requests-oauthlib >= 0.4.0", ], )
from distutils.core import setup setup( name='GoogleCalendarV3', version='0.1.2', author='Ashutosh Priyadarshy', author_email='static@siftcal.com', packages=['google_calendar_v3', 'google_calendar_v3.test'], scripts=['bin/example.py'], url='http://www.github.com/priyadarshy/google-calendar-v3/', license='LICENSE.txt', description='Python Client for Google Calendar API V3.', long_description=open('README.txt').read(), install_requires=[ "requests >= 2.3.0", "requests-oauthlib >= 0.4.0" ], )
Update dependencies and update version.
Update dependencies and update version.
Python
apache-2.0
priyadarshy/google-calendar-v3,mbrondani/google-calendar-v3
from distutils.core import setup setup( name='GoogleCalendarV3', - version='0.1.1', + version='0.1.2', author='Ashutosh Priyadarshy', author_email='static@siftcal.com', packages=['google_calendar_v3', 'google_calendar_v3.test'], scripts=['bin/example.py'], url='http://www.github.com/priyadarshy/google-calendar-v3/', license='LICENSE.txt', description='Python Client for Google Calendar API V3.', long_description=open('README.txt').read(), install_requires=[ + "requests >= 2.3.0", - "requests-oauthlib >= 0.4.0", + "requests-oauthlib >= 0.4.0" ], )
Update dependencies and update version.
## Code Before: from distutils.core import setup setup( name='GoogleCalendarV3', version='0.1.1', author='Ashutosh Priyadarshy', author_email='static@siftcal.com', packages=['google_calendar_v3', 'google_calendar_v3.test'], scripts=['bin/example.py'], url='http://www.github.com/priyadarshy/google-calendar-v3/', license='LICENSE.txt', description='Python Client for Google Calendar API V3.', long_description=open('README.txt').read(), install_requires=[ "requests-oauthlib >= 0.4.0", ], ) ## Instruction: Update dependencies and update version. ## Code After: from distutils.core import setup setup( name='GoogleCalendarV3', version='0.1.2', author='Ashutosh Priyadarshy', author_email='static@siftcal.com', packages=['google_calendar_v3', 'google_calendar_v3.test'], scripts=['bin/example.py'], url='http://www.github.com/priyadarshy/google-calendar-v3/', license='LICENSE.txt', description='Python Client for Google Calendar API V3.', long_description=open('README.txt').read(), install_requires=[ "requests >= 2.3.0", "requests-oauthlib >= 0.4.0" ], )
from distutils.core import setup setup( name='GoogleCalendarV3', - version='0.1.1', ? ^ + version='0.1.2', ? ^ author='Ashutosh Priyadarshy', author_email='static@siftcal.com', packages=['google_calendar_v3', 'google_calendar_v3.test'], scripts=['bin/example.py'], url='http://www.github.com/priyadarshy/google-calendar-v3/', license='LICENSE.txt', description='Python Client for Google Calendar API V3.', long_description=open('README.txt').read(), install_requires=[ + "requests >= 2.3.0", - "requests-oauthlib >= 0.4.0", ? - + "requests-oauthlib >= 0.4.0" ], )
68878c516c497103586cb4de38b371f02ab6bee2
oneflow/profiles/api.py
oneflow/profiles/api.py
import logging from django.contrib.auth import get_user_model from tastypie.resources import ModelResource from tastypie import fields from ..base.api import common_authentication, UserObjectsOnlyAuthorization from .models import UserProfile LOGGER = logging.getLogger(__name__) User = get_user_model() class EmberMeta: # Ember-data expect the following 2 directives always_return_data = True allowed_methods = ('get', 'post', 'put', 'delete') # These are specific to 1flow functionnals. authentication = common_authentication authorization = UserObjectsOnlyAuthorization() class UserResource(ModelResource): class Meta(EmberMeta): queryset = User.objects.all() resource_name = 'user' class UserProfileResource(ModelResource): user = fields.ForeignKey(UserResource, 'user') class Meta(EmberMeta): queryset = UserProfile.objects.all() resource_name = 'user_profile'
import logging from django.contrib.auth import get_user_model from tastypie.resources import ModelResource from tastypie import fields from ..base.api import common_authentication, UserObjectsOnlyAuthorization from .models import UserProfile LOGGER = logging.getLogger(__name__) User = get_user_model() class EmberMeta: # Ember-data expect the following 2 directives always_return_data = True allowed_methods = ('get', 'post', 'put', 'delete') # These are specific to 1flow functionnals. authentication = common_authentication authorization = UserObjectsOnlyAuthorization() class UserResource(ModelResource): class Meta(EmberMeta): queryset = User.objects.all() resource_name = 'user' class UserProfileResource(ModelResource): # NOTE: "user" won't work because it's a OneToOne field in DJango. # We need "user_id". See http://stackoverflow.com/a/15609667/654755 user_id = fields.ForeignKey(UserResource, 'user') class Meta(EmberMeta): queryset = UserProfile.objects.all() resource_name = 'user_profile'
Fix the `User` not being loaded client side.
Fix the `User` not being loaded client side.
Python
agpl-3.0
WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow,1flow/1flow
import logging from django.contrib.auth import get_user_model from tastypie.resources import ModelResource from tastypie import fields from ..base.api import common_authentication, UserObjectsOnlyAuthorization from .models import UserProfile LOGGER = logging.getLogger(__name__) User = get_user_model() class EmberMeta: # Ember-data expect the following 2 directives always_return_data = True allowed_methods = ('get', 'post', 'put', 'delete') # These are specific to 1flow functionnals. authentication = common_authentication authorization = UserObjectsOnlyAuthorization() class UserResource(ModelResource): class Meta(EmberMeta): queryset = User.objects.all() resource_name = 'user' class UserProfileResource(ModelResource): + # NOTE: "user" won't work because it's a OneToOne field in DJango. + # We need "user_id". See http://stackoverflow.com/a/15609667/654755 - user = fields.ForeignKey(UserResource, 'user') + user_id = fields.ForeignKey(UserResource, 'user') class Meta(EmberMeta): queryset = UserProfile.objects.all() resource_name = 'user_profile'
Fix the `User` not being loaded client side.
## Code Before: import logging from django.contrib.auth import get_user_model from tastypie.resources import ModelResource from tastypie import fields from ..base.api import common_authentication, UserObjectsOnlyAuthorization from .models import UserProfile LOGGER = logging.getLogger(__name__) User = get_user_model() class EmberMeta: # Ember-data expect the following 2 directives always_return_data = True allowed_methods = ('get', 'post', 'put', 'delete') # These are specific to 1flow functionnals. authentication = common_authentication authorization = UserObjectsOnlyAuthorization() class UserResource(ModelResource): class Meta(EmberMeta): queryset = User.objects.all() resource_name = 'user' class UserProfileResource(ModelResource): user = fields.ForeignKey(UserResource, 'user') class Meta(EmberMeta): queryset = UserProfile.objects.all() resource_name = 'user_profile' ## Instruction: Fix the `User` not being loaded client side. ## Code After: import logging from django.contrib.auth import get_user_model from tastypie.resources import ModelResource from tastypie import fields from ..base.api import common_authentication, UserObjectsOnlyAuthorization from .models import UserProfile LOGGER = logging.getLogger(__name__) User = get_user_model() class EmberMeta: # Ember-data expect the following 2 directives always_return_data = True allowed_methods = ('get', 'post', 'put', 'delete') # These are specific to 1flow functionnals. authentication = common_authentication authorization = UserObjectsOnlyAuthorization() class UserResource(ModelResource): class Meta(EmberMeta): queryset = User.objects.all() resource_name = 'user' class UserProfileResource(ModelResource): # NOTE: "user" won't work because it's a OneToOne field in DJango. # We need "user_id". See http://stackoverflow.com/a/15609667/654755 user_id = fields.ForeignKey(UserResource, 'user') class Meta(EmberMeta): queryset = UserProfile.objects.all() resource_name = 'user_profile'
import logging from django.contrib.auth import get_user_model from tastypie.resources import ModelResource from tastypie import fields from ..base.api import common_authentication, UserObjectsOnlyAuthorization from .models import UserProfile LOGGER = logging.getLogger(__name__) User = get_user_model() class EmberMeta: # Ember-data expect the following 2 directives always_return_data = True allowed_methods = ('get', 'post', 'put', 'delete') # These are specific to 1flow functionnals. authentication = common_authentication authorization = UserObjectsOnlyAuthorization() class UserResource(ModelResource): class Meta(EmberMeta): queryset = User.objects.all() resource_name = 'user' class UserProfileResource(ModelResource): + # NOTE: "user" won't work because it's a OneToOne field in DJango. + # We need "user_id". See http://stackoverflow.com/a/15609667/654755 - user = fields.ForeignKey(UserResource, 'user') + user_id = fields.ForeignKey(UserResource, 'user') ? +++ class Meta(EmberMeta): queryset = UserProfile.objects.all() resource_name = 'user_profile'
09498335615b7e770f5976b9749d68050966501d
models/timeandplace.py
models/timeandplace.py
from .base import Serializable from .locations import Platform from datetime import datetime class TimeAndPlace(Serializable): def __init__(self, platform=None, arrival=None, departure=None): super().__init__() self.platform = platform self.arrival = arrival self.departure = departure self.passthrough = False @classmethod def _validate(cls): return { 'platform': (None, Platform), 'arrival': (None, datetime), 'departure': (None, datetime), 'passthrough': bool } @property def stop(self): return self.platform.stop def __eq__(self, other): assert isinstance(other, TimeAndPlace) return (self.platform == other.platform and self.arrival == other.arrival and self.departure == other.departure) def __repr__(self): return ('<TimeAndPlace %s %s %s>' % (self.arrival, self.departure, self.platform))
from .base import Serializable from .locations import Platform from .realtime import RealtimeTime class TimeAndPlace(Serializable): def __init__(self, platform=None, arrival=None, departure=None): super().__init__() self.platform = platform self.arrival = arrival self.departure = departure self.passthrough = False @classmethod def _validate(cls): return { 'platform': (None, Platform), 'arrival': (None, RealtimeTime), 'departure': (None, RealtimeTime), 'passthrough': bool } @property def stop(self): return self.platform.stop def __eq__(self, other): assert isinstance(other, TimeAndPlace) return (self.platform == other.platform and self.arrival == other.arrival and self.departure == other.departure) def __repr__(self): return ('<TimeAndPlace %s %s %s>' % (self.arrival, self.departure, self.platform))
Revert "TimeAndPlace no longer refers to realtime data"
Revert "TimeAndPlace no longer refers to realtime data" This reverts commit cf92e191e3748c67102f142b411937517c5051f4.
Python
apache-2.0
NoMoKeTo/choo,NoMoKeTo/transit
from .base import Serializable from .locations import Platform - from datetime import datetime + from .realtime import RealtimeTime class TimeAndPlace(Serializable): def __init__(self, platform=None, arrival=None, departure=None): super().__init__() self.platform = platform self.arrival = arrival self.departure = departure self.passthrough = False @classmethod def _validate(cls): return { 'platform': (None, Platform), - 'arrival': (None, datetime), + 'arrival': (None, RealtimeTime), - 'departure': (None, datetime), + 'departure': (None, RealtimeTime), 'passthrough': bool } @property def stop(self): return self.platform.stop def __eq__(self, other): assert isinstance(other, TimeAndPlace) return (self.platform == other.platform and self.arrival == other.arrival and self.departure == other.departure) def __repr__(self): return ('<TimeAndPlace %s %s %s>' % (self.arrival, self.departure, self.platform))
Revert "TimeAndPlace no longer refers to realtime data"
## Code Before: from .base import Serializable from .locations import Platform from datetime import datetime class TimeAndPlace(Serializable): def __init__(self, platform=None, arrival=None, departure=None): super().__init__() self.platform = platform self.arrival = arrival self.departure = departure self.passthrough = False @classmethod def _validate(cls): return { 'platform': (None, Platform), 'arrival': (None, datetime), 'departure': (None, datetime), 'passthrough': bool } @property def stop(self): return self.platform.stop def __eq__(self, other): assert isinstance(other, TimeAndPlace) return (self.platform == other.platform and self.arrival == other.arrival and self.departure == other.departure) def __repr__(self): return ('<TimeAndPlace %s %s %s>' % (self.arrival, self.departure, self.platform)) ## Instruction: Revert "TimeAndPlace no longer refers to realtime data" ## Code After: from .base import Serializable from .locations import Platform from .realtime import RealtimeTime class TimeAndPlace(Serializable): def __init__(self, platform=None, arrival=None, departure=None): super().__init__() self.platform = platform self.arrival = arrival self.departure = departure self.passthrough = False @classmethod def _validate(cls): return { 'platform': (None, Platform), 'arrival': (None, RealtimeTime), 'departure': (None, RealtimeTime), 'passthrough': bool } @property def stop(self): return self.platform.stop def __eq__(self, other): assert isinstance(other, TimeAndPlace) return (self.platform == other.platform and self.arrival == other.arrival and self.departure == other.departure) def __repr__(self): return ('<TimeAndPlace %s %s %s>' % (self.arrival, self.departure, self.platform))
from .base import Serializable from .locations import Platform - from datetime import datetime + from .realtime import RealtimeTime class TimeAndPlace(Serializable): def __init__(self, platform=None, arrival=None, departure=None): super().__init__() self.platform = platform self.arrival = arrival self.departure = departure self.passthrough = False @classmethod def _validate(cls): return { 'platform': (None, Platform), - 'arrival': (None, datetime), ? ^ ^ + 'arrival': (None, RealtimeTime), ? ^^ + ++ ^ - 'departure': (None, datetime), ? ^ ^ + 'departure': (None, RealtimeTime), ? ^^ + ++ ^ 'passthrough': bool } @property def stop(self): return self.platform.stop def __eq__(self, other): assert isinstance(other, TimeAndPlace) return (self.platform == other.platform and self.arrival == other.arrival and self.departure == other.departure) def __repr__(self): return ('<TimeAndPlace %s %s %s>' % (self.arrival, self.departure, self.platform))
bc8675b170748b51403fb31d03ed06399268cb7b
examples/test_deferred_asserts.py
examples/test_deferred_asserts.py
import pytest from seleniumbase import BaseCase class DeferredAssertTests(BaseCase): @pytest.mark.expected_failure def test_deferred_asserts(self): self.open("https://xkcd.com/993/") self.wait_for_element("#comic") print("\n(This test should fail)") self.deferred_assert_element('img[alt="Brand Identity"]') self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail self.deferred_assert_element("#comicmap") self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail self.deferred_assert_text("Random", "#middleContainer") self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail self.process_deferred_asserts()
import pytest from seleniumbase import BaseCase class DeferredAssertTests(BaseCase): @pytest.mark.expected_failure def test_deferred_asserts(self): self.open("https://xkcd.com/993/") self.wait_for_element("#comic") print("\n(This test should fail)") self.deferred_assert_element('img[alt="Brand Identity"]') self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail self.deferred_assert_element("#comicmap") self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail self.deferred_assert_text("Random", "#middleContainer") self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail self.deferred_assert_exact_text("Brand Identity", "#ctitle") self.deferred_assert_exact_text("Fake Food", "#comic") # Will Fail self.process_deferred_asserts()
Update an example test that uses deferred asserts
Update an example test that uses deferred asserts
Python
mit
mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase
import pytest from seleniumbase import BaseCase class DeferredAssertTests(BaseCase): @pytest.mark.expected_failure def test_deferred_asserts(self): self.open("https://xkcd.com/993/") self.wait_for_element("#comic") print("\n(This test should fail)") self.deferred_assert_element('img[alt="Brand Identity"]') self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail self.deferred_assert_element("#comicmap") self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail self.deferred_assert_text("Random", "#middleContainer") self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail + self.deferred_assert_exact_text("Brand Identity", "#ctitle") + self.deferred_assert_exact_text("Fake Food", "#comic") # Will Fail self.process_deferred_asserts()
Update an example test that uses deferred asserts
## Code Before: import pytest from seleniumbase import BaseCase class DeferredAssertTests(BaseCase): @pytest.mark.expected_failure def test_deferred_asserts(self): self.open("https://xkcd.com/993/") self.wait_for_element("#comic") print("\n(This test should fail)") self.deferred_assert_element('img[alt="Brand Identity"]') self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail self.deferred_assert_element("#comicmap") self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail self.deferred_assert_text("Random", "#middleContainer") self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail self.process_deferred_asserts() ## Instruction: Update an example test that uses deferred asserts ## Code After: import pytest from seleniumbase import BaseCase class DeferredAssertTests(BaseCase): @pytest.mark.expected_failure def test_deferred_asserts(self): self.open("https://xkcd.com/993/") self.wait_for_element("#comic") print("\n(This test should fail)") self.deferred_assert_element('img[alt="Brand Identity"]') self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail self.deferred_assert_element("#comicmap") self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail self.deferred_assert_text("Random", "#middleContainer") self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail self.deferred_assert_exact_text("Brand Identity", "#ctitle") self.deferred_assert_exact_text("Fake Food", "#comic") # Will Fail self.process_deferred_asserts()
import pytest from seleniumbase import BaseCase class DeferredAssertTests(BaseCase): @pytest.mark.expected_failure def test_deferred_asserts(self): self.open("https://xkcd.com/993/") self.wait_for_element("#comic") print("\n(This test should fail)") self.deferred_assert_element('img[alt="Brand Identity"]') self.deferred_assert_element('img[alt="Rocket Ship"]') # Will Fail self.deferred_assert_element("#comicmap") self.deferred_assert_text("Fake Item", "#middleContainer") # Will Fail self.deferred_assert_text("Random", "#middleContainer") self.deferred_assert_element('a[name="Super Fake !!!"]') # Will Fail + self.deferred_assert_exact_text("Brand Identity", "#ctitle") + self.deferred_assert_exact_text("Fake Food", "#comic") # Will Fail self.process_deferred_asserts()
6413ce937fbdfdf1acc5cffab4f01f0b40fb2cfc
views.py
views.py
from flask import Flask, render_template, url_for, Markup from flask.ext.libsass import * import pkg_resources import markdown app=Flask(__name__) Sass( {'app': 'scss/app.scss'}, app, url_path='/static/css', include_paths=[pkg_resources.resource_filename('views', 'scss')], output_style='compressed' ) @app.route('/<page>') def get_page(page): md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8') html=Markup(markdown.markdown(md.read(), output_format='html5')) md.close() if page=='index': return render_template('page.html', content=html) return render_template('page.html', content=html, title=page) @app.route('/') def index(): return get_page('index') if __name__=='__main__': app.run()
from flask import Flask, render_template, url_for, Markup, abort from flask.ext.libsass import * import pkg_resources import markdown app=Flask(__name__) Sass( {'app': 'scss/app.scss'}, app, url_path='/static/css', include_paths=[pkg_resources.resource_filename('views', 'scss')], output_style='compressed' ) @app.route('/<page>') def get_page(page): try: md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8') html=Markup(markdown.markdown(md.read(), output_format='html5')) md.close() if page=='index': return render_template('page.html', content=html) return render_template('page.html', content=html, title=page) except OSError: abort(404) @app.route('/') def index(): return get_page('index') if __name__=='__main__': app.run()
Add basic page request exception handling
Add basic page request exception handling
Python
mpl-2.0
vishwin/vishwin.info-http,vishwin/vishwin.info-http,vishwin/vishwin.info-http
- from flask import Flask, render_template, url_for, Markup + from flask import Flask, render_template, url_for, Markup, abort from flask.ext.libsass import * import pkg_resources import markdown app=Flask(__name__) Sass( {'app': 'scss/app.scss'}, app, url_path='/static/css', include_paths=[pkg_resources.resource_filename('views', 'scss')], output_style='compressed' ) @app.route('/<page>') def get_page(page): + try: - md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8') + md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8') - html=Markup(markdown.markdown(md.read(), output_format='html5')) + html=Markup(markdown.markdown(md.read(), output_format='html5')) - md.close() + md.close() - if page=='index': + if page=='index': - return render_template('page.html', content=html) + return render_template('page.html', content=html) - return render_template('page.html', content=html, title=page) + return render_template('page.html', content=html, title=page) + except OSError: + abort(404) @app.route('/') def index(): return get_page('index') if __name__=='__main__': app.run()
Add basic page request exception handling
## Code Before: from flask import Flask, render_template, url_for, Markup from flask.ext.libsass import * import pkg_resources import markdown app=Flask(__name__) Sass( {'app': 'scss/app.scss'}, app, url_path='/static/css', include_paths=[pkg_resources.resource_filename('views', 'scss')], output_style='compressed' ) @app.route('/<page>') def get_page(page): md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8') html=Markup(markdown.markdown(md.read(), output_format='html5')) md.close() if page=='index': return render_template('page.html', content=html) return render_template('page.html', content=html, title=page) @app.route('/') def index(): return get_page('index') if __name__=='__main__': app.run() ## Instruction: Add basic page request exception handling ## Code After: from flask import Flask, render_template, url_for, Markup, abort from flask.ext.libsass import * import pkg_resources import markdown app=Flask(__name__) Sass( {'app': 'scss/app.scss'}, app, url_path='/static/css', include_paths=[pkg_resources.resource_filename('views', 'scss')], output_style='compressed' ) @app.route('/<page>') def get_page(page): try: md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8') html=Markup(markdown.markdown(md.read(), output_format='html5')) md.close() if page=='index': return render_template('page.html', content=html) return render_template('page.html', content=html, title=page) except OSError: abort(404) @app.route('/') def index(): return get_page('index') if __name__=='__main__': app.run()
- from flask import Flask, render_template, url_for, Markup + from flask import Flask, render_template, url_for, Markup, abort ? +++++++ from flask.ext.libsass import * import pkg_resources import markdown app=Flask(__name__) Sass( {'app': 'scss/app.scss'}, app, url_path='/static/css', include_paths=[pkg_resources.resource_filename('views', 'scss')], output_style='compressed' ) @app.route('/<page>') def get_page(page): + try: - md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8') + md=open(pkg_resources.resource_filename('views', 'pages/' + page + '.md'), encoding='UTF-8') ? + - html=Markup(markdown.markdown(md.read(), output_format='html5')) + html=Markup(markdown.markdown(md.read(), output_format='html5')) ? + - md.close() + md.close() ? + - if page=='index': + if page=='index': ? + - return render_template('page.html', content=html) + return render_template('page.html', content=html) ? + - return render_template('page.html', content=html, title=page) + return render_template('page.html', content=html, title=page) ? + + except OSError: + abort(404) @app.route('/') def index(): return get_page('index') if __name__=='__main__': app.run()
ae8f9c39cd75d837a4cb5a4cea4d3d11fd1cabed
tests/test_comments.py
tests/test_comments.py
from hypothesis_auto import auto_pytest_magic from isort import comments auto_pytest_magic(comments.parse) auto_pytest_magic(comments.add_to_line)
from hypothesis_auto import auto_pytest_magic from isort import comments auto_pytest_magic(comments.parse) auto_pytest_magic(comments.add_to_line) def test_add_to_line(): assert comments.add_to_line([], "import os # comment", removed=True).strip() == "import os"
Add additional test case for comments
Add additional test case for comments
Python
mit
PyCQA/isort,PyCQA/isort
from hypothesis_auto import auto_pytest_magic from isort import comments auto_pytest_magic(comments.parse) auto_pytest_magic(comments.add_to_line) + + def test_add_to_line(): + assert comments.add_to_line([], "import os # comment", removed=True).strip() == "import os" +
Add additional test case for comments
## Code Before: from hypothesis_auto import auto_pytest_magic from isort import comments auto_pytest_magic(comments.parse) auto_pytest_magic(comments.add_to_line) ## Instruction: Add additional test case for comments ## Code After: from hypothesis_auto import auto_pytest_magic from isort import comments auto_pytest_magic(comments.parse) auto_pytest_magic(comments.add_to_line) def test_add_to_line(): assert comments.add_to_line([], "import os # comment", removed=True).strip() == "import os"
from hypothesis_auto import auto_pytest_magic from isort import comments auto_pytest_magic(comments.parse) auto_pytest_magic(comments.add_to_line) + + + def test_add_to_line(): + assert comments.add_to_line([], "import os # comment", removed=True).strip() == "import os"
7b50adc607f0e0e970c6f5793eadd9fb42027d0a
Tools/scripts/setup.py
Tools/scripts/setup.py
from distutils.core import setup if __name__ == '__main__': setup( scripts=[ 'byteyears.py', 'checkpyc.py', 'copytime.py', 'crlf.py', 'dutree.py', 'ftpmirror.py', 'h2py.py', 'lfcr.py', 'logmerge.py', '../../Lib/tabnanny.py', '../../Lib/timeit.py', 'untabify.py', ], )
from distutils.core import setup if __name__ == '__main__': setup( scripts=[ 'byteyears.py', 'checkpyc.py', 'copytime.py', 'crlf.py', 'dutree.py', 'ftpmirror.py', 'h2py.py', 'lfcr.py', '../i18n/pygettext.py', 'logmerge.py', '../../Lib/tabnanny.py', '../../Lib/timeit.py', 'untabify.py', ], )
Install pygettext (once the scriptsinstall target is working again).
Install pygettext (once the scriptsinstall target is working again).
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
from distutils.core import setup if __name__ == '__main__': setup( scripts=[ 'byteyears.py', 'checkpyc.py', 'copytime.py', 'crlf.py', 'dutree.py', 'ftpmirror.py', 'h2py.py', 'lfcr.py', + '../i18n/pygettext.py', 'logmerge.py', '../../Lib/tabnanny.py', '../../Lib/timeit.py', 'untabify.py', ], )
Install pygettext (once the scriptsinstall target is working again).
## Code Before: from distutils.core import setup if __name__ == '__main__': setup( scripts=[ 'byteyears.py', 'checkpyc.py', 'copytime.py', 'crlf.py', 'dutree.py', 'ftpmirror.py', 'h2py.py', 'lfcr.py', 'logmerge.py', '../../Lib/tabnanny.py', '../../Lib/timeit.py', 'untabify.py', ], ) ## Instruction: Install pygettext (once the scriptsinstall target is working again). ## Code After: from distutils.core import setup if __name__ == '__main__': setup( scripts=[ 'byteyears.py', 'checkpyc.py', 'copytime.py', 'crlf.py', 'dutree.py', 'ftpmirror.py', 'h2py.py', 'lfcr.py', '../i18n/pygettext.py', 'logmerge.py', '../../Lib/tabnanny.py', '../../Lib/timeit.py', 'untabify.py', ], )
from distutils.core import setup if __name__ == '__main__': setup( scripts=[ 'byteyears.py', 'checkpyc.py', 'copytime.py', 'crlf.py', 'dutree.py', 'ftpmirror.py', 'h2py.py', 'lfcr.py', + '../i18n/pygettext.py', 'logmerge.py', '../../Lib/tabnanny.py', '../../Lib/timeit.py', 'untabify.py', ], )
a5898f8e5b2b25af472f1e2e5ce02626b86db5f2
tunneler/tests/test_models.py
tunneler/tests/test_models.py
from unittest import TestCase from ..models import Tunnel
from unittest import TestCase from ..models import Tunnel class TestModels(TestCase): def test_defaults(self): tunnel = Tunnel() self.assertEquals(tunnel.name, 'unnamed') self.assertEquals(tunnel.process, None) self.assertEqual(tunnel.local_port, 0) self.assertEqual(tunnel.host, 'somehost') self.assertEqual(tunnel.remote_port, 0) self.assertEqual(tunnel.user, 'somebody') self.assertEqual(tunnel.server, 'somewhere')
Add a basic test for models.
Add a basic test for models.
Python
isc
xoliver/tunneler,xoliver/tunneler
from unittest import TestCase from ..models import Tunnel + + class TestModels(TestCase): + def test_defaults(self): + tunnel = Tunnel() + self.assertEquals(tunnel.name, 'unnamed') + self.assertEquals(tunnel.process, None) + self.assertEqual(tunnel.local_port, 0) + self.assertEqual(tunnel.host, 'somehost') + self.assertEqual(tunnel.remote_port, 0) + self.assertEqual(tunnel.user, 'somebody') + self.assertEqual(tunnel.server, 'somewhere') +
Add a basic test for models.
## Code Before: from unittest import TestCase from ..models import Tunnel ## Instruction: Add a basic test for models. ## Code After: from unittest import TestCase from ..models import Tunnel class TestModels(TestCase): def test_defaults(self): tunnel = Tunnel() self.assertEquals(tunnel.name, 'unnamed') self.assertEquals(tunnel.process, None) self.assertEqual(tunnel.local_port, 0) self.assertEqual(tunnel.host, 'somehost') self.assertEqual(tunnel.remote_port, 0) self.assertEqual(tunnel.user, 'somebody') self.assertEqual(tunnel.server, 'somewhere')
from unittest import TestCase from ..models import Tunnel + + + class TestModels(TestCase): + def test_defaults(self): + tunnel = Tunnel() + self.assertEquals(tunnel.name, 'unnamed') + self.assertEquals(tunnel.process, None) + self.assertEqual(tunnel.local_port, 0) + self.assertEqual(tunnel.host, 'somehost') + self.assertEqual(tunnel.remote_port, 0) + self.assertEqual(tunnel.user, 'somebody') + self.assertEqual(tunnel.server, 'somewhere')
f21da23d45c328acffaba69a6f2fbf2056ca326b
datapipe/denoising/__init__.py
datapipe/denoising/__init__.py
__all__ = ['abstract_cleaning_algorithm', 'fft', 'null', 'null_ref', 'tailcut', 'tailcut_jd', 'wavelets_mrfilter', 'wavelets_mrtransform']
__all__ = ['abstract_cleaning_algorithm', 'fft', 'null', 'null_ref', 'tailcut', 'tailcut_jd', 'wavelets_mrfilter', 'wavelets_mrtransform', 'inverse_transform_sampling']
Add a module to the __all__ list.
Add a module to the __all__ list.
Python
mit
jdhp-sap/sap-cta-data-pipeline,jdhp-sap/sap-cta-data-pipeline,jdhp-sap/data-pipeline-standalone-scripts,jdhp-sap/data-pipeline-standalone-scripts
__all__ = ['abstract_cleaning_algorithm', 'fft', 'null', 'null_ref', 'tailcut', 'tailcut_jd', 'wavelets_mrfilter', - 'wavelets_mrtransform'] + 'wavelets_mrtransform', + 'inverse_transform_sampling']
Add a module to the __all__ list.
## Code Before: __all__ = ['abstract_cleaning_algorithm', 'fft', 'null', 'null_ref', 'tailcut', 'tailcut_jd', 'wavelets_mrfilter', 'wavelets_mrtransform'] ## Instruction: Add a module to the __all__ list. ## Code After: __all__ = ['abstract_cleaning_algorithm', 'fft', 'null', 'null_ref', 'tailcut', 'tailcut_jd', 'wavelets_mrfilter', 'wavelets_mrtransform', 'inverse_transform_sampling']
__all__ = ['abstract_cleaning_algorithm', 'fft', 'null', 'null_ref', 'tailcut', 'tailcut_jd', 'wavelets_mrfilter', - 'wavelets_mrtransform'] ? ^ + 'wavelets_mrtransform', ? ^ + 'inverse_transform_sampling']
91519c542b2fac085dc6b785a41d2fbdba91386c
business_requirement_deliverable_report/__openerp__.py
business_requirement_deliverable_report/__openerp__.py
{ 'name': 'Business Requirement Document Printout', 'summary': 'Print the Business Requirement Document for your customers', 'version': '8.0.5.0.1', 'category': 'Business Requirements Management', 'website': 'https://www.elico-corp.com', 'author': 'Elico Corp', 'license': 'AGPL-3', 'application': False, 'installable': True, 'depends': [ 'business_requirement_deliverable', ], 'data': [ 'views/report_business_requirement.xml', 'views/report_business_requirement_deliverable.xml', 'views/report_business_requirement_deliverable_resource.xml', 'report/report.xml' ], 'image': [ 'static/img/bus_req_report1.png', 'static/img/bus_req_report2.png', 'static/img/bus_req_report3.png', ], }
{ 'name': 'Business Requirement Document Printout', 'summary': 'Print the Business Requirement Document for your customers', 'version': '8.0.5.0.1', 'category': 'Business Requirements Management', 'website': 'https://www.elico-corp.com', 'author': 'Elico Corp, Odoo Community Association (OCA)', 'license': 'AGPL-3', 'application': False, 'installable': True, 'depends': [ 'business_requirement_deliverable', ], 'data': [ 'views/report_business_requirement.xml', 'views/report_business_requirement_deliverable.xml', 'views/report_business_requirement_deliverable_resource.xml', 'report/report.xml' ], 'image': [ 'static/img/bus_req_report1.png', 'static/img/bus_req_report2.png', 'static/img/bus_req_report3.png', ], }
Fix manifest: add OCA in the authors
Fix manifest: add OCA in the authors Added OCA in the authors
Python
agpl-3.0
YogeshMahera-SerpentCS/business-requirement,sudhir-serpentcs/business-requirement
{ 'name': 'Business Requirement Document Printout', 'summary': 'Print the Business Requirement Document for your customers', 'version': '8.0.5.0.1', 'category': 'Business Requirements Management', 'website': 'https://www.elico-corp.com', - 'author': 'Elico Corp', + 'author': 'Elico Corp, Odoo Community Association (OCA)', 'license': 'AGPL-3', 'application': False, 'installable': True, 'depends': [ 'business_requirement_deliverable', ], 'data': [ 'views/report_business_requirement.xml', 'views/report_business_requirement_deliverable.xml', 'views/report_business_requirement_deliverable_resource.xml', 'report/report.xml' ], 'image': [ 'static/img/bus_req_report1.png', 'static/img/bus_req_report2.png', 'static/img/bus_req_report3.png', ], }
Fix manifest: add OCA in the authors
## Code Before: { 'name': 'Business Requirement Document Printout', 'summary': 'Print the Business Requirement Document for your customers', 'version': '8.0.5.0.1', 'category': 'Business Requirements Management', 'website': 'https://www.elico-corp.com', 'author': 'Elico Corp', 'license': 'AGPL-3', 'application': False, 'installable': True, 'depends': [ 'business_requirement_deliverable', ], 'data': [ 'views/report_business_requirement.xml', 'views/report_business_requirement_deliverable.xml', 'views/report_business_requirement_deliverable_resource.xml', 'report/report.xml' ], 'image': [ 'static/img/bus_req_report1.png', 'static/img/bus_req_report2.png', 'static/img/bus_req_report3.png', ], } ## Instruction: Fix manifest: add OCA in the authors ## Code After: { 'name': 'Business Requirement Document Printout', 'summary': 'Print the Business Requirement Document for your customers', 'version': '8.0.5.0.1', 'category': 'Business Requirements Management', 'website': 'https://www.elico-corp.com', 'author': 'Elico Corp, Odoo Community Association (OCA)', 'license': 'AGPL-3', 'application': False, 'installable': True, 'depends': [ 'business_requirement_deliverable', ], 'data': [ 'views/report_business_requirement.xml', 'views/report_business_requirement_deliverable.xml', 'views/report_business_requirement_deliverable_resource.xml', 'report/report.xml' ], 'image': [ 'static/img/bus_req_report1.png', 'static/img/bus_req_report2.png', 'static/img/bus_req_report3.png', ], }
{ 'name': 'Business Requirement Document Printout', 'summary': 'Print the Business Requirement Document for your customers', 'version': '8.0.5.0.1', 'category': 'Business Requirements Management', 'website': 'https://www.elico-corp.com', - 'author': 'Elico Corp', + 'author': 'Elico Corp, Odoo Community Association (OCA)', 'license': 'AGPL-3', 'application': False, 'installable': True, 'depends': [ 'business_requirement_deliverable', ], 'data': [ 'views/report_business_requirement.xml', 'views/report_business_requirement_deliverable.xml', 'views/report_business_requirement_deliverable_resource.xml', 'report/report.xml' ], 'image': [ 'static/img/bus_req_report1.png', 'static/img/bus_req_report2.png', 'static/img/bus_req_report3.png', ], }
7e27c47496a55f7a4c58c2c8c79ce854d80f0893
skyfield/tests/test_trigonometry.py
skyfield/tests/test_trigonometry.py
from skyfield.api import Angle, Topos, load, load_file from skyfield.trigonometry import position_angle_of def test_position_angle(): a = Angle(degrees=0), Angle(degrees=0) b = Angle(degrees=1), Angle(degrees=1) assert str(position_angle_of(a, b)) == '315deg 00\' 15.7"' def test_position_angle_against_nasa_horizons(): ts = load.timescale(builtin=True) t = ts.utc(2053, 10, 9) eph = load_file('./skyfield/tests/data/jup310-2053-10-08.bsp') boston = eph['earth'] + Topos(longitude_degrees=(-71, 3, 24.8), latitude_degrees=(42, 21, 24.1)) b = boston.at(t) j = b.observe(eph['jupiter'])#.apparent() i = b.observe(eph['io'])#.apparent() a = position_angle_of(j.radec(epoch='date')[1::-1], i.radec(epoch='date')[1::-1]) assert abs(a.degrees - 293.671) < 0.002
from skyfield.api import Angle, Topos, load, load_file from skyfield.trigonometry import position_angle_of def test_position_angle(): a = Angle(degrees=0), Angle(degrees=0) b = Angle(degrees=1), Angle(degrees=1) assert str(position_angle_of(a, b)) == '315deg 00\' 15.7"' def test_position_angle_against_nasa_horizons(): ts = load.timescale(builtin=True) t = ts.utc(2053, 10, 9) eph = load_file('./skyfield/tests/data/jup310-2053-10-08.bsp') boston = eph['earth'] + Topos(longitude_degrees=(-71, 3, 24.8), latitude_degrees=(42, 21, 24.1)) b = boston.at(t) j = b.observe(eph['jupiter'])#.apparent() i = b.observe(eph['io'])#.apparent() a = position_angle_of(j.radec(epoch='date'), i.radec(epoch='date')) assert abs(a.degrees - 293.671) < 0.002
Remove hack from position angle test
Remove hack from position angle test
Python
mit
skyfielders/python-skyfield,skyfielders/python-skyfield
from skyfield.api import Angle, Topos, load, load_file from skyfield.trigonometry import position_angle_of def test_position_angle(): a = Angle(degrees=0), Angle(degrees=0) b = Angle(degrees=1), Angle(degrees=1) assert str(position_angle_of(a, b)) == '315deg 00\' 15.7"' def test_position_angle_against_nasa_horizons(): ts = load.timescale(builtin=True) t = ts.utc(2053, 10, 9) eph = load_file('./skyfield/tests/data/jup310-2053-10-08.bsp') boston = eph['earth'] + Topos(longitude_degrees=(-71, 3, 24.8), latitude_degrees=(42, 21, 24.1)) b = boston.at(t) j = b.observe(eph['jupiter'])#.apparent() i = b.observe(eph['io'])#.apparent() - a = position_angle_of(j.radec(epoch='date')[1::-1], + a = position_angle_of(j.radec(epoch='date'), i.radec(epoch='date')) - i.radec(epoch='date')[1::-1]) assert abs(a.degrees - 293.671) < 0.002
Remove hack from position angle test
## Code Before: from skyfield.api import Angle, Topos, load, load_file from skyfield.trigonometry import position_angle_of def test_position_angle(): a = Angle(degrees=0), Angle(degrees=0) b = Angle(degrees=1), Angle(degrees=1) assert str(position_angle_of(a, b)) == '315deg 00\' 15.7"' def test_position_angle_against_nasa_horizons(): ts = load.timescale(builtin=True) t = ts.utc(2053, 10, 9) eph = load_file('./skyfield/tests/data/jup310-2053-10-08.bsp') boston = eph['earth'] + Topos(longitude_degrees=(-71, 3, 24.8), latitude_degrees=(42, 21, 24.1)) b = boston.at(t) j = b.observe(eph['jupiter'])#.apparent() i = b.observe(eph['io'])#.apparent() a = position_angle_of(j.radec(epoch='date')[1::-1], i.radec(epoch='date')[1::-1]) assert abs(a.degrees - 293.671) < 0.002 ## Instruction: Remove hack from position angle test ## Code After: from skyfield.api import Angle, Topos, load, load_file from skyfield.trigonometry import position_angle_of def test_position_angle(): a = Angle(degrees=0), Angle(degrees=0) b = Angle(degrees=1), Angle(degrees=1) assert str(position_angle_of(a, b)) == '315deg 00\' 15.7"' def test_position_angle_against_nasa_horizons(): ts = load.timescale(builtin=True) t = ts.utc(2053, 10, 9) eph = load_file('./skyfield/tests/data/jup310-2053-10-08.bsp') boston = eph['earth'] + Topos(longitude_degrees=(-71, 3, 24.8), latitude_degrees=(42, 21, 24.1)) b = boston.at(t) j = b.observe(eph['jupiter'])#.apparent() i = b.observe(eph['io'])#.apparent() a = position_angle_of(j.radec(epoch='date'), i.radec(epoch='date')) assert abs(a.degrees - 293.671) < 0.002
from skyfield.api import Angle, Topos, load, load_file from skyfield.trigonometry import position_angle_of def test_position_angle(): a = Angle(degrees=0), Angle(degrees=0) b = Angle(degrees=1), Angle(degrees=1) assert str(position_angle_of(a, b)) == '315deg 00\' 15.7"' def test_position_angle_against_nasa_horizons(): ts = load.timescale(builtin=True) t = ts.utc(2053, 10, 9) eph = load_file('./skyfield/tests/data/jup310-2053-10-08.bsp') boston = eph['earth'] + Topos(longitude_degrees=(-71, 3, 24.8), latitude_degrees=(42, 21, 24.1)) b = boston.at(t) j = b.observe(eph['jupiter'])#.apparent() i = b.observe(eph['io'])#.apparent() - a = position_angle_of(j.radec(epoch='date')[1::-1], ? ------- + a = position_angle_of(j.radec(epoch='date'), i.radec(epoch='date')) ? +++++++++++++++++++++++ - i.radec(epoch='date')[1::-1]) assert abs(a.degrees - 293.671) < 0.002
49f61f7f47bbb69236ef319dfa861ea437a0aac4
build_qrc.py
build_qrc.py
import os import sys import json def read_conf(fname): if not os.path.isfile(fname): return {} with open(fname, 'r') as conf: return json.load(conf) def build_qrc(resources): yield '<RCC>' yield '<qresource>' for d in resources: for root, dirs, files in os.walk(d): for f in files: yield '<file>{}</file>'.format(os.path.join(root, f)) yield '</qresource>' yield '</RCC>' def build_resources(resources, target): with open(target, 'w') as f: for line in build_qrc(resources): f.write(line + os.linesep) def build(source): conf = read_conf(source) target = os.path.basename(source) if '.' in target: target = target.rsplit('.', 1)[0] target += '.qrc' build_resources(conf.get('resources', []), target) if __name__ == '__main__': build(sys.argv[1] if len(sys.argv) >= 1 else 'resources.json')
import os import sys import json def read_conf(fname): if not os.path.isfile(fname): return {} with open(fname, 'r') as conf: return json.load(conf) def build_qrc(resources): yield '<RCC>' yield '<qresource>' for d in resources: for root, dirs, files in os.walk(d): dirs.sort() files.sort() for f in files: yield '<file>{}</file>'.format(os.path.join(root, f)) yield '</qresource>' yield '</RCC>' def build_resources(resources, target): with open(target, 'w') as f: for line in build_qrc(resources): f.write(line + os.linesep) def build(source): conf = read_conf(source) target = os.path.basename(source) if '.' in target: target = target.rsplit('.', 1)[0] target += '.qrc' build_resources(conf.get('resources', []), target) if __name__ == '__main__': build(sys.argv[1] if len(sys.argv) >= 1 else 'resources.json')
Sort qrc input file list
Sort qrc input file list so that yubikey-manager-qt packages build in a reproducible way in spite of indeterministic filesystem readdir order See https://reproducible-builds.org/ for why this is good.
Python
bsd-2-clause
Yubico/yubikey-manager-qt,Yubico/yubikey-manager-qt,Yubico/yubikey-manager-qt,Yubico/yubikey-manager-qt
import os import sys import json def read_conf(fname): if not os.path.isfile(fname): return {} with open(fname, 'r') as conf: return json.load(conf) def build_qrc(resources): yield '<RCC>' yield '<qresource>' for d in resources: for root, dirs, files in os.walk(d): + dirs.sort() + files.sort() for f in files: yield '<file>{}</file>'.format(os.path.join(root, f)) yield '</qresource>' yield '</RCC>' def build_resources(resources, target): with open(target, 'w') as f: for line in build_qrc(resources): f.write(line + os.linesep) def build(source): conf = read_conf(source) target = os.path.basename(source) if '.' in target: target = target.rsplit('.', 1)[0] target += '.qrc' build_resources(conf.get('resources', []), target) if __name__ == '__main__': build(sys.argv[1] if len(sys.argv) >= 1 else 'resources.json')
Sort qrc input file list
## Code Before: import os import sys import json def read_conf(fname): if not os.path.isfile(fname): return {} with open(fname, 'r') as conf: return json.load(conf) def build_qrc(resources): yield '<RCC>' yield '<qresource>' for d in resources: for root, dirs, files in os.walk(d): for f in files: yield '<file>{}</file>'.format(os.path.join(root, f)) yield '</qresource>' yield '</RCC>' def build_resources(resources, target): with open(target, 'w') as f: for line in build_qrc(resources): f.write(line + os.linesep) def build(source): conf = read_conf(source) target = os.path.basename(source) if '.' in target: target = target.rsplit('.', 1)[0] target += '.qrc' build_resources(conf.get('resources', []), target) if __name__ == '__main__': build(sys.argv[1] if len(sys.argv) >= 1 else 'resources.json') ## Instruction: Sort qrc input file list ## Code After: import os import sys import json def read_conf(fname): if not os.path.isfile(fname): return {} with open(fname, 'r') as conf: return json.load(conf) def build_qrc(resources): yield '<RCC>' yield '<qresource>' for d in resources: for root, dirs, files in os.walk(d): dirs.sort() files.sort() for f in files: yield '<file>{}</file>'.format(os.path.join(root, f)) yield '</qresource>' yield '</RCC>' def build_resources(resources, target): with open(target, 'w') as f: for line in build_qrc(resources): f.write(line + os.linesep) def build(source): conf = read_conf(source) target = os.path.basename(source) if '.' in target: target = target.rsplit('.', 1)[0] target += '.qrc' build_resources(conf.get('resources', []), target) if __name__ == '__main__': build(sys.argv[1] if len(sys.argv) >= 1 else 'resources.json')
import os import sys import json def read_conf(fname): if not os.path.isfile(fname): return {} with open(fname, 'r') as conf: return json.load(conf) def build_qrc(resources): yield '<RCC>' yield '<qresource>' for d in resources: for root, dirs, files in os.walk(d): + dirs.sort() + files.sort() for f in files: yield '<file>{}</file>'.format(os.path.join(root, f)) yield '</qresource>' yield '</RCC>' def build_resources(resources, target): with open(target, 'w') as f: for line in build_qrc(resources): f.write(line + os.linesep) def build(source): conf = read_conf(source) target = os.path.basename(source) if '.' in target: target = target.rsplit('.', 1)[0] target += '.qrc' build_resources(conf.get('resources', []), target) if __name__ == '__main__': build(sys.argv[1] if len(sys.argv) >= 1 else 'resources.json')
8b9454fdf9e54059edcc951f188c05cb0f34c0a4
lookup_isbn.py
lookup_isbn.py
import yaml from amazon.api import AmazonAPI class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_key_id'], self.config['aws_secret_key'], self.config['amazon_associate_tag'] ) def lookup(self, isbn): product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books") book = { 'title': product.title, 'image_url': product.large_image_url, 'sales_rank': int(product.sales_rank), 'price': product.price_and_currency[0], 'offer_url': product.offer_url, 'authors': product.authors, 'publisher': product.publisher, 'isbn': isbn, 'binding': product.binding, 'pages': product.pages, 'publication_date': product.publication_date, 'list_price': product.list_price[0] } return book book = Books('config.yml').lookup('9781449389734') print yaml.dump(book, default_flow_style = False)
import yaml import sys import os from amazon.api import AmazonAPI # Change to script directory os.chdir(os.path.dirname(sys.argv[0])) class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_key_id'], self.config['aws_secret_key'], self.config['amazon_associate_tag'] ) def lookup(self, isbn): product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books") book = { 'title': product.title, 'image_url': product.large_image_url, 'sales_rank': int(product.sales_rank), 'price': product.price_and_currency[0], 'offer_url': product.offer_url, 'authors': product.authors, 'publisher': product.publisher, 'isbn': isbn, 'binding': product.binding, 'pages': product.pages, 'publication_date': product.publication_date, 'list_price': product.list_price[0] } return book books = Books('config.yml') for isbn in sys.argv[1:]: book = books.lookup(isbn) with open('raw_data/{0}.yml'.format(isbn), 'w') as out: out.write(yaml.dump(book, default_flow_style = False))
Read commandline args as isbns
Read commandline args as isbns
Python
mit
sortelli/book_pivot,sortelli/book_pivot
import yaml + import sys + import os from amazon.api import AmazonAPI + + # Change to script directory + os.chdir(os.path.dirname(sys.argv[0])) class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_key_id'], self.config['aws_secret_key'], self.config['amazon_associate_tag'] ) def lookup(self, isbn): product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books") book = { 'title': product.title, 'image_url': product.large_image_url, 'sales_rank': int(product.sales_rank), 'price': product.price_and_currency[0], 'offer_url': product.offer_url, 'authors': product.authors, 'publisher': product.publisher, 'isbn': isbn, 'binding': product.binding, 'pages': product.pages, 'publication_date': product.publication_date, 'list_price': product.list_price[0] } return book - book = Books('config.yml').lookup('9781449389734') - print yaml.dump(book, default_flow_style = False) + books = Books('config.yml') + for isbn in sys.argv[1:]: + book = books.lookup(isbn) + with open('raw_data/{0}.yml'.format(isbn), 'w') as out: + out.write(yaml.dump(book, default_flow_style = False)) +
Read commandline args as isbns
## Code Before: import yaml from amazon.api import AmazonAPI class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_key_id'], self.config['aws_secret_key'], self.config['amazon_associate_tag'] ) def lookup(self, isbn): product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books") book = { 'title': product.title, 'image_url': product.large_image_url, 'sales_rank': int(product.sales_rank), 'price': product.price_and_currency[0], 'offer_url': product.offer_url, 'authors': product.authors, 'publisher': product.publisher, 'isbn': isbn, 'binding': product.binding, 'pages': product.pages, 'publication_date': product.publication_date, 'list_price': product.list_price[0] } return book book = Books('config.yml').lookup('9781449389734') print yaml.dump(book, default_flow_style = False) ## Instruction: Read commandline args as isbns ## Code After: import yaml import sys import os from amazon.api import AmazonAPI # Change to script directory os.chdir(os.path.dirname(sys.argv[0])) class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_key_id'], self.config['aws_secret_key'], self.config['amazon_associate_tag'] ) def lookup(self, isbn): product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books") book = { 'title': product.title, 'image_url': product.large_image_url, 'sales_rank': int(product.sales_rank), 'price': product.price_and_currency[0], 'offer_url': product.offer_url, 'authors': product.authors, 'publisher': product.publisher, 'isbn': isbn, 'binding': product.binding, 'pages': product.pages, 'publication_date': product.publication_date, 'list_price': product.list_price[0] } return book books = Books('config.yml') for isbn in sys.argv[1:]: book = books.lookup(isbn) with open('raw_data/{0}.yml'.format(isbn), 'w') as out: out.write(yaml.dump(book, default_flow_style = False))
import yaml + import sys + import os from amazon.api import AmazonAPI + + # Change to script directory + os.chdir(os.path.dirname(sys.argv[0])) class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_key_id'], self.config['aws_secret_key'], self.config['amazon_associate_tag'] ) def lookup(self, isbn): product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books") book = { 'title': product.title, 'image_url': product.large_image_url, 'sales_rank': int(product.sales_rank), 'price': product.price_and_currency[0], 'offer_url': product.offer_url, 'authors': product.authors, 'publisher': product.publisher, 'isbn': isbn, 'binding': product.binding, 'pages': product.pages, 'publication_date': product.publication_date, 'list_price': product.list_price[0] } return book - book = Books('config.yml').lookup('9781449389734') + books = Books('config.yml') + for isbn in sys.argv[1:]: + book = books.lookup(isbn) + + with open('raw_data/{0}.yml'.format(isbn), 'w') as out: - print yaml.dump(book, default_flow_style = False) ? ^ - ^ + out.write(yaml.dump(book, default_flow_style = False)) ? ^^^^^^^^^ ^^ +
bb575cfdf4a6781c878a12f80987fb3e62fe56d4
chandl/model/posts.py
chandl/model/posts.py
from __future__ import unicode_literals class Posts(list): """ Represents a list of posts in a thread. """ def __init__(self, *args): """ Initialise a new posts list. :param args: The list of posts. """ super(Posts, self).__init__(*args) def filter(self, predicate): """ Take a subset of this list of posts. :param predicate: The predicate to use to choose which posts make the cut. :return: The filtered posts. """ return Posts(filter(predicate, self)) def map(self, transformation): """ Applies a transformation function to each post, returning a list of this function's returned values. :param transformation: The transformation function. :return: The transformed list of posts. """ return map(transformation, self) def foreach(self, function): """ Call a function for each post. :param function: A function taking a post argument. Return values are ignored. """ for post in self: function(post)
from __future__ import unicode_literals class Posts(list): """ Represents a list of posts in a thread. """ def __init__(self, *args): """ Initialise a new posts list. :param args: The list of posts. """ super(Posts, self).__init__(*args) def filter(self, predicate): """ Take a subset of this list of posts. :param predicate: The predicate to use to choose which posts make the cut. :return: The filtered posts. """ return Posts([post for post in self if predicate(post)]) def map(self, transform): """ Applies a transformation function to each post, returning a list of this function's returned values. :param transform: The transformation function. :return: The transformed list of posts. """ return [transform(post) for post in self] def foreach(self, function): """ Call a function for each post. :param function: A function taking a post argument. Return values are ignored. """ for post in self: function(post)
Make post filtering and mapping more pythonic
Make post filtering and mapping more pythonic
Python
mit
gebn/chandl,gebn/chandl
from __future__ import unicode_literals class Posts(list): """ Represents a list of posts in a thread. """ def __init__(self, *args): """ Initialise a new posts list. :param args: The list of posts. """ super(Posts, self).__init__(*args) def filter(self, predicate): """ Take a subset of this list of posts. :param predicate: The predicate to use to choose which posts make the cut. :return: The filtered posts. """ - return Posts(filter(predicate, self)) + return Posts([post for post in self if predicate(post)]) - def map(self, transformation): + def map(self, transform): """ Applies a transformation function to each post, returning a list of this function's returned values. - :param transformation: The transformation function. + :param transform: The transformation function. :return: The transformed list of posts. """ - return map(transformation, self) + return [transform(post) for post in self] def foreach(self, function): """ Call a function for each post. :param function: A function taking a post argument. Return values are ignored. """ for post in self: function(post)
Make post filtering and mapping more pythonic
## Code Before: from __future__ import unicode_literals class Posts(list): """ Represents a list of posts in a thread. """ def __init__(self, *args): """ Initialise a new posts list. :param args: The list of posts. """ super(Posts, self).__init__(*args) def filter(self, predicate): """ Take a subset of this list of posts. :param predicate: The predicate to use to choose which posts make the cut. :return: The filtered posts. """ return Posts(filter(predicate, self)) def map(self, transformation): """ Applies a transformation function to each post, returning a list of this function's returned values. :param transformation: The transformation function. :return: The transformed list of posts. """ return map(transformation, self) def foreach(self, function): """ Call a function for each post. :param function: A function taking a post argument. Return values are ignored. """ for post in self: function(post) ## Instruction: Make post filtering and mapping more pythonic ## Code After: from __future__ import unicode_literals class Posts(list): """ Represents a list of posts in a thread. """ def __init__(self, *args): """ Initialise a new posts list. :param args: The list of posts. """ super(Posts, self).__init__(*args) def filter(self, predicate): """ Take a subset of this list of posts. :param predicate: The predicate to use to choose which posts make the cut. :return: The filtered posts. """ return Posts([post for post in self if predicate(post)]) def map(self, transform): """ Applies a transformation function to each post, returning a list of this function's returned values. :param transform: The transformation function. :return: The transformed list of posts. """ return [transform(post) for post in self] def foreach(self, function): """ Call a function for each post. :param function: A function taking a post argument. Return values are ignored. """ for post in self: function(post)
from __future__ import unicode_literals class Posts(list): """ Represents a list of posts in a thread. """ def __init__(self, *args): """ Initialise a new posts list. :param args: The list of posts. """ super(Posts, self).__init__(*args) def filter(self, predicate): """ Take a subset of this list of posts. :param predicate: The predicate to use to choose which posts make the cut. :return: The filtered posts. """ - return Posts(filter(predicate, self)) + return Posts([post for post in self if predicate(post)]) - def map(self, transformation): ? ----- + def map(self, transform): """ Applies a transformation function to each post, returning a list of this function's returned values. - :param transformation: The transformation function. ? ----- + :param transform: The transformation function. :return: The transformed list of posts. """ - return map(transformation, self) + return [transform(post) for post in self] def foreach(self, function): """ Call a function for each post. :param function: A function taking a post argument. Return values are ignored. """ for post in self: function(post)
5ed5855efe09c92efbf93dab5eb0b37325072381
opps/api/__init__.py
opps/api/__init__.py
from django.http import HttpResponse from django.contrib.auth import authenticate from piston.handler import BaseHandler as Handler from opps.api.models import ApiKey class BaseHandler(Handler): def read(self, request): base = self.model.objects if request.GET.items(): return base.filter(**request.GET.dict()) return base.all() class ApiKeyAuthentication(object): def __init__(self, auth_func=authenticate, method=['GET']): self.auth_func = auth_func self.method = method def is_authenticated(self, request): if request.method == 'GET' and 'GET' in self.method: return True method = getattr(request, request.method) try: ApiKey.objects.get( user__username=method.get('api_username'), key=method.get('api_key')) except ApiKey.DoesNotExist: return False return True def challenge(self): resp = HttpResponse("Authorization Required") resp.status_code = 401 return resp
from django.http import HttpResponse from django.contrib.auth import authenticate from piston.handler import BaseHandler as Handler from opps.api.models import ApiKey class BaseHandler(Handler): def read(self, request): base = self.model.objects if request.GET.items(): return base.filter(**request.GET.dict()) return base.all() class ApiKeyAuthentication(object): def __init__(self, auth_func=authenticate, method=['GET']): self.auth_func = auth_func self.method = method def is_authenticated(self, request): if request.method == 'GET' and 'GET' in self.method: return True try: method = getattr(request, request.method) except: method = request.GET try: ApiKey.objects.get( user__username=method.get('api_username'), key=method.get('api_key')) except ApiKey.DoesNotExist: return False return True def challenge(self): resp = HttpResponse("Authorization Required") resp.status_code = 401 return resp
Fix method get on ApiKeyAuthentication
Fix method get on ApiKeyAuthentication
Python
mit
jeanmask/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,jeanmask/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,jeanmask/opps
from django.http import HttpResponse from django.contrib.auth import authenticate from piston.handler import BaseHandler as Handler from opps.api.models import ApiKey class BaseHandler(Handler): def read(self, request): base = self.model.objects if request.GET.items(): return base.filter(**request.GET.dict()) return base.all() class ApiKeyAuthentication(object): def __init__(self, auth_func=authenticate, method=['GET']): self.auth_func = auth_func self.method = method def is_authenticated(self, request): if request.method == 'GET' and 'GET' in self.method: return True + try: - method = getattr(request, request.method) + method = getattr(request, request.method) + except: + method = request.GET + try: ApiKey.objects.get( user__username=method.get('api_username'), key=method.get('api_key')) except ApiKey.DoesNotExist: return False return True def challenge(self): resp = HttpResponse("Authorization Required") resp.status_code = 401 return resp
Fix method get on ApiKeyAuthentication
## Code Before: from django.http import HttpResponse from django.contrib.auth import authenticate from piston.handler import BaseHandler as Handler from opps.api.models import ApiKey class BaseHandler(Handler): def read(self, request): base = self.model.objects if request.GET.items(): return base.filter(**request.GET.dict()) return base.all() class ApiKeyAuthentication(object): def __init__(self, auth_func=authenticate, method=['GET']): self.auth_func = auth_func self.method = method def is_authenticated(self, request): if request.method == 'GET' and 'GET' in self.method: return True method = getattr(request, request.method) try: ApiKey.objects.get( user__username=method.get('api_username'), key=method.get('api_key')) except ApiKey.DoesNotExist: return False return True def challenge(self): resp = HttpResponse("Authorization Required") resp.status_code = 401 return resp ## Instruction: Fix method get on ApiKeyAuthentication ## Code After: from django.http import HttpResponse from django.contrib.auth import authenticate from piston.handler import BaseHandler as Handler from opps.api.models import ApiKey class BaseHandler(Handler): def read(self, request): base = self.model.objects if request.GET.items(): return base.filter(**request.GET.dict()) return base.all() class ApiKeyAuthentication(object): def __init__(self, auth_func=authenticate, method=['GET']): self.auth_func = auth_func self.method = method def is_authenticated(self, request): if request.method == 'GET' and 'GET' in self.method: return True try: method = getattr(request, request.method) except: method = request.GET try: ApiKey.objects.get( user__username=method.get('api_username'), key=method.get('api_key')) except ApiKey.DoesNotExist: return False return True def challenge(self): resp = HttpResponse("Authorization Required") resp.status_code = 401 return resp
from django.http import HttpResponse from django.contrib.auth import authenticate from piston.handler import BaseHandler as Handler from opps.api.models import ApiKey class BaseHandler(Handler): def read(self, request): base = self.model.objects if request.GET.items(): return base.filter(**request.GET.dict()) return base.all() class ApiKeyAuthentication(object): def __init__(self, auth_func=authenticate, method=['GET']): self.auth_func = auth_func self.method = method def is_authenticated(self, request): if request.method == 'GET' and 'GET' in self.method: return True + try: - method = getattr(request, request.method) + method = getattr(request, request.method) ? ++++ + except: + method = request.GET + try: ApiKey.objects.get( user__username=method.get('api_username'), key=method.get('api_key')) except ApiKey.DoesNotExist: return False return True def challenge(self): resp = HttpResponse("Authorization Required") resp.status_code = 401 return resp
9fcfd8e13b5c4684a1cb3890427662ded2d28c24
examples/get_dataset.py
examples/get_dataset.py
import os import urllib.request DATASET_URL = 'http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/diabetes' TARGET_PATH = os.path.dirname(os.path.realpath(__file__)) + '/dataset.txt' def main(): urllib.request.urlretrieve(DATASET_URL, TARGET_PATH) if __name__ == '__main__': main()
import os import urllib.request import random DATASET_URL = 'http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/letter.scale' DATASET_SIZE = 1000 TARGET_PATH = os.path.dirname(os.path.realpath(__file__)) + '/dataset.txt' def main(): rows = list(urllib.request.urlopen(DATASET_URL)) selected = random.sample(rows, DATASET_SIZE) with open(TARGET_PATH, 'wb') as f: for row in selected: f.write(row) if __name__ == '__main__': main()
Change dataset used in example (letter)
Change dataset used in example (letter) XXX: UncertaintySampling(le) weird?
Python
bsd-2-clause
ntucllab/libact,ntucllab/libact,ntucllab/libact
import os import urllib.request + import random - DATASET_URL = 'http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/diabetes' + DATASET_URL = 'http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/letter.scale' + DATASET_SIZE = 1000 TARGET_PATH = os.path.dirname(os.path.realpath(__file__)) + '/dataset.txt' def main(): - urllib.request.urlretrieve(DATASET_URL, TARGET_PATH) + rows = list(urllib.request.urlopen(DATASET_URL)) + selected = random.sample(rows, DATASET_SIZE) + with open(TARGET_PATH, 'wb') as f: + for row in selected: + f.write(row) if __name__ == '__main__': main()
Change dataset used in example (letter)
## Code Before: import os import urllib.request DATASET_URL = 'http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/diabetes' TARGET_PATH = os.path.dirname(os.path.realpath(__file__)) + '/dataset.txt' def main(): urllib.request.urlretrieve(DATASET_URL, TARGET_PATH) if __name__ == '__main__': main() ## Instruction: Change dataset used in example (letter) ## Code After: import os import urllib.request import random DATASET_URL = 'http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/letter.scale' DATASET_SIZE = 1000 TARGET_PATH = os.path.dirname(os.path.realpath(__file__)) + '/dataset.txt' def main(): rows = list(urllib.request.urlopen(DATASET_URL)) selected = random.sample(rows, DATASET_SIZE) with open(TARGET_PATH, 'wb') as f: for row in selected: f.write(row) if __name__ == '__main__': main()
import os import urllib.request + import random - DATASET_URL = 'http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/binary/diabetes' ? ^ ^ ^^ ^^^^ + DATASET_URL = 'http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/letter.scale' ? ^^^^ ^^ ^^ ^ + ++ ++++ + DATASET_SIZE = 1000 TARGET_PATH = os.path.dirname(os.path.realpath(__file__)) + '/dataset.txt' def main(): - urllib.request.urlretrieve(DATASET_URL, TARGET_PATH) + rows = list(urllib.request.urlopen(DATASET_URL)) + selected = random.sample(rows, DATASET_SIZE) + with open(TARGET_PATH, 'wb') as f: + for row in selected: + f.write(row) if __name__ == '__main__': main()
4a5ea880b77e44fa20129e6195cf37d5d72427f3
webpay/model/model.py
webpay/model/model.py
import json class Model: def __init__(self, client, data, conversion = None): self._client = client self._data = data for k, v in data.items(): if conversion is None: self.__dict__[k] = v else: conv = conversion(k) self.__dict__[k] = v if conv is None else conv(client, v) def __str__(self): return '<webpay.model.%s.%s> %s' % (self.object, self.object.capitalize(), json.dumps(self._data, indent = 4, sort_keys = True))
import json class Model: def __init__(self, client, data, conversion = None): self._client = client self._data = data for k, v in data.items(): if conversion is None: self.__dict__[k] = v else: conv = conversion(k) self.__dict__[k] = v if conv is None else conv(client, v) def __str__(self): t = type(self) return '<%s.%s> %s' % (t.__module__, t.__name__, json.dumps(self._data, indent = 4, sort_keys = True))
Use type's module and name to show full class path correctly
Use type's module and name to show full class path correctly
Python
mit
yamaneko1212/webpay-python
import json class Model: def __init__(self, client, data, conversion = None): self._client = client self._data = data for k, v in data.items(): if conversion is None: self.__dict__[k] = v else: conv = conversion(k) self.__dict__[k] = v if conv is None else conv(client, v) def __str__(self): - return '<webpay.model.%s.%s> %s' % (self.object, self.object.capitalize(), json.dumps(self._data, indent = 4, sort_keys = True)) + t = type(self) + return '<%s.%s> %s' % (t.__module__, t.__name__, json.dumps(self._data, indent = 4, sort_keys = True))
Use type's module and name to show full class path correctly
## Code Before: import json class Model: def __init__(self, client, data, conversion = None): self._client = client self._data = data for k, v in data.items(): if conversion is None: self.__dict__[k] = v else: conv = conversion(k) self.__dict__[k] = v if conv is None else conv(client, v) def __str__(self): return '<webpay.model.%s.%s> %s' % (self.object, self.object.capitalize(), json.dumps(self._data, indent = 4, sort_keys = True)) ## Instruction: Use type's module and name to show full class path correctly ## Code After: import json class Model: def __init__(self, client, data, conversion = None): self._client = client self._data = data for k, v in data.items(): if conversion is None: self.__dict__[k] = v else: conv = conversion(k) self.__dict__[k] = v if conv is None else conv(client, v) def __str__(self): t = type(self) return '<%s.%s> %s' % (t.__module__, t.__name__, json.dumps(self._data, indent = 4, sort_keys = True))
import json class Model: def __init__(self, client, data, conversion = None): self._client = client self._data = data for k, v in data.items(): if conversion is None: self.__dict__[k] = v else: conv = conversion(k) self.__dict__[k] = v if conv is None else conv(client, v) def __str__(self): + t = type(self) - return '<webpay.model.%s.%s> %s' % (self.object, self.object.capitalize(), json.dumps(self._data, indent = 4, sort_keys = True)) ? ------------- ^ ^^^^^^^^^ ---------- ^ ^^^^^^^ ^^ + return '<%s.%s> %s' % (t.__module__, t.__name__, json.dumps(self._data, indent = 4, sort_keys = True)) ? ^^^^^^^^^ ^^ ^^^ ^ ^^
55755871c240289238072602eefd9eed14d7e70e
bin/combine-examples.py
bin/combine-examples.py
import re import sys def main(argv): examples = {} requires = set() for filename in argv[1:]: lines = open(filename, 'rU').readlines() if len(lines) > 0 and lines[0].startswith('// NOCOMPILE'): continue requires.update(line for line in lines if line.startswith('goog.require')) examples[filename] = [line for line in lines if not line.startswith('goog.require')] for require in sorted(requires): print require, for filename in sorted(examples.keys()): print '// ', filename print '(function(){' for line in examples[filename]: print line, print '})();' if __name__ == '__main__': sys.exit(main(sys.argv))
import re import sys def main(argv): examples = {} requires = set() for filename in argv[1:]: lines = open(filename, 'rU').readlines() if len(lines) > 0 and lines[0].startswith('// NOCOMPILE'): continue requires.update(line for line in lines if line.startswith('goog.require')) examples[filename] = [line for line in lines if not line.startswith('goog.require')] for require in sorted(requires): sys.stdout.write(require) for filename in sorted(examples.keys()): sys.stdout.write('// ' + filename + '\n') sys.stdout.write('(function(){\n') for line in examples[filename]: sys.stdout.write(line) sys.stdout.write('})();\n') if __name__ == '__main__': sys.exit(main(sys.argv))
Use write to avoid newline problems
Use write to avoid newline problems
Python
bsd-2-clause
elemoine/ol3,gingerik/ol3,itayod/ol3,stweil/ol3,bill-chadwick/ol3,epointal/ol3,adube/ol3,denilsonsa/ol3,fblackburn/ol3,xiaoqqchen/ol3,bogdanvaduva/ol3,landonb/ol3,tsauerwein/ol3,klokantech/ol3,landonb/ol3,bjornharrtell/ol3,llambanna/ol3,gingerik/ol3,gingerik/ol3,Distem/ol3,bjornharrtell/ol3,Distem/ol3,richstoner/ol3,klokantech/ol3raster,thhomas/ol3,thhomas/ol3,Antreasgr/ol3,mechdrew/ol3,mechdrew/ol3,stweil/ol3,kjelderg/ol3,planetlabs/ol3,klokantech/ol3,elemoine/ol3,openlayers/openlayers,antonio83moura/ol3,fperucic/ol3,jmiller-boundless/ol3,hafenr/ol3,epointal/ol3,ahocevar/ol3,tsauerwein/ol3,klokantech/ol3raster,geonux/ol3,wlerner/ol3,wlerner/ol3,stweil/ol3,gingerik/ol3,wlerner/ol3,xiaoqqchen/ol3,tamarmot/ol3,stweil/openlayers,mechdrew/ol3,ahocevar/ol3,thomasmoelhave/ol3,kjelderg/ol3,klokantech/ol3raster,pmlrsg/ol3,klokantech/ol3,thhomas/ol3,CandoImage/ol3,thomasmoelhave/ol3,planetlabs/ol3,ahocevar/openlayers,oterral/ol3,t27/ol3,bartvde/ol3,geekdenz/openlayers,mzur/ol3,geekdenz/ol3,mzur/ol3,jmiller-boundless/ol3,Distem/ol3,NOAA-ORR-ERD/ol3,Andrey-Pavlov/ol3,CandoImage/ol3,freylis/ol3,mechdrew/ol3,fperucic/ol3,klokantech/ol3raster,richstoner/ol3,openlayers/openlayers,NOAA-ORR-ERD/ol3,Antreasgr/ol3,thomasmoelhave/ol3,tschaub/ol3,llambanna/ol3,Morgul/ol3,ahocevar/openlayers,elemoine/ol3,alvinlindstam/ol3,xiaoqqchen/ol3,t27/ol3,ahocevar/ol3,Andrey-Pavlov/ol3,kjelderg/ol3,t27/ol3,bogdanvaduva/ol3,alvinlindstam/ol3,jmiller-boundless/ol3,fredj/ol3,jmiller-boundless/ol3,adube/ol3,pmlrsg/ol3,t27/ol3,alvinlindstam/ol3,freylis/ol3,geekdenz/openlayers,itayod/ol3,planetlabs/ol3,llambanna/ol3,denilsonsa/ol3,bartvde/ol3,pmlrsg/ol3,tsauerwein/ol3,oterral/ol3,fredj/ol3,epointal/ol3,geekdenz/ol3,aisaacs/ol3,alexbrault/ol3,jacmendt/ol3,ahocevar/ol3,bill-chadwick/ol3,CandoImage/ol3,hafenr/ol3,denilsonsa/ol3,kjelderg/ol3,fredj/ol3,richstoner/ol3,tamarmot/ol3,bjornharrtell/ol3,stweil/ol3,landonb/ol3,adube/ol3,tamarmot/ol3,tschaub/ol3,wlerner/ol3,das-peter/ol3,kkuunnddaannkk/ol3,hafenr/ol3,bogdanvaduva/ol3,Morgul/ol3,geonux/ol3,jacmendt/ol3,bill-chadwick/ol3,geonux/ol3,freylis/ol3,denilsonsa/ol3,kkuunnddaannkk/ol3,fperucic/ol3,alexbrault/ol3,Antreasgr/ol3,das-peter/ol3,tschaub/ol3,llambanna/ol3,NOAA-ORR-ERD/ol3,alvinlindstam/ol3,NOAA-ORR-ERD/ol3,Andrey-Pavlov/ol3,tsauerwein/ol3,klokantech/ol3,geekdenz/ol3,mzur/ol3,freylis/ol3,geonux/ol3,thhomas/ol3,geekdenz/ol3,Antreasgr/ol3,fredj/ol3,stweil/openlayers,alexbrault/ol3,Andrey-Pavlov/ol3,bartvde/ol3,bill-chadwick/ol3,planetlabs/ol3,jacmendt/ol3,landonb/ol3,thomasmoelhave/ol3,aisaacs/ol3,pmlrsg/ol3,stweil/openlayers,fperucic/ol3,hafenr/ol3,bartvde/ol3,jacmendt/ol3,itayod/ol3,oterral/ol3,itayod/ol3,elemoine/ol3,bogdanvaduva/ol3,kkuunnddaannkk/ol3,das-peter/ol3,Morgul/ol3,CandoImage/ol3,aisaacs/ol3,aisaacs/ol3,antonio83moura/ol3,epointal/ol3,Distem/ol3,richstoner/ol3,ahocevar/openlayers,alexbrault/ol3,geekdenz/openlayers,xiaoqqchen/ol3,mzur/ol3,jmiller-boundless/ol3,tschaub/ol3,das-peter/ol3,fblackburn/ol3,tamarmot/ol3,antonio83moura/ol3,openlayers/openlayers,kkuunnddaannkk/ol3,fblackburn/ol3,fblackburn/ol3,Morgul/ol3,antonio83moura/ol3
import re import sys def main(argv): examples = {} requires = set() for filename in argv[1:]: lines = open(filename, 'rU').readlines() if len(lines) > 0 and lines[0].startswith('// NOCOMPILE'): continue requires.update(line for line in lines if line.startswith('goog.require')) examples[filename] = [line for line in lines if not line.startswith('goog.require')] for require in sorted(requires): - print require, + sys.stdout.write(require) for filename in sorted(examples.keys()): - print '// ', filename - print '(function(){' + sys.stdout.write('// ' + filename + '\n') + sys.stdout.write('(function(){\n') for line in examples[filename]: - print line, - print '})();' + sys.stdout.write(line) + sys.stdout.write('})();\n') if __name__ == '__main__': sys.exit(main(sys.argv))
Use write to avoid newline problems
## Code Before: import re import sys def main(argv): examples = {} requires = set() for filename in argv[1:]: lines = open(filename, 'rU').readlines() if len(lines) > 0 and lines[0].startswith('// NOCOMPILE'): continue requires.update(line for line in lines if line.startswith('goog.require')) examples[filename] = [line for line in lines if not line.startswith('goog.require')] for require in sorted(requires): print require, for filename in sorted(examples.keys()): print '// ', filename print '(function(){' for line in examples[filename]: print line, print '})();' if __name__ == '__main__': sys.exit(main(sys.argv)) ## Instruction: Use write to avoid newline problems ## Code After: import re import sys def main(argv): examples = {} requires = set() for filename in argv[1:]: lines = open(filename, 'rU').readlines() if len(lines) > 0 and lines[0].startswith('// NOCOMPILE'): continue requires.update(line for line in lines if line.startswith('goog.require')) examples[filename] = [line for line in lines if not line.startswith('goog.require')] for require in sorted(requires): sys.stdout.write(require) for filename in sorted(examples.keys()): sys.stdout.write('// ' + filename + '\n') sys.stdout.write('(function(){\n') for line in examples[filename]: sys.stdout.write(line) sys.stdout.write('})();\n') if __name__ == '__main__': sys.exit(main(sys.argv))
import re import sys def main(argv): examples = {} requires = set() for filename in argv[1:]: lines = open(filename, 'rU').readlines() if len(lines) > 0 and lines[0].startswith('// NOCOMPILE'): continue requires.update(line for line in lines if line.startswith('goog.require')) examples[filename] = [line for line in lines if not line.startswith('goog.require')] for require in sorted(requires): - print require, + sys.stdout.write(require) for filename in sorted(examples.keys()): - print '// ', filename - print '(function(){' + sys.stdout.write('// ' + filename + '\n') + sys.stdout.write('(function(){\n') for line in examples[filename]: - print line, - print '})();' + sys.stdout.write(line) + sys.stdout.write('})();\n') if __name__ == '__main__': sys.exit(main(sys.argv))
bc6392560ea87c74d6c6a94812b6caba7d6c2954
django_elect/settings.py
django_elect/settings.py
from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/ """ DJANGO_ELECT_USER_MODEL = getattr(settings, 'DJANGO_ELECT_USER_MODEL', 'auth.User') """ List of tuples to pass to Migration.depedencies for django_elect migrations """ DJANGO_ELECT_MIGRATION_DEPENDENCIES = getattr(settings, 'DJANGO_ELECT_MIGRATION_DEPENDENCIES', [('auth', '0001_initial')]) """ URL to redirect voters to who are not logged in. """ LOGIN_URL = getattr(settings, 'LOGIN_URL', '/account/')
from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/ """ DJANGO_ELECT_USER_MODEL = getattr(settings, 'DJANGO_ELECT_USER_MODEL', settings.AUTH_USER_MODEL) """ List of tuples to pass to Migration.depedencies for django_elect migrations """ DJANGO_ELECT_MIGRATION_DEPENDENCIES = getattr(settings, 'DJANGO_ELECT_MIGRATION_DEPENDENCIES', [('auth', '0001_initial')]) """ URL to redirect voters to who are not logged in. """ LOGIN_URL = getattr(settings, 'LOGIN_URL', '/account/')
Change DJANGO_ELECT_USER_MODEL to default to AUTH_USER_MODEL
Change DJANGO_ELECT_USER_MODEL to default to AUTH_USER_MODEL
Python
bsd-3-clause
MasonM/django-elect,MasonM/django-elect,MasonM/django-elect
from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/ """ DJANGO_ELECT_USER_MODEL = getattr(settings, - 'DJANGO_ELECT_USER_MODEL', 'auth.User') + 'DJANGO_ELECT_USER_MODEL', settings.AUTH_USER_MODEL) """ List of tuples to pass to Migration.depedencies for django_elect migrations """ DJANGO_ELECT_MIGRATION_DEPENDENCIES = getattr(settings, 'DJANGO_ELECT_MIGRATION_DEPENDENCIES', [('auth', '0001_initial')]) """ URL to redirect voters to who are not logged in. """ LOGIN_URL = getattr(settings, 'LOGIN_URL', '/account/')
Change DJANGO_ELECT_USER_MODEL to default to AUTH_USER_MODEL
## Code Before: from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/ """ DJANGO_ELECT_USER_MODEL = getattr(settings, 'DJANGO_ELECT_USER_MODEL', 'auth.User') """ List of tuples to pass to Migration.depedencies for django_elect migrations """ DJANGO_ELECT_MIGRATION_DEPENDENCIES = getattr(settings, 'DJANGO_ELECT_MIGRATION_DEPENDENCIES', [('auth', '0001_initial')]) """ URL to redirect voters to who are not logged in. """ LOGIN_URL = getattr(settings, 'LOGIN_URL', '/account/') ## Instruction: Change DJANGO_ELECT_USER_MODEL to default to AUTH_USER_MODEL ## Code After: from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/ """ DJANGO_ELECT_USER_MODEL = getattr(settings, 'DJANGO_ELECT_USER_MODEL', settings.AUTH_USER_MODEL) """ List of tuples to pass to Migration.depedencies for django_elect migrations """ DJANGO_ELECT_MIGRATION_DEPENDENCIES = getattr(settings, 'DJANGO_ELECT_MIGRATION_DEPENDENCIES', [('auth', '0001_initial')]) """ URL to redirect voters to who are not logged in. """ LOGIN_URL = getattr(settings, 'LOGIN_URL', '/account/')
from django.conf import settings """ A string that corresponds to the path to the model that should be used for the Election.allowed_voters and Vote.account foreign keys. This is mainly for sites that extend the User model via inheritance, as detailed at http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/ """ DJANGO_ELECT_USER_MODEL = getattr(settings, - 'DJANGO_ELECT_USER_MODEL', 'auth.User') + 'DJANGO_ELECT_USER_MODEL', settings.AUTH_USER_MODEL) """ List of tuples to pass to Migration.depedencies for django_elect migrations """ DJANGO_ELECT_MIGRATION_DEPENDENCIES = getattr(settings, 'DJANGO_ELECT_MIGRATION_DEPENDENCIES', [('auth', '0001_initial')]) """ URL to redirect voters to who are not logged in. """ LOGIN_URL = getattr(settings, 'LOGIN_URL', '/account/')
95b08a7cb2d473c25c1d326b0394336955b47af4
appy/models.py
appy/models.py
from django.db import models from django.contrib.auth.models import User class Tag(models.Model): description = models.TextField() class Position(models.Model): company = models.TextField() job_title = models.TextField() description = models.TextField() tags = models.ManyToManyField(Tag) class Application(models.Model): user = models.ForeignKey(User) position = models.ForeignKey(Position) APPLIED = 'APP' REJECTED = 'REJ' INTERVIEWING = 'INT' NEGOTIATING = 'NEG' STATUS_CHOICES = ( (APPLIED, 'Applied'), (REJECTED, 'Rejected'), (INTERVIEWING, 'Interviewing'), (NEGOTIATING, 'Negotiating'), ) status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
from django.db import models from django.contrib.auth.models import User class Tag(models.Model): description = models.TextField() def __unicode__(self): return self.description class Position(models.Model): company = models.TextField() job_title = models.TextField() description = models.TextField() tags = models.ManyToManyField(Tag) def __unicode__(self): return u'%s at %s' % (self.job_title, self.company) class Application(models.Model): user = models.ForeignKey(User) position = models.ForeignKey(Position) APPLIED = 'APP' REJECTED = 'REJ' INTERVIEWING = 'INT' NEGOTIATING = 'NEG' STATUS_CHOICES = ( (APPLIED, 'Applied'), (REJECTED, 'Rejected'), (INTERVIEWING, 'Interviewing'), (NEGOTIATING, 'Negotiating'), ) status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
Add unicode representations for tags/positions
Add unicode representations for tags/positions
Python
mit
merdey/ApPy,merdey/ApPy
from django.db import models from django.contrib.auth.models import User class Tag(models.Model): description = models.TextField() + def __unicode__(self): + return self.description + class Position(models.Model): company = models.TextField() job_title = models.TextField() description = models.TextField() tags = models.ManyToManyField(Tag) + + def __unicode__(self): + return u'%s at %s' % (self.job_title, self.company) class Application(models.Model): user = models.ForeignKey(User) position = models.ForeignKey(Position) APPLIED = 'APP' REJECTED = 'REJ' INTERVIEWING = 'INT' NEGOTIATING = 'NEG' STATUS_CHOICES = ( (APPLIED, 'Applied'), (REJECTED, 'Rejected'), (INTERVIEWING, 'Interviewing'), (NEGOTIATING, 'Negotiating'), ) status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
Add unicode representations for tags/positions
## Code Before: from django.db import models from django.contrib.auth.models import User class Tag(models.Model): description = models.TextField() class Position(models.Model): company = models.TextField() job_title = models.TextField() description = models.TextField() tags = models.ManyToManyField(Tag) class Application(models.Model): user = models.ForeignKey(User) position = models.ForeignKey(Position) APPLIED = 'APP' REJECTED = 'REJ' INTERVIEWING = 'INT' NEGOTIATING = 'NEG' STATUS_CHOICES = ( (APPLIED, 'Applied'), (REJECTED, 'Rejected'), (INTERVIEWING, 'Interviewing'), (NEGOTIATING, 'Negotiating'), ) status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) ## Instruction: Add unicode representations for tags/positions ## Code After: from django.db import models from django.contrib.auth.models import User class Tag(models.Model): description = models.TextField() def __unicode__(self): return self.description class Position(models.Model): company = models.TextField() job_title = models.TextField() description = models.TextField() tags = models.ManyToManyField(Tag) def __unicode__(self): return u'%s at %s' % (self.job_title, self.company) class Application(models.Model): user = models.ForeignKey(User) position = models.ForeignKey(Position) APPLIED = 'APP' REJECTED = 'REJ' INTERVIEWING = 'INT' NEGOTIATING = 'NEG' STATUS_CHOICES = ( (APPLIED, 'Applied'), (REJECTED, 'Rejected'), (INTERVIEWING, 'Interviewing'), (NEGOTIATING, 'Negotiating'), ) status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
from django.db import models from django.contrib.auth.models import User class Tag(models.Model): description = models.TextField() + def __unicode__(self): + return self.description + class Position(models.Model): company = models.TextField() job_title = models.TextField() description = models.TextField() tags = models.ManyToManyField(Tag) + + def __unicode__(self): + return u'%s at %s' % (self.job_title, self.company) class Application(models.Model): user = models.ForeignKey(User) position = models.ForeignKey(Position) APPLIED = 'APP' REJECTED = 'REJ' INTERVIEWING = 'INT' NEGOTIATING = 'NEG' STATUS_CHOICES = ( (APPLIED, 'Applied'), (REJECTED, 'Rejected'), (INTERVIEWING, 'Interviewing'), (NEGOTIATING, 'Negotiating'), ) status = models.CharField(max_length=3, choices=STATUS_CHOICES, default=APPLIED) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
6aa53f1fda74eb10051cb0bcc315f7db7dee1b57
tests/test_propagation.py
tests/test_propagation.py
from opentracing import Format from basictracer import BasicTracer def test_propagation(): tracer = BasicTracer() sp = tracer.start_span(operation_name="test") sp.set_baggage_item("foo", "bar") opname = 'op' tests = [(Format.BINARY, bytearray()), (Format.TEXT_MAP, {})] for format, carrier in tests: tracer.inject(sp, format, carrier) child = tracer.join(opname, format, carrier) assert child.context.trace_id == sp.context.trace_id assert child.context.parent_id == sp.context.span_id assert child.context.sampled == sp.context.sampled assert child.context.baggage == sp.context.baggage
import pytest from opentracing import Format, UnsupportedFormatException from basictracer import BasicTracer def test_propagation(): tracer = BasicTracer() sp = tracer.start_span(operation_name="test") sp.context.sampled = False sp.set_baggage_item("foo", "bar") opname = 'op' # Test invalid types with pytest.raises(UnsupportedFormatException): tracer.inject(sp, "invalid", {}) with pytest.raises(UnsupportedFormatException): tracer.join("", "invalid", {}) tests = [(Format.BINARY, bytearray()), (Format.TEXT_MAP, {})] for format, carrier in tests: tracer.inject(sp, format, carrier) child = tracer.join(opname, format, carrier) assert child.context.trace_id == sp.context.trace_id assert child.context.parent_id == sp.context.span_id assert child.context.sampled == sp.context.sampled assert child.context.baggage == sp.context.baggage def test_start_span(): """ Test in process child span creation.""" tracer = BasicTracer() sp = tracer.start_span(operation_name="test") sp.set_baggage_item("foo", "bar") child = tracer.start_span(operation_name="child", parent=sp) assert child.context.trace_id == sp.context.trace_id assert child.context.parent_id == sp.context.span_id assert child.context.sampled == sp.context.sampled assert child.context.baggage == sp.context.baggage
Add baggage and invalid carrier tests
Add baggage and invalid carrier tests
Python
apache-2.0
opentracing/basictracer-python
- from opentracing import Format + import pytest + from opentracing import Format, UnsupportedFormatException from basictracer import BasicTracer def test_propagation(): tracer = BasicTracer() sp = tracer.start_span(operation_name="test") + sp.context.sampled = False sp.set_baggage_item("foo", "bar") opname = 'op' + + # Test invalid types + with pytest.raises(UnsupportedFormatException): + tracer.inject(sp, "invalid", {}) + with pytest.raises(UnsupportedFormatException): + tracer.join("", "invalid", {}) tests = [(Format.BINARY, bytearray()), (Format.TEXT_MAP, {})] for format, carrier in tests: tracer.inject(sp, format, carrier) child = tracer.join(opname, format, carrier) assert child.context.trace_id == sp.context.trace_id assert child.context.parent_id == sp.context.span_id assert child.context.sampled == sp.context.sampled assert child.context.baggage == sp.context.baggage + def test_start_span(): + """ Test in process child span creation.""" + tracer = BasicTracer() + sp = tracer.start_span(operation_name="test") + sp.set_baggage_item("foo", "bar") + child = tracer.start_span(operation_name="child", parent=sp) + + assert child.context.trace_id == sp.context.trace_id + assert child.context.parent_id == sp.context.span_id + assert child.context.sampled == sp.context.sampled + assert child.context.baggage == sp.context.baggage +
Add baggage and invalid carrier tests
## Code Before: from opentracing import Format from basictracer import BasicTracer def test_propagation(): tracer = BasicTracer() sp = tracer.start_span(operation_name="test") sp.set_baggage_item("foo", "bar") opname = 'op' tests = [(Format.BINARY, bytearray()), (Format.TEXT_MAP, {})] for format, carrier in tests: tracer.inject(sp, format, carrier) child = tracer.join(opname, format, carrier) assert child.context.trace_id == sp.context.trace_id assert child.context.parent_id == sp.context.span_id assert child.context.sampled == sp.context.sampled assert child.context.baggage == sp.context.baggage ## Instruction: Add baggage and invalid carrier tests ## Code After: import pytest from opentracing import Format, UnsupportedFormatException from basictracer import BasicTracer def test_propagation(): tracer = BasicTracer() sp = tracer.start_span(operation_name="test") sp.context.sampled = False sp.set_baggage_item("foo", "bar") opname = 'op' # Test invalid types with pytest.raises(UnsupportedFormatException): tracer.inject(sp, "invalid", {}) with pytest.raises(UnsupportedFormatException): tracer.join("", "invalid", {}) tests = [(Format.BINARY, bytearray()), (Format.TEXT_MAP, {})] for format, carrier in tests: tracer.inject(sp, format, carrier) child = tracer.join(opname, format, carrier) assert child.context.trace_id == sp.context.trace_id assert child.context.parent_id == sp.context.span_id assert child.context.sampled == sp.context.sampled assert child.context.baggage == sp.context.baggage def test_start_span(): """ Test in process child span creation.""" tracer = BasicTracer() sp = tracer.start_span(operation_name="test") sp.set_baggage_item("foo", "bar") child = tracer.start_span(operation_name="child", parent=sp) assert child.context.trace_id == sp.context.trace_id assert child.context.parent_id == sp.context.span_id assert child.context.sampled == sp.context.sampled assert child.context.baggage == sp.context.baggage
- from opentracing import Format + import pytest + from opentracing import Format, UnsupportedFormatException from basictracer import BasicTracer def test_propagation(): tracer = BasicTracer() sp = tracer.start_span(operation_name="test") + sp.context.sampled = False sp.set_baggage_item("foo", "bar") opname = 'op' + + # Test invalid types + with pytest.raises(UnsupportedFormatException): + tracer.inject(sp, "invalid", {}) + with pytest.raises(UnsupportedFormatException): + tracer.join("", "invalid", {}) tests = [(Format.BINARY, bytearray()), (Format.TEXT_MAP, {})] for format, carrier in tests: tracer.inject(sp, format, carrier) child = tracer.join(opname, format, carrier) assert child.context.trace_id == sp.context.trace_id assert child.context.parent_id == sp.context.span_id assert child.context.sampled == sp.context.sampled assert child.context.baggage == sp.context.baggage + def test_start_span(): + """ Test in process child span creation.""" + tracer = BasicTracer() + sp = tracer.start_span(operation_name="test") + sp.set_baggage_item("foo", "bar") + + child = tracer.start_span(operation_name="child", parent=sp) + + assert child.context.trace_id == sp.context.trace_id + assert child.context.parent_id == sp.context.span_id + assert child.context.sampled == sp.context.sampled + assert child.context.baggage == sp.context.baggage
4b54d1472a57ad4d45293ec7bdce9a0ed9746bde
ideasbox/mixins.py
ideasbox/mixins.py
from django.views.generic import ListView class ByTagListView(ListView): def get_queryset(self): qs = super(ByTagListView, self).get_queryset() if 'tag' in self.kwargs: qs = qs.filter(tags__slug__in=[self.kwargs['tag']]) return qs def get_context_data(self, **kwargs): context = super(ByTagListView, self).get_context_data(**kwargs) context['tag'] = self.kwargs.get('tag') return context
from django.views.generic import ListView from taggit.models import Tag class ByTagListView(ListView): def get_queryset(self): qs = super(ByTagListView, self).get_queryset() if 'tag' in self.kwargs: qs = qs.filter(tags__slug__in=[self.kwargs['tag']]) return qs def get_context_data(self, **kwargs): context = super(ByTagListView, self).get_context_data(**kwargs) context['tag'] = Tag.objects.get(slug=self.kwargs.get('tag')) return context
Use tag name not slug in tag page title
Use tag name not slug in tag page title
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,Lcaracol/ideasbox.lan,Lcaracol/ideasbox.lan,Lcaracol/ideasbox.lan,ideascube/ideascube
from django.views.generic import ListView + + from taggit.models import Tag class ByTagListView(ListView): def get_queryset(self): qs = super(ByTagListView, self).get_queryset() if 'tag' in self.kwargs: qs = qs.filter(tags__slug__in=[self.kwargs['tag']]) return qs def get_context_data(self, **kwargs): context = super(ByTagListView, self).get_context_data(**kwargs) - context['tag'] = self.kwargs.get('tag') + context['tag'] = Tag.objects.get(slug=self.kwargs.get('tag')) return context
Use tag name not slug in tag page title
## Code Before: from django.views.generic import ListView class ByTagListView(ListView): def get_queryset(self): qs = super(ByTagListView, self).get_queryset() if 'tag' in self.kwargs: qs = qs.filter(tags__slug__in=[self.kwargs['tag']]) return qs def get_context_data(self, **kwargs): context = super(ByTagListView, self).get_context_data(**kwargs) context['tag'] = self.kwargs.get('tag') return context ## Instruction: Use tag name not slug in tag page title ## Code After: from django.views.generic import ListView from taggit.models import Tag class ByTagListView(ListView): def get_queryset(self): qs = super(ByTagListView, self).get_queryset() if 'tag' in self.kwargs: qs = qs.filter(tags__slug__in=[self.kwargs['tag']]) return qs def get_context_data(self, **kwargs): context = super(ByTagListView, self).get_context_data(**kwargs) context['tag'] = Tag.objects.get(slug=self.kwargs.get('tag')) return context
from django.views.generic import ListView + + from taggit.models import Tag class ByTagListView(ListView): def get_queryset(self): qs = super(ByTagListView, self).get_queryset() if 'tag' in self.kwargs: qs = qs.filter(tags__slug__in=[self.kwargs['tag']]) return qs def get_context_data(self, **kwargs): context = super(ByTagListView, self).get_context_data(**kwargs) - context['tag'] = self.kwargs.get('tag') + context['tag'] = Tag.objects.get(slug=self.kwargs.get('tag')) ? +++++++++++++++++++++ + return context
f8eb93f1845a7776c61a59bafc6fdeb689712aff
examples/comp/ask_user_dialog.py
examples/comp/ask_user_dialog.py
"""Example showing the Ask User dialog controls and overall usage.""" import fusionless as fu dialog = fu.AskUserDialog() dialog.add_text("text", default="Default text value") dialog.add_position("position", default=(0.2, 0.8)) dialog.add_slider("slider", default=0.5, min=-10, max=10) dialog.add_screw("screw") dialog.add_file_browse("file", default="C:/path/to/foo") dialog.add_path_browse("path") dialog.add_clip_browse("clip") dialog.add_checkbox("checkbox", name="Do not check this!") dialog.add_dropdown("dropdown", options=["A", "B", "C"]) dialog.add_multibutton("multibutton", options=["Foo", "Bar", "Nugget"]) result = dialog.show() if result is None: # Dialog was cancelled pass else: checked = result['checkbox'] if checked: print("You sure are living on the edge!") import pprint pprint.pprint(result)
"""Example showing the Ask User dialog controls and overall usage.""" import fusionless as fu dialog = fu.AskUserDialog("Example Ask User Dialog") dialog.add_text("text", default="Default text value") dialog.add_position("position", default=(0.2, 0.8)) dialog.add_slider("slider", default=0.5, min=-10, max=10) dialog.add_screw("screw") dialog.add_file_browse("file", default="C:/path/to/foo") dialog.add_path_browse("path") dialog.add_clip_browse("clip") dialog.add_checkbox("checkbox", name="Do not check this!") dialog.add_dropdown("dropdown", options=["A", "B", "C"]) dialog.add_multibutton("multibutton", options=["Foo", "Bar", "Nugget"]) result = dialog.show() if result is None: # Dialog was cancelled pass else: checked = result['checkbox'] if checked: print("You sure are living on the edge!") import pprint pprint.pprint(result)
Add dialog title to example
Add dialog title to example
Python
bsd-3-clause
BigRoy/fusionless,BigRoy/fusionscript
"""Example showing the Ask User dialog controls and overall usage.""" import fusionless as fu - dialog = fu.AskUserDialog() + dialog = fu.AskUserDialog("Example Ask User Dialog") dialog.add_text("text", default="Default text value") dialog.add_position("position", default=(0.2, 0.8)) dialog.add_slider("slider", default=0.5, min=-10, max=10) dialog.add_screw("screw") dialog.add_file_browse("file", default="C:/path/to/foo") dialog.add_path_browse("path") dialog.add_clip_browse("clip") dialog.add_checkbox("checkbox", name="Do not check this!") dialog.add_dropdown("dropdown", options=["A", "B", "C"]) dialog.add_multibutton("multibutton", options=["Foo", "Bar", "Nugget"]) result = dialog.show() if result is None: # Dialog was cancelled pass else: checked = result['checkbox'] if checked: print("You sure are living on the edge!") import pprint pprint.pprint(result)
Add dialog title to example
## Code Before: """Example showing the Ask User dialog controls and overall usage.""" import fusionless as fu dialog = fu.AskUserDialog() dialog.add_text("text", default="Default text value") dialog.add_position("position", default=(0.2, 0.8)) dialog.add_slider("slider", default=0.5, min=-10, max=10) dialog.add_screw("screw") dialog.add_file_browse("file", default="C:/path/to/foo") dialog.add_path_browse("path") dialog.add_clip_browse("clip") dialog.add_checkbox("checkbox", name="Do not check this!") dialog.add_dropdown("dropdown", options=["A", "B", "C"]) dialog.add_multibutton("multibutton", options=["Foo", "Bar", "Nugget"]) result = dialog.show() if result is None: # Dialog was cancelled pass else: checked = result['checkbox'] if checked: print("You sure are living on the edge!") import pprint pprint.pprint(result) ## Instruction: Add dialog title to example ## Code After: """Example showing the Ask User dialog controls and overall usage.""" import fusionless as fu dialog = fu.AskUserDialog("Example Ask User Dialog") dialog.add_text("text", default="Default text value") dialog.add_position("position", default=(0.2, 0.8)) dialog.add_slider("slider", default=0.5, min=-10, max=10) dialog.add_screw("screw") dialog.add_file_browse("file", default="C:/path/to/foo") dialog.add_path_browse("path") dialog.add_clip_browse("clip") dialog.add_checkbox("checkbox", name="Do not check this!") dialog.add_dropdown("dropdown", options=["A", "B", "C"]) dialog.add_multibutton("multibutton", options=["Foo", "Bar", "Nugget"]) result = dialog.show() if result is None: # Dialog was cancelled pass else: checked = result['checkbox'] if checked: print("You sure are living on the edge!") import pprint pprint.pprint(result)
"""Example showing the Ask User dialog controls and overall usage.""" import fusionless as fu - dialog = fu.AskUserDialog() + dialog = fu.AskUserDialog("Example Ask User Dialog") dialog.add_text("text", default="Default text value") dialog.add_position("position", default=(0.2, 0.8)) dialog.add_slider("slider", default=0.5, min=-10, max=10) dialog.add_screw("screw") dialog.add_file_browse("file", default="C:/path/to/foo") dialog.add_path_browse("path") dialog.add_clip_browse("clip") dialog.add_checkbox("checkbox", name="Do not check this!") dialog.add_dropdown("dropdown", options=["A", "B", "C"]) dialog.add_multibutton("multibutton", options=["Foo", "Bar", "Nugget"]) result = dialog.show() if result is None: # Dialog was cancelled pass else: checked = result['checkbox'] if checked: print("You sure are living on the edge!") import pprint pprint.pprint(result)
1963012ba4628f1f66d495e777275243dc7248e4
.CI/trigger_conda-forge.github.io.py
.CI/trigger_conda-forge.github.io.py
import os import requests import six import conda_smithy.ci_register def rebuild_travis(repo_slug): headers = conda_smithy.ci_register.travis_headers() # If we don't specify the API version, we get a 404. # Also fix the accepted content type. headers["Accept"] = "application/json" headers["Travis-API-Version"] = "3" # Trigger a build on `master`. encoded_slug = six.moves.urllib.parse.quote(repo_slug, safe='') url = 'https://api.travis-ci.org/repo/{}/requests'.format(encoded_slug) response = requests.post( url, json={"request": {"branch": "master"}}, headers=headers ) if response.status_code != 201: response.raise_for_status() if __name__ == '__main__': rebuild_travis('conda-forge/conda-forge.github.io')
import os import requests import six import conda_smithy.ci_register def rebuild_travis(repo_slug): headers = conda_smithy.ci_register.travis_headers() # If we don't specify the API version, we get a 404. # Also fix the accepted content type. headers["Accept"] = "application/json" headers["Travis-API-Version"] = "3" # Trigger a build on `master`. encoded_slug = six.moves.urllib.parse.quote(repo_slug, safe='') url = 'https://api.travis-ci.org/repo/{}/requests'.format(encoded_slug) response = requests.post( url, json={ "request": { "branch": "master", "message": "Triggering build from staged-recipes", } }, headers=headers ) if response.status_code != 201: response.raise_for_status() if __name__ == '__main__': rebuild_travis('conda-forge/conda-forge.github.io')
Add message to webpage repo trigger
Add message to webpage repo trigger Should fix triggering builds on the webpage repo even when the most recent commit message skip the CI build. Also should make it easier to identify builds started by this trigger. [ci skip] [skip ci]
Python
bsd-3-clause
jakirkham/staged-recipes,Cashalow/staged-recipes,dschreij/staged-recipes,scopatz/staged-recipes,stuertz/staged-recipes,conda-forge/staged-recipes,guillochon/staged-recipes,hadim/staged-recipes,SylvainCorlay/staged-recipes,mcs07/staged-recipes,scopatz/staged-recipes,sodre/staged-recipes,pmlandwehr/staged-recipes,sannykr/staged-recipes,shadowwalkersb/staged-recipes,sodre/staged-recipes,larray-project/staged-recipes,sodre/staged-recipes,patricksnape/staged-recipes,birdsarah/staged-recipes,NOAA-ORR-ERD/staged-recipes,pmlandwehr/staged-recipes,jochym/staged-recipes,chohner/staged-recipes,ceholden/staged-recipes,rmcgibbo/staged-recipes,hadim/staged-recipes,goanpeca/staged-recipes,barkls/staged-recipes,Cashalow/staged-recipes,kwilcox/staged-recipes,sannykr/staged-recipes,jjhelmus/staged-recipes,glemaitre/staged-recipes,isuruf/staged-recipes,mariusvniekerk/staged-recipes,larray-project/staged-recipes,jakirkham/staged-recipes,mariusvniekerk/staged-recipes,jochym/staged-recipes,chrisburr/staged-recipes,Juanlu001/staged-recipes,patricksnape/staged-recipes,petrushy/staged-recipes,rvalieris/staged-recipes,ReimarBauer/staged-recipes,synapticarbors/staged-recipes,rvalieris/staged-recipes,glemaitre/staged-recipes,guillochon/staged-recipes,petrushy/staged-recipes,Juanlu001/staged-recipes,asmeurer/staged-recipes,isuruf/staged-recipes,birdsarah/staged-recipes,conda-forge/staged-recipes,kwilcox/staged-recipes,barkls/staged-recipes,chrisburr/staged-recipes,jjhelmus/staged-recipes,mcs07/staged-recipes,basnijholt/staged-recipes,asmeurer/staged-recipes,ReimarBauer/staged-recipes,basnijholt/staged-recipes,cpaulik/staged-recipes,goanpeca/staged-recipes,johanneskoester/staged-recipes,shadowwalkersb/staged-recipes,synapticarbors/staged-recipes,SylvainCorlay/staged-recipes,igortg/staged-recipes,stuertz/staged-recipes,cpaulik/staged-recipes,NOAA-ORR-ERD/staged-recipes,ocefpaf/staged-recipes,johanneskoester/staged-recipes,rmcgibbo/staged-recipes,igortg/staged-recipes,ocefpaf/staged-recipes,chohner/staged-recipes,dschreij/staged-recipes,ceholden/staged-recipes
import os import requests import six import conda_smithy.ci_register def rebuild_travis(repo_slug): headers = conda_smithy.ci_register.travis_headers() # If we don't specify the API version, we get a 404. # Also fix the accepted content type. headers["Accept"] = "application/json" headers["Travis-API-Version"] = "3" # Trigger a build on `master`. encoded_slug = six.moves.urllib.parse.quote(repo_slug, safe='') url = 'https://api.travis-ci.org/repo/{}/requests'.format(encoded_slug) response = requests.post( url, - json={"request": {"branch": "master"}}, + json={ + "request": { + "branch": "master", + "message": "Triggering build from staged-recipes", + } + }, headers=headers ) if response.status_code != 201: response.raise_for_status() if __name__ == '__main__': rebuild_travis('conda-forge/conda-forge.github.io')
Add message to webpage repo trigger
## Code Before: import os import requests import six import conda_smithy.ci_register def rebuild_travis(repo_slug): headers = conda_smithy.ci_register.travis_headers() # If we don't specify the API version, we get a 404. # Also fix the accepted content type. headers["Accept"] = "application/json" headers["Travis-API-Version"] = "3" # Trigger a build on `master`. encoded_slug = six.moves.urllib.parse.quote(repo_slug, safe='') url = 'https://api.travis-ci.org/repo/{}/requests'.format(encoded_slug) response = requests.post( url, json={"request": {"branch": "master"}}, headers=headers ) if response.status_code != 201: response.raise_for_status() if __name__ == '__main__': rebuild_travis('conda-forge/conda-forge.github.io') ## Instruction: Add message to webpage repo trigger ## Code After: import os import requests import six import conda_smithy.ci_register def rebuild_travis(repo_slug): headers = conda_smithy.ci_register.travis_headers() # If we don't specify the API version, we get a 404. # Also fix the accepted content type. headers["Accept"] = "application/json" headers["Travis-API-Version"] = "3" # Trigger a build on `master`. encoded_slug = six.moves.urllib.parse.quote(repo_slug, safe='') url = 'https://api.travis-ci.org/repo/{}/requests'.format(encoded_slug) response = requests.post( url, json={ "request": { "branch": "master", "message": "Triggering build from staged-recipes", } }, headers=headers ) if response.status_code != 201: response.raise_for_status() if __name__ == '__main__': rebuild_travis('conda-forge/conda-forge.github.io')
import os import requests import six import conda_smithy.ci_register def rebuild_travis(repo_slug): headers = conda_smithy.ci_register.travis_headers() # If we don't specify the API version, we get a 404. # Also fix the accepted content type. headers["Accept"] = "application/json" headers["Travis-API-Version"] = "3" # Trigger a build on `master`. encoded_slug = six.moves.urllib.parse.quote(repo_slug, safe='') url = 'https://api.travis-ci.org/repo/{}/requests'.format(encoded_slug) response = requests.post( url, - json={"request": {"branch": "master"}}, + json={ + "request": { + "branch": "master", + "message": "Triggering build from staged-recipes", + } + }, headers=headers ) if response.status_code != 201: response.raise_for_status() if __name__ == '__main__': rebuild_travis('conda-forge/conda-forge.github.io')
001c955ffe8aef9ea3f0c6c5bcf8a857c3c10aeb
securethenews/sites/wagtail_hooks.py
securethenews/sites/wagtail_hooks.py
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register from .models import Site class SiteAdmin(ModelAdmin): model = Site menu_label = 'News Sites' menu_icon = 'site' add_to_settings_menu = False list_display = ('name', 'domain', 'score') def score(self, obj): return '{} / 100'.format(obj.scans.latest().score) score.short_description = 'Score' search_fields = ('name', 'domain') modeladmin_register(SiteAdmin)
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register from .models import Site class SiteAdmin(ModelAdmin): model = Site menu_label = 'News Sites' menu_icon = 'site' add_to_settings_menu = False list_display = ('name', 'domain', 'score', 'grade') def score(self, obj): return '{} / 100'.format(obj.scans.latest().score) score.short_description = 'Score' def grade(self, obj): return obj.scans.latest().grade['grade'] grade.short_description = 'Grade' search_fields = ('name', 'domain') modeladmin_register(SiteAdmin)
Add grade to list display for News Sites
Add grade to list display for News Sites
Python
agpl-3.0
freedomofpress/securethenews,DNSUsher/securethenews,freedomofpress/securethenews,DNSUsher/securethenews,freedomofpress/securethenews,freedomofpress/securethenews,DNSUsher/securethenews
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register from .models import Site class SiteAdmin(ModelAdmin): model = Site menu_label = 'News Sites' menu_icon = 'site' add_to_settings_menu = False - list_display = ('name', 'domain', 'score') + list_display = ('name', 'domain', 'score', 'grade') def score(self, obj): return '{} / 100'.format(obj.scans.latest().score) score.short_description = 'Score' + + def grade(self, obj): + return obj.scans.latest().grade['grade'] + grade.short_description = 'Grade' search_fields = ('name', 'domain') modeladmin_register(SiteAdmin)
Add grade to list display for News Sites
## Code Before: from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register from .models import Site class SiteAdmin(ModelAdmin): model = Site menu_label = 'News Sites' menu_icon = 'site' add_to_settings_menu = False list_display = ('name', 'domain', 'score') def score(self, obj): return '{} / 100'.format(obj.scans.latest().score) score.short_description = 'Score' search_fields = ('name', 'domain') modeladmin_register(SiteAdmin) ## Instruction: Add grade to list display for News Sites ## Code After: from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register from .models import Site class SiteAdmin(ModelAdmin): model = Site menu_label = 'News Sites' menu_icon = 'site' add_to_settings_menu = False list_display = ('name', 'domain', 'score', 'grade') def score(self, obj): return '{} / 100'.format(obj.scans.latest().score) score.short_description = 'Score' def grade(self, obj): return obj.scans.latest().grade['grade'] grade.short_description = 'Grade' search_fields = ('name', 'domain') modeladmin_register(SiteAdmin)
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register from .models import Site class SiteAdmin(ModelAdmin): model = Site menu_label = 'News Sites' menu_icon = 'site' add_to_settings_menu = False - list_display = ('name', 'domain', 'score') + list_display = ('name', 'domain', 'score', 'grade') ? +++++++++ def score(self, obj): return '{} / 100'.format(obj.scans.latest().score) score.short_description = 'Score' + def grade(self, obj): + return obj.scans.latest().grade['grade'] + grade.short_description = 'Grade' + search_fields = ('name', 'domain') modeladmin_register(SiteAdmin)
77c0c6087b385eb7d61ff3f08655312a9d9250f5
libravatar/urls.py
libravatar/urls.py
from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^account/', include('libravatar.account.urls')), (r'^tools/', include('libravatar.tools.urls')), (r'^$', 'libravatar.public.views.home'), (r'^resize/', 'libravatar.public.views.resize'), (r'^resolve/', 'libravatar.public.views.resolve'), (r'^admin/', include(admin.site.urls)), (r'^admin/doc/', include('django.contrib.admindocs.urls')), )
from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^account/', include('libravatar.account.urls')), (r'^tools/', include('libravatar.tools.urls')), (r'^$', 'libravatar.public.views.home'), (r'^resize/', 'libravatar.public.views.resize'), (r'^resolve/', 'libravatar.public.views.resolve'), )
Remove the admin from the url resolver
Remove the admin from the url resolver
Python
agpl-3.0
libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar,libravatar/libravatar
from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^account/', include('libravatar.account.urls')), (r'^tools/', include('libravatar.tools.urls')), (r'^$', 'libravatar.public.views.home'), (r'^resize/', 'libravatar.public.views.resize'), (r'^resolve/', 'libravatar.public.views.resolve'), - - (r'^admin/', include(admin.site.urls)), - (r'^admin/doc/', include('django.contrib.admindocs.urls')), )
Remove the admin from the url resolver
## Code Before: from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^account/', include('libravatar.account.urls')), (r'^tools/', include('libravatar.tools.urls')), (r'^$', 'libravatar.public.views.home'), (r'^resize/', 'libravatar.public.views.resize'), (r'^resolve/', 'libravatar.public.views.resolve'), (r'^admin/', include(admin.site.urls)), (r'^admin/doc/', include('django.contrib.admindocs.urls')), ) ## Instruction: Remove the admin from the url resolver ## Code After: from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^account/', include('libravatar.account.urls')), (r'^tools/', include('libravatar.tools.urls')), (r'^$', 'libravatar.public.views.home'), (r'^resize/', 'libravatar.public.views.resize'), (r'^resolve/', 'libravatar.public.views.resolve'), )
from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^account/', include('libravatar.account.urls')), (r'^tools/', include('libravatar.tools.urls')), (r'^$', 'libravatar.public.views.home'), (r'^resize/', 'libravatar.public.views.resize'), (r'^resolve/', 'libravatar.public.views.resolve'), - - (r'^admin/', include(admin.site.urls)), - (r'^admin/doc/', include('django.contrib.admindocs.urls')), )
33e88c063fedb11211e3786a9d722a9d12f72ce8
contrib/dn42_whoisd.py
contrib/dn42_whoisd.py
import argparse import asyncio import lglass.dn42 import lglass.whois.engine import lglass.whois.server def create_database(db_path): return lglass.dn42.DN42Database(db_path) if __name__ == "__main__": argparser = argparse.ArgumentParser(description="DN42 Whois server") argparser.add_argument("--port", "-p", default=4343) argparser.add_argument("--address", "-a", default="::1,127.0.0.1") argparser.add_argument("database") args = argparser.parse_args() db = create_database(args.database) engine = lglass.whois.engine.WhoisEngine(db) server = lglass.whois.server.SimpleWhoisServer(engine) loop = asyncio.get_event_loop() coro = asyncio.start_server(server.handle, args.address.split(","), args.port, loop=loop) s = loop.run_until_complete(coro) try: loop.run_forever() except KeyboardInterrupt: pass finally: s.close() loop.run_until_complete(s.wait_closed()) loop.close()
import argparse import asyncio import lglass.dn42 import lglass.whois.engine import lglass.whois.server def create_database(db_path): return lglass.dn42.DN42Database(db_path) if __name__ == "__main__": argparser = argparse.ArgumentParser(description="DN42 Whois server") argparser.add_argument("--port", "-p", default=4343) argparser.add_argument("--address", "-a", default="::1,127.0.0.1") argparser.add_argument("database") args = argparser.parse_args() db = create_database(args.database) engine = lglass.whois.engine.WhoisEngine(db) engine.type_hints[r"[0-9A-Za-z]+-DN42$"] = {"role", "person"} server = lglass.whois.server.SimpleWhoisServer(engine) loop = asyncio.get_event_loop() coro = asyncio.start_server(server.handle, args.address.split(","), args.port, loop=loop) s = loop.run_until_complete(coro) try: loop.run_forever() except KeyboardInterrupt: pass finally: s.close() loop.run_until_complete(s.wait_closed()) loop.close()
Add type hint for -DN42
Add type hint for -DN42
Python
mit
fritz0705/lglass
import argparse import asyncio import lglass.dn42 import lglass.whois.engine import lglass.whois.server def create_database(db_path): return lglass.dn42.DN42Database(db_path) if __name__ == "__main__": argparser = argparse.ArgumentParser(description="DN42 Whois server") argparser.add_argument("--port", "-p", default=4343) argparser.add_argument("--address", "-a", default="::1,127.0.0.1") argparser.add_argument("database") args = argparser.parse_args() db = create_database(args.database) engine = lglass.whois.engine.WhoisEngine(db) + engine.type_hints[r"[0-9A-Za-z]+-DN42$"] = {"role", "person"} server = lglass.whois.server.SimpleWhoisServer(engine) loop = asyncio.get_event_loop() coro = asyncio.start_server(server.handle, args.address.split(","), args.port, loop=loop) s = loop.run_until_complete(coro) try: loop.run_forever() except KeyboardInterrupt: pass finally: s.close() loop.run_until_complete(s.wait_closed()) loop.close()
Add type hint for -DN42
## Code Before: import argparse import asyncio import lglass.dn42 import lglass.whois.engine import lglass.whois.server def create_database(db_path): return lglass.dn42.DN42Database(db_path) if __name__ == "__main__": argparser = argparse.ArgumentParser(description="DN42 Whois server") argparser.add_argument("--port", "-p", default=4343) argparser.add_argument("--address", "-a", default="::1,127.0.0.1") argparser.add_argument("database") args = argparser.parse_args() db = create_database(args.database) engine = lglass.whois.engine.WhoisEngine(db) server = lglass.whois.server.SimpleWhoisServer(engine) loop = asyncio.get_event_loop() coro = asyncio.start_server(server.handle, args.address.split(","), args.port, loop=loop) s = loop.run_until_complete(coro) try: loop.run_forever() except KeyboardInterrupt: pass finally: s.close() loop.run_until_complete(s.wait_closed()) loop.close() ## Instruction: Add type hint for -DN42 ## Code After: import argparse import asyncio import lglass.dn42 import lglass.whois.engine import lglass.whois.server def create_database(db_path): return lglass.dn42.DN42Database(db_path) if __name__ == "__main__": argparser = argparse.ArgumentParser(description="DN42 Whois server") argparser.add_argument("--port", "-p", default=4343) argparser.add_argument("--address", "-a", default="::1,127.0.0.1") argparser.add_argument("database") args = argparser.parse_args() db = create_database(args.database) engine = lglass.whois.engine.WhoisEngine(db) engine.type_hints[r"[0-9A-Za-z]+-DN42$"] = {"role", "person"} server = lglass.whois.server.SimpleWhoisServer(engine) loop = asyncio.get_event_loop() coro = asyncio.start_server(server.handle, args.address.split(","), args.port, loop=loop) s = loop.run_until_complete(coro) try: loop.run_forever() except KeyboardInterrupt: pass finally: s.close() loop.run_until_complete(s.wait_closed()) loop.close()
import argparse import asyncio import lglass.dn42 import lglass.whois.engine import lglass.whois.server def create_database(db_path): return lglass.dn42.DN42Database(db_path) if __name__ == "__main__": argparser = argparse.ArgumentParser(description="DN42 Whois server") argparser.add_argument("--port", "-p", default=4343) argparser.add_argument("--address", "-a", default="::1,127.0.0.1") argparser.add_argument("database") args = argparser.parse_args() db = create_database(args.database) engine = lglass.whois.engine.WhoisEngine(db) + engine.type_hints[r"[0-9A-Za-z]+-DN42$"] = {"role", "person"} server = lglass.whois.server.SimpleWhoisServer(engine) loop = asyncio.get_event_loop() coro = asyncio.start_server(server.handle, args.address.split(","), args.port, loop=loop) s = loop.run_until_complete(coro) try: loop.run_forever() except KeyboardInterrupt: pass finally: s.close() loop.run_until_complete(s.wait_closed()) loop.close()
d666c5c818fbfc00f642cfeb24cb90aab94035cd
keyring/devpi_client.py
keyring/devpi_client.py
import contextlib import functools import pluggy import keyring from keyring.errors import KeyringError hookimpl = pluggy.HookimplMarker("devpiclient") # https://github.com/jaraco/jaraco.context/blob/c3a9b739/jaraco/context.py#L205 suppress = type('suppress', (contextlib.suppress, contextlib.ContextDecorator), {}) def restore_signature(func): # workaround for pytest-dev/pluggy#358 @functools.wraps(func) def wrapper(url, username): return func(url, username) return wrapper @hookimpl() @restore_signature @suppress(KeyringError) def devpiclient_get_password(url, username): """ >>> pluggy._hooks.varnames(devpiclient_get_password) (('url', 'username'), ()) >>> """ return keyring.get_password(url, username)
import contextlib import functools import pluggy import keyring.errors hookimpl = pluggy.HookimplMarker("devpiclient") # https://github.com/jaraco/jaraco.context/blob/c3a9b739/jaraco/context.py#L205 suppress = type('suppress', (contextlib.suppress, contextlib.ContextDecorator), {}) def restore_signature(func): # workaround for pytest-dev/pluggy#358 @functools.wraps(func) def wrapper(url, username): return func(url, username) return wrapper @hookimpl() @restore_signature @suppress(keyring.errors.KeyringError) def devpiclient_get_password(url, username): """ >>> pluggy._hooks.varnames(devpiclient_get_password) (('url', 'username'), ()) >>> """ return keyring.get_password(url, username)
Remove superfluous import by using the exception from the namespace.
Remove superfluous import by using the exception from the namespace.
Python
mit
jaraco/keyring
import contextlib import functools import pluggy - import keyring + import keyring.errors - from keyring.errors import KeyringError hookimpl = pluggy.HookimplMarker("devpiclient") # https://github.com/jaraco/jaraco.context/blob/c3a9b739/jaraco/context.py#L205 suppress = type('suppress', (contextlib.suppress, contextlib.ContextDecorator), {}) def restore_signature(func): # workaround for pytest-dev/pluggy#358 @functools.wraps(func) def wrapper(url, username): return func(url, username) return wrapper @hookimpl() @restore_signature - @suppress(KeyringError) + @suppress(keyring.errors.KeyringError) def devpiclient_get_password(url, username): """ >>> pluggy._hooks.varnames(devpiclient_get_password) (('url', 'username'), ()) >>> """ return keyring.get_password(url, username)
Remove superfluous import by using the exception from the namespace.
## Code Before: import contextlib import functools import pluggy import keyring from keyring.errors import KeyringError hookimpl = pluggy.HookimplMarker("devpiclient") # https://github.com/jaraco/jaraco.context/blob/c3a9b739/jaraco/context.py#L205 suppress = type('suppress', (contextlib.suppress, contextlib.ContextDecorator), {}) def restore_signature(func): # workaround for pytest-dev/pluggy#358 @functools.wraps(func) def wrapper(url, username): return func(url, username) return wrapper @hookimpl() @restore_signature @suppress(KeyringError) def devpiclient_get_password(url, username): """ >>> pluggy._hooks.varnames(devpiclient_get_password) (('url', 'username'), ()) >>> """ return keyring.get_password(url, username) ## Instruction: Remove superfluous import by using the exception from the namespace. ## Code After: import contextlib import functools import pluggy import keyring.errors hookimpl = pluggy.HookimplMarker("devpiclient") # https://github.com/jaraco/jaraco.context/blob/c3a9b739/jaraco/context.py#L205 suppress = type('suppress', (contextlib.suppress, contextlib.ContextDecorator), {}) def restore_signature(func): # workaround for pytest-dev/pluggy#358 @functools.wraps(func) def wrapper(url, username): return func(url, username) return wrapper @hookimpl() @restore_signature @suppress(keyring.errors.KeyringError) def devpiclient_get_password(url, username): """ >>> pluggy._hooks.varnames(devpiclient_get_password) (('url', 'username'), ()) >>> """ return keyring.get_password(url, username)
import contextlib import functools import pluggy - import keyring + import keyring.errors ? +++++++ - from keyring.errors import KeyringError hookimpl = pluggy.HookimplMarker("devpiclient") # https://github.com/jaraco/jaraco.context/blob/c3a9b739/jaraco/context.py#L205 suppress = type('suppress', (contextlib.suppress, contextlib.ContextDecorator), {}) def restore_signature(func): # workaround for pytest-dev/pluggy#358 @functools.wraps(func) def wrapper(url, username): return func(url, username) return wrapper @hookimpl() @restore_signature - @suppress(KeyringError) + @suppress(keyring.errors.KeyringError) ? +++++++++++++++ def devpiclient_get_password(url, username): """ >>> pluggy._hooks.varnames(devpiclient_get_password) (('url', 'username'), ()) >>> """ return keyring.get_password(url, username)
74c7f22cfdd14761932fb9c138435671d1490dfa
partner_industry_secondary/models/res_partner.py
partner_industry_secondary/models/res_partner.py
from odoo import api, exceptions, fields, models, _ class ResPartner(models.Model): _inherit = 'res.partner' industry_id = fields.Many2one(string='Main Industry') secondary_industry_ids = fields.Many2many( comodel_name='res.partner.industry', string="Secondary Industries", domain="[('id', '!=', industry_id)]") @api.constrains('industry_id', 'secondary_industry_ids') def _check_industries(self): if self.industry_id in self.secondary_industry_ids: raise exceptions.ValidationError( _('The main industry must be different ' 'from the secondary industries.'))
from odoo import api, exceptions, fields, models, _ class ResPartner(models.Model): _inherit = 'res.partner' industry_id = fields.Many2one(string='Main Industry') secondary_industry_ids = fields.Many2many( comodel_name='res.partner.industry', string="Secondary Industries", domain="[('id', '!=', industry_id)]") @api.constrains('industry_id', 'secondary_industry_ids') def _check_industries(self): for partner in self: if partner.industry_id in partner.secondary_industry_ids: raise exceptions.ValidationError( _('The main industry must be different ' 'from the secondary industries.'))
Make api constrains multi to avoid error when create a company with 2 contacts
partner_industry_Secondary: Make api constrains multi to avoid error when create a company with 2 contacts
Python
agpl-3.0
syci/partner-contact,syci/partner-contact
from odoo import api, exceptions, fields, models, _ class ResPartner(models.Model): _inherit = 'res.partner' industry_id = fields.Many2one(string='Main Industry') secondary_industry_ids = fields.Many2many( comodel_name='res.partner.industry', string="Secondary Industries", domain="[('id', '!=', industry_id)]") @api.constrains('industry_id', 'secondary_industry_ids') def _check_industries(self): + for partner in self: - if self.industry_id in self.secondary_industry_ids: + if partner.industry_id in partner.secondary_industry_ids: - raise exceptions.ValidationError( + raise exceptions.ValidationError( - _('The main industry must be different ' + _('The main industry must be different ' - 'from the secondary industries.')) + 'from the secondary industries.'))
Make api constrains multi to avoid error when create a company with 2 contacts
## Code Before: from odoo import api, exceptions, fields, models, _ class ResPartner(models.Model): _inherit = 'res.partner' industry_id = fields.Many2one(string='Main Industry') secondary_industry_ids = fields.Many2many( comodel_name='res.partner.industry', string="Secondary Industries", domain="[('id', '!=', industry_id)]") @api.constrains('industry_id', 'secondary_industry_ids') def _check_industries(self): if self.industry_id in self.secondary_industry_ids: raise exceptions.ValidationError( _('The main industry must be different ' 'from the secondary industries.')) ## Instruction: Make api constrains multi to avoid error when create a company with 2 contacts ## Code After: from odoo import api, exceptions, fields, models, _ class ResPartner(models.Model): _inherit = 'res.partner' industry_id = fields.Many2one(string='Main Industry') secondary_industry_ids = fields.Many2many( comodel_name='res.partner.industry', string="Secondary Industries", domain="[('id', '!=', industry_id)]") @api.constrains('industry_id', 'secondary_industry_ids') def _check_industries(self): for partner in self: if partner.industry_id in partner.secondary_industry_ids: raise exceptions.ValidationError( _('The main industry must be different ' 'from the secondary industries.'))
from odoo import api, exceptions, fields, models, _ class ResPartner(models.Model): _inherit = 'res.partner' industry_id = fields.Many2one(string='Main Industry') secondary_industry_ids = fields.Many2many( comodel_name='res.partner.industry', string="Secondary Industries", domain="[('id', '!=', industry_id)]") @api.constrains('industry_id', 'secondary_industry_ids') def _check_industries(self): + for partner in self: - if self.industry_id in self.secondary_industry_ids: ? ^ ^^ ^ ^^ + if partner.industry_id in partner.secondary_industry_ids: ? ++++ ^^^^^ ^ ^^^^^ ^ - raise exceptions.ValidationError( + raise exceptions.ValidationError( ? ++++ - _('The main industry must be different ' + _('The main industry must be different ' ? ++++ - 'from the secondary industries.')) + 'from the secondary industries.')) ? ++++
97f1d671966917d29d20c0afb554aaed69c4f9af
wysihtml5/tests/__init__.py
wysihtml5/tests/__init__.py
import os import sys import unittest def setup_django_settings(): os.chdir(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, os.getcwd()) os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings" def run_tests(): if not os.environ.get("DJANGO_SETTINGS_MODULE", False): setup_django_settings() from django.conf import settings from django.test.utils import get_runner TestRunner = get_runner(settings) test_suite = TestRunner(verbosity=2, interactive=True, failfast=False) test_suite.run_tests(["wysihtml5"]) def suite(): if not os.environ.get("DJANGO_SETTINGS_MODULE", False): setup_django_settings() else: from django.db.models.loading import load_app from django.conf import settings settings.INSTALLED_APPS = settings.INSTALLED_APPS + ['wysihtml5.tests',] map(load_app, settings.INSTALLED_APPS) from wysihtml5.tests import fields, widgets testsuite = unittest.TestSuite([ unittest.TestLoader().loadTestsFromModule(fields), unittest.TestLoader().loadTestsFromModule(widgets), ]) return testsuite if __name__ == "__main__": run_tests()
import os import sys import unittest def setup_django_settings(): os.chdir(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, os.getcwd()) os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings" def run_tests(): if not os.environ.get("DJANGO_SETTINGS_MODULE", False): setup_django_settings() from django.conf import settings from django.test.utils import get_runner TestRunner = get_runner(settings) test_suite = TestRunner(verbosity=2, interactive=True, failfast=False) test_suite.run_tests(["wysihtml5"]) def suite(): if not os.environ.get("DJANGO_SETTINGS_MODULE", False): setup_django_settings() else: from django.db.models.loading import load_app from django.conf import settings settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + \ ['wysihtml5.tests'] map(load_app, settings.INSTALLED_APPS) from wysihtml5.tests import fields, widgets testsuite = unittest.TestSuite([ unittest.TestLoader().loadTestsFromModule(fields), unittest.TestLoader().loadTestsFromModule(widgets), ]) return testsuite if __name__ == "__main__": run_tests()
Convert INSTALLED_APPS to list before concat
Convert INSTALLED_APPS to list before concat
Python
bsd-2-clause
danirus/django-wysihtml5,danirus/django-wysihtml5,danirus/django-wysihtml5
import os import sys import unittest def setup_django_settings(): os.chdir(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, os.getcwd()) os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings" def run_tests(): if not os.environ.get("DJANGO_SETTINGS_MODULE", False): setup_django_settings() from django.conf import settings from django.test.utils import get_runner TestRunner = get_runner(settings) test_suite = TestRunner(verbosity=2, interactive=True, failfast=False) test_suite.run_tests(["wysihtml5"]) def suite(): if not os.environ.get("DJANGO_SETTINGS_MODULE", False): setup_django_settings() else: from django.db.models.loading import load_app from django.conf import settings - settings.INSTALLED_APPS = settings.INSTALLED_APPS + ['wysihtml5.tests',] + settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + \ + ['wysihtml5.tests'] map(load_app, settings.INSTALLED_APPS) from wysihtml5.tests import fields, widgets testsuite = unittest.TestSuite([ unittest.TestLoader().loadTestsFromModule(fields), unittest.TestLoader().loadTestsFromModule(widgets), ]) return testsuite if __name__ == "__main__": run_tests()
Convert INSTALLED_APPS to list before concat
## Code Before: import os import sys import unittest def setup_django_settings(): os.chdir(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, os.getcwd()) os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings" def run_tests(): if not os.environ.get("DJANGO_SETTINGS_MODULE", False): setup_django_settings() from django.conf import settings from django.test.utils import get_runner TestRunner = get_runner(settings) test_suite = TestRunner(verbosity=2, interactive=True, failfast=False) test_suite.run_tests(["wysihtml5"]) def suite(): if not os.environ.get("DJANGO_SETTINGS_MODULE", False): setup_django_settings() else: from django.db.models.loading import load_app from django.conf import settings settings.INSTALLED_APPS = settings.INSTALLED_APPS + ['wysihtml5.tests',] map(load_app, settings.INSTALLED_APPS) from wysihtml5.tests import fields, widgets testsuite = unittest.TestSuite([ unittest.TestLoader().loadTestsFromModule(fields), unittest.TestLoader().loadTestsFromModule(widgets), ]) return testsuite if __name__ == "__main__": run_tests() ## Instruction: Convert INSTALLED_APPS to list before concat ## Code After: import os import sys import unittest def setup_django_settings(): os.chdir(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, os.getcwd()) os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings" def run_tests(): if not os.environ.get("DJANGO_SETTINGS_MODULE", False): setup_django_settings() from django.conf import settings from django.test.utils import get_runner TestRunner = get_runner(settings) test_suite = TestRunner(verbosity=2, interactive=True, failfast=False) test_suite.run_tests(["wysihtml5"]) def suite(): if not os.environ.get("DJANGO_SETTINGS_MODULE", False): setup_django_settings() else: from django.db.models.loading import load_app from django.conf import settings settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + \ ['wysihtml5.tests'] map(load_app, settings.INSTALLED_APPS) from wysihtml5.tests import fields, widgets testsuite = unittest.TestSuite([ unittest.TestLoader().loadTestsFromModule(fields), unittest.TestLoader().loadTestsFromModule(widgets), ]) return testsuite if __name__ == "__main__": run_tests()
import os import sys import unittest def setup_django_settings(): os.chdir(os.path.join(os.path.dirname(__file__), "..")) sys.path.insert(0, os.getcwd()) os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings" def run_tests(): if not os.environ.get("DJANGO_SETTINGS_MODULE", False): setup_django_settings() from django.conf import settings from django.test.utils import get_runner TestRunner = get_runner(settings) test_suite = TestRunner(verbosity=2, interactive=True, failfast=False) test_suite.run_tests(["wysihtml5"]) def suite(): if not os.environ.get("DJANGO_SETTINGS_MODULE", False): setup_django_settings() else: from django.db.models.loading import load_app from django.conf import settings - settings.INSTALLED_APPS = settings.INSTALLED_APPS + ['wysihtml5.tests',] ? ^^^^^^^^^^^^^^^^^^^^ + settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + \ ? +++++ + ^ + ['wysihtml5.tests'] map(load_app, settings.INSTALLED_APPS) from wysihtml5.tests import fields, widgets testsuite = unittest.TestSuite([ unittest.TestLoader().loadTestsFromModule(fields), unittest.TestLoader().loadTestsFromModule(widgets), ]) return testsuite if __name__ == "__main__": run_tests()
ea0087970b0c0adfd8942123899ff0ec231afa03
test/selenium/src/lib/page/extended_info.py
test/selenium/src/lib/page/extended_info.py
from selenium.common import exceptions from lib import base from lib.constants import locator class ExtendedInfo(base.Component): """Model representing an extended info box that allows the object to be mapped""" _locator = locator.ExtendedInfo def __init__(self, driver): super(ExtendedInfo, self).__init__(driver) self.button_map = None def _reload_contents(self): self.button_map = base.Button( self._driver, self._locator.BUTTON_MAP_TO) def map_to_object(self): try: self.button_map = base.Button( self._driver, self._locator.BUTTON_MAP_TO) self.button_map.click() except exceptions.StaleElementReferenceException: self._reload_contents() return self.map_to_object() def is_already_mapped(self): """Checks if the object is already mapped""" try: self._driver.find_element(*self._locator.ALREADY_MAPPED) return True except exceptions.NoSuchElementException: return False
from selenium.common import exceptions from lib import base from lib.constants import locator from lib.utils import selenium_utils class ExtendedInfo(base.Component): """Model representing an extended info box that allows the object to be mapped""" locator_cls = locator.ExtendedInfo def __init__(self, driver): super(ExtendedInfo, self).__init__(driver) self.is_mapped = None self.button_map = None self.title = base.Label(driver, self.locator_cls.TITLE) self._set_is_mapped() def map_to_object(self): selenium_utils.click_on_staleable_element( self._driver, self.locator_cls.BUTTON_MAP_TO) self.is_mapped = True def _set_is_mapped(self): """Checks if the object is already mapped""" try: self._driver.find_element(*self.locator_cls.ALREADY_MAPPED) self.is_mapped = True except exceptions.NoSuchElementException: self.is_mapped = False
Handle stealable element with utils
Handle stealable element with utils
Python
apache-2.0
AleksNeStu/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core,kr41/ggrc-core,prasannav7/ggrc-core,j0gurt/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,plamut/ggrc-core,NejcZupec/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,NejcZupec/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,prasannav7/ggrc-core,j0gurt/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,andrei-karalionak/ggrc-core,NejcZupec/ggrc-core,prasannav7/ggrc-core,selahssea/ggrc-core,edofic/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,josthkko/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,kr41/ggrc-core,plamut/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,prasannav7/ggrc-core,kr41/ggrc-core
from selenium.common import exceptions from lib import base from lib.constants import locator + from lib.utils import selenium_utils class ExtendedInfo(base.Component): """Model representing an extended info box that allows the object to be mapped""" - _locator = locator.ExtendedInfo + locator_cls = locator.ExtendedInfo def __init__(self, driver): super(ExtendedInfo, self).__init__(driver) + self.is_mapped = None self.button_map = None + self.title = base.Label(driver, self.locator_cls.TITLE) + self._set_is_mapped() - def _reload_contents(self): - self.button_map = base.Button( - self._driver, self._locator.BUTTON_MAP_TO) def map_to_object(self): - try: - self.button_map = base.Button( + selenium_utils.click_on_staleable_element( + self._driver, - self._driver, self._locator.BUTTON_MAP_TO) + self.locator_cls.BUTTON_MAP_TO) + self.is_mapped = True - self.button_map.click() - except exceptions.StaleElementReferenceException: - self._reload_contents() - return self.map_to_object() - def is_already_mapped(self): + def _set_is_mapped(self): """Checks if the object is already mapped""" try: - self._driver.find_element(*self._locator.ALREADY_MAPPED) + self._driver.find_element(*self.locator_cls.ALREADY_MAPPED) - return True + self.is_mapped = True except exceptions.NoSuchElementException: - return False + self.is_mapped = False
Handle stealable element with utils
## Code Before: from selenium.common import exceptions from lib import base from lib.constants import locator class ExtendedInfo(base.Component): """Model representing an extended info box that allows the object to be mapped""" _locator = locator.ExtendedInfo def __init__(self, driver): super(ExtendedInfo, self).__init__(driver) self.button_map = None def _reload_contents(self): self.button_map = base.Button( self._driver, self._locator.BUTTON_MAP_TO) def map_to_object(self): try: self.button_map = base.Button( self._driver, self._locator.BUTTON_MAP_TO) self.button_map.click() except exceptions.StaleElementReferenceException: self._reload_contents() return self.map_to_object() def is_already_mapped(self): """Checks if the object is already mapped""" try: self._driver.find_element(*self._locator.ALREADY_MAPPED) return True except exceptions.NoSuchElementException: return False ## Instruction: Handle stealable element with utils ## Code After: from selenium.common import exceptions from lib import base from lib.constants import locator from lib.utils import selenium_utils class ExtendedInfo(base.Component): """Model representing an extended info box that allows the object to be mapped""" locator_cls = locator.ExtendedInfo def __init__(self, driver): super(ExtendedInfo, self).__init__(driver) self.is_mapped = None self.button_map = None self.title = base.Label(driver, self.locator_cls.TITLE) self._set_is_mapped() def map_to_object(self): selenium_utils.click_on_staleable_element( self._driver, self.locator_cls.BUTTON_MAP_TO) self.is_mapped = True def _set_is_mapped(self): """Checks if the object is already mapped""" try: self._driver.find_element(*self.locator_cls.ALREADY_MAPPED) self.is_mapped = True except exceptions.NoSuchElementException: self.is_mapped = False
from selenium.common import exceptions from lib import base from lib.constants import locator + from lib.utils import selenium_utils class ExtendedInfo(base.Component): """Model representing an extended info box that allows the object to be mapped""" - _locator = locator.ExtendedInfo ? - + locator_cls = locator.ExtendedInfo ? ++++ def __init__(self, driver): super(ExtendedInfo, self).__init__(driver) + self.is_mapped = None self.button_map = None + self.title = base.Label(driver, self.locator_cls.TITLE) + self._set_is_mapped() - def _reload_contents(self): - self.button_map = base.Button( - self._driver, self._locator.BUTTON_MAP_TO) def map_to_object(self): - try: - self.button_map = base.Button( + selenium_utils.click_on_staleable_element( + self._driver, - self._driver, self._locator.BUTTON_MAP_TO) ? -- --------------- + self.locator_cls.BUTTON_MAP_TO) ? ++++ + self.is_mapped = True - self.button_map.click() - except exceptions.StaleElementReferenceException: - self._reload_contents() - return self.map_to_object() - def is_already_mapped(self): ? -------- + def _set_is_mapped(self): ? +++++ """Checks if the object is already mapped""" try: - self._driver.find_element(*self._locator.ALREADY_MAPPED) ? - + self._driver.find_element(*self.locator_cls.ALREADY_MAPPED) ? ++++ - return True + self.is_mapped = True except exceptions.NoSuchElementException: - return False + self.is_mapped = False
f4e5f0587c1214433de46fc5d86e77d849fdddc4
src/robot/utils/robotio.py
src/robot/utils/robotio.py
import io from .platform import PY3 def file_writer(path=None, encoding='UTF-8', newline=None): if path: f = io.open(path, 'w', encoding=encoding, newline=newline) else: f = io.StringIO(newline=newline) if PY3: return f # TODO: Consider removing this and using u'' or `from __future__ import # unicode_literals` everywhere. write = f.write f.write = lambda text: write(unicode(text)) return f def binary_file_writer(path=None): if path: return io.open(path, 'wb') f = io.BytesIO() getvalue = f.getvalue f.getvalue = lambda encoding='UTF-8': getvalue().decode(encoding) return f
import io from .platform import PY3 def file_writer(path=None, encoding='UTF-8', newline=None): if path: f = io.open(path, 'w', encoding=encoding, newline=newline) else: f = io.StringIO(newline=newline) if PY3: return f # These streams require written text to be Unicode. We don't want to add # `u` prefix to all our strings in Python 2, and cannot really use # `unicode_literals` either because many other Python 2 APIs accept only # byte strings. write = f.write f.write = lambda text: write(unicode(text)) return f def binary_file_writer(path=None): if path: return io.open(path, 'wb') f = io.BytesIO() getvalue = f.getvalue f.getvalue = lambda encoding='UTF-8': getvalue().decode(encoding) return f
Replace TODO with comment explaining why it wasn't possible
Replace TODO with comment explaining why it wasn't possible
Python
apache-2.0
alexandrul-ci/robotframework,synsun/robotframework,jaloren/robotframework,snyderr/robotframework,joongh/robotframework,HelioGuilherme66/robotframework,HelioGuilherme66/robotframework,alexandrul-ci/robotframework,synsun/robotframework,synsun/robotframework,snyderr/robotframework,joongh/robotframework,synsun/robotframework,alexandrul-ci/robotframework,snyderr/robotframework,alexandrul-ci/robotframework,jaloren/robotframework,synsun/robotframework,jaloren/robotframework,joongh/robotframework,HelioGuilherme66/robotframework,robotframework/robotframework,snyderr/robotframework,robotframework/robotframework,joongh/robotframework,jaloren/robotframework,joongh/robotframework,snyderr/robotframework,robotframework/robotframework,jaloren/robotframework,alexandrul-ci/robotframework
import io from .platform import PY3 def file_writer(path=None, encoding='UTF-8', newline=None): if path: f = io.open(path, 'w', encoding=encoding, newline=newline) else: f = io.StringIO(newline=newline) if PY3: return f - # TODO: Consider removing this and using u'' or `from __future__ import - # unicode_literals` everywhere. + # These streams require written text to be Unicode. We don't want to add + # `u` prefix to all our strings in Python 2, and cannot really use + # `unicode_literals` either because many other Python 2 APIs accept only + # byte strings. write = f.write f.write = lambda text: write(unicode(text)) return f def binary_file_writer(path=None): if path: return io.open(path, 'wb') f = io.BytesIO() getvalue = f.getvalue f.getvalue = lambda encoding='UTF-8': getvalue().decode(encoding) return f
Replace TODO with comment explaining why it wasn't possible
## Code Before: import io from .platform import PY3 def file_writer(path=None, encoding='UTF-8', newline=None): if path: f = io.open(path, 'w', encoding=encoding, newline=newline) else: f = io.StringIO(newline=newline) if PY3: return f # TODO: Consider removing this and using u'' or `from __future__ import # unicode_literals` everywhere. write = f.write f.write = lambda text: write(unicode(text)) return f def binary_file_writer(path=None): if path: return io.open(path, 'wb') f = io.BytesIO() getvalue = f.getvalue f.getvalue = lambda encoding='UTF-8': getvalue().decode(encoding) return f ## Instruction: Replace TODO with comment explaining why it wasn't possible ## Code After: import io from .platform import PY3 def file_writer(path=None, encoding='UTF-8', newline=None): if path: f = io.open(path, 'w', encoding=encoding, newline=newline) else: f = io.StringIO(newline=newline) if PY3: return f # These streams require written text to be Unicode. We don't want to add # `u` prefix to all our strings in Python 2, and cannot really use # `unicode_literals` either because many other Python 2 APIs accept only # byte strings. write = f.write f.write = lambda text: write(unicode(text)) return f def binary_file_writer(path=None): if path: return io.open(path, 'wb') f = io.BytesIO() getvalue = f.getvalue f.getvalue = lambda encoding='UTF-8': getvalue().decode(encoding) return f
import io from .platform import PY3 def file_writer(path=None, encoding='UTF-8', newline=None): if path: f = io.open(path, 'w', encoding=encoding, newline=newline) else: f = io.StringIO(newline=newline) if PY3: return f - # TODO: Consider removing this and using u'' or `from __future__ import - # unicode_literals` everywhere. + # These streams require written text to be Unicode. We don't want to add + # `u` prefix to all our strings in Python 2, and cannot really use + # `unicode_literals` either because many other Python 2 APIs accept only + # byte strings. write = f.write f.write = lambda text: write(unicode(text)) return f def binary_file_writer(path=None): if path: return io.open(path, 'wb') f = io.BytesIO() getvalue = f.getvalue f.getvalue = lambda encoding='UTF-8': getvalue().decode(encoding) return f
0e7be2adf1101ae842dddb3db3217957a8e5957f
iati/core/rulesets.py
iati/core/rulesets.py
"""A module containg a core representation of IATI Rulesets.""" class Ruleset(object): """Representation of a Ruleset as defined within the IATI SSOT.""" pass class Rule(object): """Representation of a Rule contained within a Ruleset. Acts as a base class for specific types of Rule that actually do something. """ pass class NoMoreThanOne(Rule): """Representation of a Rule that checks that there is no more than one Element matching a given XPath.""" pass
class Ruleset(object): """Representation of a Ruleset as defined within the IATI SSOT.""" pass class Rule(object): """Representation of a Rule contained within a Ruleset. Acts as a base class for specific types of Rule that actually do something. """ pass class NoMoreThanOne(Rule): """Representation of a Rule that checks that there is no more than one Element matching a given XPath.""" pass
Add a ruleset module TODO
Add a ruleset module TODO
Python
mit
IATI/iati.core,IATI/iati.core
- """A module containg a core representation of IATI Rulesets.""" class Ruleset(object): """Representation of a Ruleset as defined within the IATI SSOT.""" pass class Rule(object): """Representation of a Rule contained within a Ruleset. Acts as a base class for specific types of Rule that actually do something. """ pass class NoMoreThanOne(Rule): """Representation of a Rule that checks that there is no more than one Element matching a given XPath.""" pass
Add a ruleset module TODO
## Code Before: """A module containg a core representation of IATI Rulesets.""" class Ruleset(object): """Representation of a Ruleset as defined within the IATI SSOT.""" pass class Rule(object): """Representation of a Rule contained within a Ruleset. Acts as a base class for specific types of Rule that actually do something. """ pass class NoMoreThanOne(Rule): """Representation of a Rule that checks that there is no more than one Element matching a given XPath.""" pass ## Instruction: Add a ruleset module TODO ## Code After: class Ruleset(object): """Representation of a Ruleset as defined within the IATI SSOT.""" pass class Rule(object): """Representation of a Rule contained within a Ruleset. Acts as a base class for specific types of Rule that actually do something. """ pass class NoMoreThanOne(Rule): """Representation of a Rule that checks that there is no more than one Element matching a given XPath.""" pass
- """A module containg a core representation of IATI Rulesets.""" class Ruleset(object): """Representation of a Ruleset as defined within the IATI SSOT.""" pass class Rule(object): """Representation of a Rule contained within a Ruleset. Acts as a base class for specific types of Rule that actually do something. """ pass class NoMoreThanOne(Rule): """Representation of a Rule that checks that there is no more than one Element matching a given XPath.""" pass
4585ab22a4185122162b987cf8cc845a63ed5a05
pyheufybot/modules/say.py
pyheufybot/modules/say.py
from module_interface import Module, ModuleType class Say(Module): def __init__(self): self.trigger = "say" self.moduleType = ModuleType.ACTIVE self.messagesTypes = ["PRIVMSG"] self.helpText = "Usage: say <message> | Makes the bot say the given line" def execute(self, message, serverInfo): pass
from module_interface import Module, ModuleType from message import IRCResponse, ResponseType class Say(Module): def __init__(self): self.trigger = "say" self.moduleType = ModuleType.ACTIVE self.messagesTypes = ["PRIVMSG"] self.helpText = "Usage: say <message> | Makes the bot say the given line" def execute(self, message, serverInfo): return [ IRCResponse(message.replyTo, ResponseType.MESSAGE, message.messageText) ]
Make it possible for modules to send a response
Make it possible for modules to send a response
Python
mit
Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot
from module_interface import Module, ModuleType + from message import IRCResponse, ResponseType class Say(Module): def __init__(self): self.trigger = "say" self.moduleType = ModuleType.ACTIVE self.messagesTypes = ["PRIVMSG"] self.helpText = "Usage: say <message> | Makes the bot say the given line" def execute(self, message, serverInfo): - pass + return [ IRCResponse(message.replyTo, ResponseType.MESSAGE, message.messageText) ]
Make it possible for modules to send a response
## Code Before: from module_interface import Module, ModuleType class Say(Module): def __init__(self): self.trigger = "say" self.moduleType = ModuleType.ACTIVE self.messagesTypes = ["PRIVMSG"] self.helpText = "Usage: say <message> | Makes the bot say the given line" def execute(self, message, serverInfo): pass ## Instruction: Make it possible for modules to send a response ## Code After: from module_interface import Module, ModuleType from message import IRCResponse, ResponseType class Say(Module): def __init__(self): self.trigger = "say" self.moduleType = ModuleType.ACTIVE self.messagesTypes = ["PRIVMSG"] self.helpText = "Usage: say <message> | Makes the bot say the given line" def execute(self, message, serverInfo): return [ IRCResponse(message.replyTo, ResponseType.MESSAGE, message.messageText) ]
from module_interface import Module, ModuleType + from message import IRCResponse, ResponseType class Say(Module): def __init__(self): self.trigger = "say" self.moduleType = ModuleType.ACTIVE self.messagesTypes = ["PRIVMSG"] self.helpText = "Usage: say <message> | Makes the bot say the given line" def execute(self, message, serverInfo): - pass + return [ IRCResponse(message.replyTo, ResponseType.MESSAGE, message.messageText) ]
b0edec6bc9a4d77a1f0ea0f803ea892f35cc2f4f
text_field.py
text_field.py
class TextField: def __init__(self, model, view): self.model = model self.view = view self.model.view = self self.view.editingFinished.connect(self.editingFinished) def editingFinished(self): self.model.text = self.view.text() # model --> view def refresh(self): self.view.setText(self.model.text)
class TextField: def __init__(self, model, view): self.model = model self.view = view self.model.view = self # Make TextField also work for QLabel, which doesn't allow editing if hasattr(self.view, 'editingFinished'): self.view.editingFinished.connect(self.editingFinished) def editingFinished(self): self.model.text = self.view.text() # model --> view def refresh(self): self.view.setText(self.model.text)
Make TextField also work with a QLabel view, which doesn't allow editing.
Make TextField also work with a QLabel view, which doesn't allow editing.
Python
bsd-3-clause
hsoft/qtlib
class TextField: def __init__(self, model, view): self.model = model self.view = view self.model.view = self + # Make TextField also work for QLabel, which doesn't allow editing + if hasattr(self.view, 'editingFinished'): - self.view.editingFinished.connect(self.editingFinished) + self.view.editingFinished.connect(self.editingFinished) def editingFinished(self): self.model.text = self.view.text() # model --> view def refresh(self): self.view.setText(self.model.text)
Make TextField also work with a QLabel view, which doesn't allow editing.
## Code Before: class TextField: def __init__(self, model, view): self.model = model self.view = view self.model.view = self self.view.editingFinished.connect(self.editingFinished) def editingFinished(self): self.model.text = self.view.text() # model --> view def refresh(self): self.view.setText(self.model.text) ## Instruction: Make TextField also work with a QLabel view, which doesn't allow editing. ## Code After: class TextField: def __init__(self, model, view): self.model = model self.view = view self.model.view = self # Make TextField also work for QLabel, which doesn't allow editing if hasattr(self.view, 'editingFinished'): self.view.editingFinished.connect(self.editingFinished) def editingFinished(self): self.model.text = self.view.text() # model --> view def refresh(self): self.view.setText(self.model.text)
class TextField: def __init__(self, model, view): self.model = model self.view = view self.model.view = self + # Make TextField also work for QLabel, which doesn't allow editing + if hasattr(self.view, 'editingFinished'): - self.view.editingFinished.connect(self.editingFinished) + self.view.editingFinished.connect(self.editingFinished) ? ++++ def editingFinished(self): self.model.text = self.view.text() # model --> view def refresh(self): self.view.setText(self.model.text)
c988925927ec9d50ded81c92b85c3abce6c2638f
fireplace/carddata/minions/neutral/legendary.py
fireplace/carddata/minions/neutral/legendary.py
import random from ...card import * # Ragnaros the Firelord class EX1_298(Card): cantAttack = True def onTurnEnd(self, player): self.hit(random.choice(self.controller.getTargets(TARGET_ENEMY_CHARACTERS)), 8) # Harrison Jones class EX1_558(Card): def action(self): weapon = self.controller.opponent.hero.weapon if weapon: weapon.destroy() self.controller.draw(weapon.durability) # Deathwing class NEW1_030(Card): def action(self): for target in self.controller.getTargets(TARGET_ALL_MINIONS): # Let's not kill ourselves in the process if target is not self: target.destroy() self.controller.discardHand()
import random from ...card import * # Cairne Bloodhoof class EX1_110(Card): deathrattle = summonMinion("EX1_110t") # Baron Geddon class EX1_249(Card): def action(self): for target in self.controller.getTargets(TARGET_ALL_MINIONS): if target is not self: self.hit(target, 2) # Ragnaros the Firelord class EX1_298(Card): cantAttack = True def onTurnEnd(self, player): self.hit(random.choice(self.controller.getTargets(TARGET_ENEMY_CHARACTERS)), 8) # Harrison Jones class EX1_558(Card): def action(self): weapon = self.controller.opponent.hero.weapon if weapon: weapon.destroy() self.controller.draw(weapon.durability) # Malygos class EX1_563(Card): spellpower = 5 # Deathwing class NEW1_030(Card): def action(self): for target in self.controller.getTargets(TARGET_ALL_MINIONS): # Let's not kill ourselves in the process if target is not self: target.destroy() self.controller.discardHand()
Implement Baron Geddon, Cairne Bloodhoof and Malygos
Implement Baron Geddon, Cairne Bloodhoof and Malygos
Python
agpl-3.0
amw2104/fireplace,beheh/fireplace,smallnamespace/fireplace,liujimj/fireplace,butozerca/fireplace,oftc-ftw/fireplace,Ragowit/fireplace,Ragowit/fireplace,smallnamespace/fireplace,NightKev/fireplace,Meerkov/fireplace,jleclanche/fireplace,butozerca/fireplace,Meerkov/fireplace,amw2104/fireplace,oftc-ftw/fireplace,liujimj/fireplace
import random from ...card import * + + + # Cairne Bloodhoof + class EX1_110(Card): + deathrattle = summonMinion("EX1_110t") + + + # Baron Geddon + class EX1_249(Card): + def action(self): + for target in self.controller.getTargets(TARGET_ALL_MINIONS): + if target is not self: + self.hit(target, 2) # Ragnaros the Firelord class EX1_298(Card): cantAttack = True def onTurnEnd(self, player): self.hit(random.choice(self.controller.getTargets(TARGET_ENEMY_CHARACTERS)), 8) # Harrison Jones class EX1_558(Card): def action(self): weapon = self.controller.opponent.hero.weapon if weapon: weapon.destroy() self.controller.draw(weapon.durability) + # Malygos + class EX1_563(Card): + spellpower = 5 + + # Deathwing class NEW1_030(Card): def action(self): for target in self.controller.getTargets(TARGET_ALL_MINIONS): # Let's not kill ourselves in the process if target is not self: target.destroy() self.controller.discardHand()
Implement Baron Geddon, Cairne Bloodhoof and Malygos
## Code Before: import random from ...card import * # Ragnaros the Firelord class EX1_298(Card): cantAttack = True def onTurnEnd(self, player): self.hit(random.choice(self.controller.getTargets(TARGET_ENEMY_CHARACTERS)), 8) # Harrison Jones class EX1_558(Card): def action(self): weapon = self.controller.opponent.hero.weapon if weapon: weapon.destroy() self.controller.draw(weapon.durability) # Deathwing class NEW1_030(Card): def action(self): for target in self.controller.getTargets(TARGET_ALL_MINIONS): # Let's not kill ourselves in the process if target is not self: target.destroy() self.controller.discardHand() ## Instruction: Implement Baron Geddon, Cairne Bloodhoof and Malygos ## Code After: import random from ...card import * # Cairne Bloodhoof class EX1_110(Card): deathrattle = summonMinion("EX1_110t") # Baron Geddon class EX1_249(Card): def action(self): for target in self.controller.getTargets(TARGET_ALL_MINIONS): if target is not self: self.hit(target, 2) # Ragnaros the Firelord class EX1_298(Card): cantAttack = True def onTurnEnd(self, player): self.hit(random.choice(self.controller.getTargets(TARGET_ENEMY_CHARACTERS)), 8) # Harrison Jones class EX1_558(Card): def action(self): weapon = self.controller.opponent.hero.weapon if weapon: weapon.destroy() self.controller.draw(weapon.durability) # Malygos class EX1_563(Card): spellpower = 5 # Deathwing class NEW1_030(Card): def action(self): for target in self.controller.getTargets(TARGET_ALL_MINIONS): # Let's not kill ourselves in the process if target is not self: target.destroy() self.controller.discardHand()
import random from ...card import * + + + # Cairne Bloodhoof + class EX1_110(Card): + deathrattle = summonMinion("EX1_110t") + + + # Baron Geddon + class EX1_249(Card): + def action(self): + for target in self.controller.getTargets(TARGET_ALL_MINIONS): + if target is not self: + self.hit(target, 2) # Ragnaros the Firelord class EX1_298(Card): cantAttack = True def onTurnEnd(self, player): self.hit(random.choice(self.controller.getTargets(TARGET_ENEMY_CHARACTERS)), 8) # Harrison Jones class EX1_558(Card): def action(self): weapon = self.controller.opponent.hero.weapon if weapon: weapon.destroy() self.controller.draw(weapon.durability) + # Malygos + class EX1_563(Card): + spellpower = 5 + + # Deathwing class NEW1_030(Card): def action(self): for target in self.controller.getTargets(TARGET_ALL_MINIONS): # Let's not kill ourselves in the process if target is not self: target.destroy() self.controller.discardHand()
9e9910346f7bacdc2a4fc2e92ecb8237bf38275e
plumbium/environment.py
plumbium/environment.py
import os try: import pip except ImportError: pass import socket def get_environment(): """Obtain information about the executing environment. Captures: * installed Python packages using pip (if available), * hostname * uname * environment variables Returns: dict: a dict with the keys ``python_packages``, ``hostname``, ``uname`` and ``environ`` """ env = {} try: env['python_packages'] = [str(p) for p in pip.get_installed_distributions()] except: pass env['hostname'] = socket.gethostname() env['uname'] = os.uname() env['environ'] = dict(os.environ) return env
import os try: import pip except ImportError: pass import socket def get_environment(): """Obtain information about the executing environment. Captures: * installed Python packages using pip (if available), * hostname * uname * environment variables Returns: dict: a dict with the keys ``python_packages``, ``hostname``, ``uname`` and ``environ`` """ env = {} try: env['python_packages'] = [str(p) for p in pip.get_installed_distributions()] except: # pylint: disable=bare-except pass env['hostname'] = socket.gethostname() env['uname'] = os.uname() env['environ'] = dict(os.environ) return env
Stop pylint complaining about bare-except
Stop pylint complaining about bare-except
Python
mit
jstutters/Plumbium
import os try: import pip except ImportError: pass import socket def get_environment(): """Obtain information about the executing environment. Captures: * installed Python packages using pip (if available), * hostname * uname * environment variables Returns: dict: a dict with the keys ``python_packages``, ``hostname``, ``uname`` and ``environ`` """ env = {} try: env['python_packages'] = [str(p) for p in pip.get_installed_distributions()] - except: + except: # pylint: disable=bare-except pass env['hostname'] = socket.gethostname() env['uname'] = os.uname() env['environ'] = dict(os.environ) return env
Stop pylint complaining about bare-except
## Code Before: import os try: import pip except ImportError: pass import socket def get_environment(): """Obtain information about the executing environment. Captures: * installed Python packages using pip (if available), * hostname * uname * environment variables Returns: dict: a dict with the keys ``python_packages``, ``hostname``, ``uname`` and ``environ`` """ env = {} try: env['python_packages'] = [str(p) for p in pip.get_installed_distributions()] except: pass env['hostname'] = socket.gethostname() env['uname'] = os.uname() env['environ'] = dict(os.environ) return env ## Instruction: Stop pylint complaining about bare-except ## Code After: import os try: import pip except ImportError: pass import socket def get_environment(): """Obtain information about the executing environment. Captures: * installed Python packages using pip (if available), * hostname * uname * environment variables Returns: dict: a dict with the keys ``python_packages``, ``hostname``, ``uname`` and ``environ`` """ env = {} try: env['python_packages'] = [str(p) for p in pip.get_installed_distributions()] except: # pylint: disable=bare-except pass env['hostname'] = socket.gethostname() env['uname'] = os.uname() env['environ'] = dict(os.environ) return env
import os try: import pip except ImportError: pass import socket def get_environment(): """Obtain information about the executing environment. Captures: * installed Python packages using pip (if available), * hostname * uname * environment variables Returns: dict: a dict with the keys ``python_packages``, ``hostname``, ``uname`` and ``environ`` """ env = {} try: env['python_packages'] = [str(p) for p in pip.get_installed_distributions()] - except: + except: # pylint: disable=bare-except pass env['hostname'] = socket.gethostname() env['uname'] = os.uname() env['environ'] = dict(os.environ) return env
499defc47f0647afda47be8a8a25d04095b07e1b
nn/slmc/accuracy.py
nn/slmc/accuracy.py
import tensorflow as tf from ..util import static_shape, static_rank def accuracy(output_layer, true_label): assert static_rank(output_layer) == 2 #assert static_shape(output_layer)[0] == (batch size) #assert static_shape(output_layer)[1] == (number of classes) assert static_rank(true_label) == 1 #assert static_shape(true_label)[0] == (batch size) assert static_shape(output_layer)[0] == static_shape(true_label)[0] correct_prediction = tf.equal(tf.argmax(output_layer, 1), true_label) return tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
import tensorflow as tf from ..util import static_shape, static_rank def accuracy(output_layer, true_label): assert static_rank(output_layer) == 2 #assert static_shape(output_layer)[0] == (batch size) #assert static_shape(output_layer)[1] == (number of classes) assert static_rank(true_label) == 1 #assert static_shape(true_label)[0] == (batch size) assert static_shape(output_layer)[0] == static_shape(true_label)[0] correct_prediction = tf.equal(tf.argmax(output_layer, 1), true_label) return tf.reduce_mean(tf.to_float(correct_prediction))
Use to_float instead of cast
Use to_float instead of cast
Python
unlicense
raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten
import tensorflow as tf from ..util import static_shape, static_rank def accuracy(output_layer, true_label): assert static_rank(output_layer) == 2 #assert static_shape(output_layer)[0] == (batch size) #assert static_shape(output_layer)[1] == (number of classes) assert static_rank(true_label) == 1 #assert static_shape(true_label)[0] == (batch size) assert static_shape(output_layer)[0] == static_shape(true_label)[0] correct_prediction = tf.equal(tf.argmax(output_layer, 1), true_label) - return tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) + return tf.reduce_mean(tf.to_float(correct_prediction))
Use to_float instead of cast
## Code Before: import tensorflow as tf from ..util import static_shape, static_rank def accuracy(output_layer, true_label): assert static_rank(output_layer) == 2 #assert static_shape(output_layer)[0] == (batch size) #assert static_shape(output_layer)[1] == (number of classes) assert static_rank(true_label) == 1 #assert static_shape(true_label)[0] == (batch size) assert static_shape(output_layer)[0] == static_shape(true_label)[0] correct_prediction = tf.equal(tf.argmax(output_layer, 1), true_label) return tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) ## Instruction: Use to_float instead of cast ## Code After: import tensorflow as tf from ..util import static_shape, static_rank def accuracy(output_layer, true_label): assert static_rank(output_layer) == 2 #assert static_shape(output_layer)[0] == (batch size) #assert static_shape(output_layer)[1] == (number of classes) assert static_rank(true_label) == 1 #assert static_shape(true_label)[0] == (batch size) assert static_shape(output_layer)[0] == static_shape(true_label)[0] correct_prediction = tf.equal(tf.argmax(output_layer, 1), true_label) return tf.reduce_mean(tf.to_float(correct_prediction))
import tensorflow as tf from ..util import static_shape, static_rank def accuracy(output_layer, true_label): assert static_rank(output_layer) == 2 #assert static_shape(output_layer)[0] == (batch size) #assert static_shape(output_layer)[1] == (number of classes) assert static_rank(true_label) == 1 #assert static_shape(true_label)[0] == (batch size) assert static_shape(output_layer)[0] == static_shape(true_label)[0] correct_prediction = tf.equal(tf.argmax(output_layer, 1), true_label) - return tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) ? ^ - ------------ + return tf.reduce_mean(tf.to_float(correct_prediction)) ? ^^^^^^
94ad884a245dea36110718577e47eb0c7b0c2b0a
skyfield/tests/test_topos.py
skyfield/tests/test_topos.py
from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (15, 25, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=0, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees #print(b.latitude.degrees, deg, error_mas) assert error_mas < 0.1
from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (-15, 15, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=angle, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1 error_degrees = abs(b.longitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1
Add test for subpoint() longitude correctness
Add test for subpoint() longitude correctness
Python
mit
skyfielders/python-skyfield,skyfielders/python-skyfield
from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos - angle = (15, 25, 35, 45) + angle = (-15, 15, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. - top = Topos(latitude_degrees=angle, longitude_degrees=0, elevation_m=0) + top = Topos(latitude_degrees=angle, longitude_degrees=angle, elevation_m=0) p = top.at(t) b = p.subpoint() + error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees - #print(b.latitude.degrees, deg, error_mas) assert error_mas < 0.1 + error_degrees = abs(b.longitude.degrees - angle) + error_mas = 60.0 * 60.0 * 1000.0 * error_degrees + assert error_mas < 0.1 +
Add test for subpoint() longitude correctness
## Code Before: from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (15, 25, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=0, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees #print(b.latitude.degrees, deg, error_mas) assert error_mas < 0.1 ## Instruction: Add test for subpoint() longitude correctness ## Code After: from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos angle = (-15, 15, 35, 45) def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. top = Topos(latitude_degrees=angle, longitude_degrees=angle, elevation_m=0) p = top.at(t) b = p.subpoint() error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1 error_degrees = abs(b.longitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees assert error_mas < 0.1
from numpy import abs from skyfield.api import load from skyfield.toposlib import Topos - angle = (15, 25, 35, 45) ? ^ + angle = (-15, 15, 35, 45) ? + ^ def ts(): yield load.timescale() def test_beneath(ts, angle): t = ts.utc(2018, 1, 19, 14, 37, 55) # An elevation of 0 is more difficult for the routine's accuracy # than a very large elevation. - top = Topos(latitude_degrees=angle, longitude_degrees=0, elevation_m=0) ? ^ + top = Topos(latitude_degrees=angle, longitude_degrees=angle, elevation_m=0) ? ^^^^^ p = top.at(t) b = p.subpoint() + error_degrees = abs(b.latitude.degrees - angle) error_mas = 60.0 * 60.0 * 1000.0 * error_degrees - #print(b.latitude.degrees, deg, error_mas) assert error_mas < 0.1 + + error_degrees = abs(b.longitude.degrees - angle) + error_mas = 60.0 * 60.0 * 1000.0 * error_degrees + assert error_mas < 0.1
27a1d78611cef1ab23044db22bd4bf7c61582efe
src/data/Track/UploadHandlers/YoutubeUploadHandler.py
src/data/Track/UploadHandlers/YoutubeUploadHandler.py
import os from data.Track.UploadHandler import UploadHandler from src.data.Track.Tracks import YoutubeTrack class YoutubeUploadHandler(UploadHandler): def __init__(self, workingDir): super().__init__(workingDir) self.attributes.update({ "URL": ["string", "required", "url"] }) def trackFromUploadedAttributes(self, attributes): track = YoutubeTrack( attributes["Artist"], attributes["Album"], attributes["Title"] ) del attributes["Artist"] del attributes["Album"] del attributes["Title"] super().autoImportAttributes(track, attributes) super().writeTrackRecord(track) artistPath = os.path.join(self.workingDir, track.artistName) albumPath = os.path.join(artistPath, track.albumTitle) recordPath = os.path.join(albumPath, track.title) + ".rec" localFilePath = os.path.join(recordPath, "muzak.yturl") fileToWrite = open(localFilePath, 'w+') fileToWrite.write(track.url) fileToWrite.close() return track
import os from src.data.Track import UploadHandler from src.data.Track.Tracks import YoutubeTrack class YoutubeUploadHandler(UploadHandler): def __init__(self, workingDir): super().__init__(workingDir) self.attributes.update({ "URL": ["string", "required", "url"] }) def trackFromUploadedAttributes(self, attributes): track = YoutubeTrack( attributes["Artist"], attributes["Album"], attributes["Title"] ) del attributes["Artist"] del attributes["Album"] del attributes["Title"] super().autoImportAttributes(track, attributes) super().writeTrackRecord(track) artistPath = os.path.join(self.workingDir, track.artistName) albumPath = os.path.join(artistPath, track.albumTitle) recordPath = os.path.join(albumPath, track.title) + ".rec" localFilePath = os.path.join(recordPath, "muzak.yturl") fileToWrite = open(localFilePath, 'w+') fileToWrite.write(track.url) fileToWrite.close() return track
Fix wrong import from UploadHandler
Fix wrong import from UploadHandler
Python
agpl-3.0
Pynitus-Universe/Pynitus-Backend,Pynitus-Universe/Pynitus-Backend,Pynitus-Universe/Pynitus,Pynitus-Universe/Pynitus
import os + from src.data.Track import UploadHandler - from data.Track.UploadHandler import UploadHandler - from src.data.Track.Tracks import YoutubeTrack class YoutubeUploadHandler(UploadHandler): def __init__(self, workingDir): super().__init__(workingDir) self.attributes.update({ "URL": ["string", "required", "url"] }) def trackFromUploadedAttributes(self, attributes): track = YoutubeTrack( attributes["Artist"], attributes["Album"], attributes["Title"] ) del attributes["Artist"] del attributes["Album"] del attributes["Title"] super().autoImportAttributes(track, attributes) super().writeTrackRecord(track) artistPath = os.path.join(self.workingDir, track.artistName) albumPath = os.path.join(artistPath, track.albumTitle) recordPath = os.path.join(albumPath, track.title) + ".rec" localFilePath = os.path.join(recordPath, "muzak.yturl") fileToWrite = open(localFilePath, 'w+') fileToWrite.write(track.url) fileToWrite.close() return track
Fix wrong import from UploadHandler
## Code Before: import os from data.Track.UploadHandler import UploadHandler from src.data.Track.Tracks import YoutubeTrack class YoutubeUploadHandler(UploadHandler): def __init__(self, workingDir): super().__init__(workingDir) self.attributes.update({ "URL": ["string", "required", "url"] }) def trackFromUploadedAttributes(self, attributes): track = YoutubeTrack( attributes["Artist"], attributes["Album"], attributes["Title"] ) del attributes["Artist"] del attributes["Album"] del attributes["Title"] super().autoImportAttributes(track, attributes) super().writeTrackRecord(track) artistPath = os.path.join(self.workingDir, track.artistName) albumPath = os.path.join(artistPath, track.albumTitle) recordPath = os.path.join(albumPath, track.title) + ".rec" localFilePath = os.path.join(recordPath, "muzak.yturl") fileToWrite = open(localFilePath, 'w+') fileToWrite.write(track.url) fileToWrite.close() return track ## Instruction: Fix wrong import from UploadHandler ## Code After: import os from src.data.Track import UploadHandler from src.data.Track.Tracks import YoutubeTrack class YoutubeUploadHandler(UploadHandler): def __init__(self, workingDir): super().__init__(workingDir) self.attributes.update({ "URL": ["string", "required", "url"] }) def trackFromUploadedAttributes(self, attributes): track = YoutubeTrack( attributes["Artist"], attributes["Album"], attributes["Title"] ) del attributes["Artist"] del attributes["Album"] del attributes["Title"] super().autoImportAttributes(track, attributes) super().writeTrackRecord(track) artistPath = os.path.join(self.workingDir, track.artistName) albumPath = os.path.join(artistPath, track.albumTitle) recordPath = os.path.join(albumPath, track.title) + ".rec" localFilePath = os.path.join(recordPath, "muzak.yturl") fileToWrite = open(localFilePath, 'w+') fileToWrite.write(track.url) fileToWrite.close() return track
import os - from data.Track.UploadHandler import UploadHandler ? -------------- + from src.data.Track import UploadHandler ? ++++ - from src.data.Track.Tracks import YoutubeTrack class YoutubeUploadHandler(UploadHandler): def __init__(self, workingDir): super().__init__(workingDir) self.attributes.update({ "URL": ["string", "required", "url"] }) def trackFromUploadedAttributes(self, attributes): track = YoutubeTrack( attributes["Artist"], attributes["Album"], attributes["Title"] ) del attributes["Artist"] del attributes["Album"] del attributes["Title"] super().autoImportAttributes(track, attributes) super().writeTrackRecord(track) artistPath = os.path.join(self.workingDir, track.artistName) albumPath = os.path.join(artistPath, track.albumTitle) recordPath = os.path.join(albumPath, track.title) + ".rec" localFilePath = os.path.join(recordPath, "muzak.yturl") fileToWrite = open(localFilePath, 'w+') fileToWrite.write(track.url) fileToWrite.close() return track
05f220d6090be58ee465b6f30d01e14079bcbeba
corehq/messaging/scheduling/scheduling_partitioned/dbaccessors.py
corehq/messaging/scheduling/scheduling_partitioned/dbaccessors.py
def save_schedule_instance(instance): instance.save()
from corehq.sql_db.util import ( get_object_from_partitioned_database, save_object_to_partitioned_database, run_query_across_partitioned_databases, ) from datetime import datetime from django.db.models import Q def get_schedule_instance(schedule_instance_id): from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance return get_object_from_partitioned_database(ScheduleInstance, str(schedule_instance_id)) def save_schedule_instance(instance): from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance if not isinstance(instance, ScheduleInstance): raise ValueError("Expected an instance of ScheduleInstance") save_object_to_partitioned_database(instance, str(instance.pk)) def delete_schedule_instance(instance): from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance if not isinstance(instance, ScheduleInstance): raise ValueError("Expected an instance of ScheduleInstance") delete_object_from_partitioned_database(instance, str(instance.pk)) def get_active_schedule_instance_ids(start_timestamp, end_timestamp): from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance q_expression = Q( active=True, next_event_due__gt=start_timestamp, next_event_due__lte=end_timestamp, ) for schedule_instance_id in run_query_across_partitioned_databases( ScheduleInstance, q_expression, values=['schedule_instance_id'] ): yield schedule_instance_id
Add functions for processing ScheduleInstances
Add functions for processing ScheduleInstances
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
+ from corehq.sql_db.util import ( + get_object_from_partitioned_database, + save_object_to_partitioned_database, + run_query_across_partitioned_databases, + ) + from datetime import datetime + from django.db.models import Q + + + def get_schedule_instance(schedule_instance_id): + from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance + + return get_object_from_partitioned_database(ScheduleInstance, str(schedule_instance_id)) def save_schedule_instance(instance): - instance.save() + from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance + if not isinstance(instance, ScheduleInstance): + raise ValueError("Expected an instance of ScheduleInstance") + + save_object_to_partitioned_database(instance, str(instance.pk)) + + + def delete_schedule_instance(instance): + from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance + + if not isinstance(instance, ScheduleInstance): + raise ValueError("Expected an instance of ScheduleInstance") + + delete_object_from_partitioned_database(instance, str(instance.pk)) + + + def get_active_schedule_instance_ids(start_timestamp, end_timestamp): + from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance + + q_expression = Q( + active=True, + next_event_due__gt=start_timestamp, + next_event_due__lte=end_timestamp, + ) + for schedule_instance_id in run_query_across_partitioned_databases( + ScheduleInstance, + q_expression, + values=['schedule_instance_id'] + ): + yield schedule_instance_id +
Add functions for processing ScheduleInstances
## Code Before: def save_schedule_instance(instance): instance.save() ## Instruction: Add functions for processing ScheduleInstances ## Code After: from corehq.sql_db.util import ( get_object_from_partitioned_database, save_object_to_partitioned_database, run_query_across_partitioned_databases, ) from datetime import datetime from django.db.models import Q def get_schedule_instance(schedule_instance_id): from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance return get_object_from_partitioned_database(ScheduleInstance, str(schedule_instance_id)) def save_schedule_instance(instance): from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance if not isinstance(instance, ScheduleInstance): raise ValueError("Expected an instance of ScheduleInstance") save_object_to_partitioned_database(instance, str(instance.pk)) def delete_schedule_instance(instance): from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance if not isinstance(instance, ScheduleInstance): raise ValueError("Expected an instance of ScheduleInstance") delete_object_from_partitioned_database(instance, str(instance.pk)) def get_active_schedule_instance_ids(start_timestamp, end_timestamp): from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance q_expression = Q( active=True, next_event_due__gt=start_timestamp, next_event_due__lte=end_timestamp, ) for schedule_instance_id in run_query_across_partitioned_databases( ScheduleInstance, q_expression, values=['schedule_instance_id'] ): yield schedule_instance_id
+ from corehq.sql_db.util import ( + get_object_from_partitioned_database, + save_object_to_partitioned_database, + run_query_across_partitioned_databases, + ) + from datetime import datetime + from django.db.models import Q + + + def get_schedule_instance(schedule_instance_id): + from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance + + return get_object_from_partitioned_database(ScheduleInstance, str(schedule_instance_id)) def save_schedule_instance(instance): - instance.save() + from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance + + if not isinstance(instance, ScheduleInstance): + raise ValueError("Expected an instance of ScheduleInstance") + + save_object_to_partitioned_database(instance, str(instance.pk)) + + + def delete_schedule_instance(instance): + from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance + + if not isinstance(instance, ScheduleInstance): + raise ValueError("Expected an instance of ScheduleInstance") + + delete_object_from_partitioned_database(instance, str(instance.pk)) + + + def get_active_schedule_instance_ids(start_timestamp, end_timestamp): + from corehq.messaging.scheduling.scheduling_partitioned.models import ScheduleInstance + + q_expression = Q( + active=True, + next_event_due__gt=start_timestamp, + next_event_due__lte=end_timestamp, + ) + for schedule_instance_id in run_query_across_partitioned_databases( + ScheduleInstance, + q_expression, + values=['schedule_instance_id'] + ): + yield schedule_instance_id
e2ce9ad697cd686e91b546f6f3aa7b24b5e9266f
masters/master.tryserver.chromium.angle/master_site_config.py
masters/master.tryserver.chromium.angle/master_site_config.py
"""ActiveMaster definition.""" from config_bootstrap import Master class TryServerANGLE(Master.Master4a): project_name = 'ANGLE Try Server' master_port = 21403 slave_port = 31403 master_port_alt = 41403 buildbot_url = 'http://build.chromium.org/p/tryserver.chromium.angle/' gerrit_host = 'https://chromium-review.googlesource.com'
"""ActiveMaster definition.""" from config_bootstrap import Master class TryServerANGLE(Master.Master4a): project_name = 'ANGLE Try Server' master_port = 21403 slave_port = 31403 master_port_alt = 41403 buildbot_url = 'http://build.chromium.org/p/tryserver.chromium.angle/' gerrit_host = 'https://chromium-review.googlesource.com' service_account_file = 'service-account-chromium-tryserver.json' buildbucket_bucket = 'master.tryserver.chromium.linux'
Add buildbucket service account to Angle master.
Add buildbucket service account to Angle master. BUG=577560 TBR=nodir@chromium.org Review URL: https://codereview.chromium.org/1624703003 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@298368 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
"""ActiveMaster definition.""" from config_bootstrap import Master class TryServerANGLE(Master.Master4a): project_name = 'ANGLE Try Server' master_port = 21403 slave_port = 31403 master_port_alt = 41403 buildbot_url = 'http://build.chromium.org/p/tryserver.chromium.angle/' gerrit_host = 'https://chromium-review.googlesource.com' + service_account_file = 'service-account-chromium-tryserver.json' + buildbucket_bucket = 'master.tryserver.chromium.linux'
Add buildbucket service account to Angle master.
## Code Before: """ActiveMaster definition.""" from config_bootstrap import Master class TryServerANGLE(Master.Master4a): project_name = 'ANGLE Try Server' master_port = 21403 slave_port = 31403 master_port_alt = 41403 buildbot_url = 'http://build.chromium.org/p/tryserver.chromium.angle/' gerrit_host = 'https://chromium-review.googlesource.com' ## Instruction: Add buildbucket service account to Angle master. ## Code After: """ActiveMaster definition.""" from config_bootstrap import Master class TryServerANGLE(Master.Master4a): project_name = 'ANGLE Try Server' master_port = 21403 slave_port = 31403 master_port_alt = 41403 buildbot_url = 'http://build.chromium.org/p/tryserver.chromium.angle/' gerrit_host = 'https://chromium-review.googlesource.com' service_account_file = 'service-account-chromium-tryserver.json' buildbucket_bucket = 'master.tryserver.chromium.linux'
"""ActiveMaster definition.""" from config_bootstrap import Master class TryServerANGLE(Master.Master4a): project_name = 'ANGLE Try Server' master_port = 21403 slave_port = 31403 master_port_alt = 41403 buildbot_url = 'http://build.chromium.org/p/tryserver.chromium.angle/' gerrit_host = 'https://chromium-review.googlesource.com' + service_account_file = 'service-account-chromium-tryserver.json' + buildbucket_bucket = 'master.tryserver.chromium.linux'
1a511f23acc873c95ed60e8a918bff5c6ba68ebc
deployment/websocket_wsgi.py
deployment/websocket_wsgi.py
import os import gevent.socket import redis.connection from manage import _set_source_root_parent, _set_source_root os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") _set_source_root_parent('submodules') _set_source_root(os.path.join('corehq', 'ex-submodules')) _set_source_root(os.path.join('custom', '_legacy')) redis.connection.socket = gevent.socket from ws4redis.uwsgi_runserver import uWSGIWebsocketServer application = uWSGIWebsocketServer()
import os import gevent.socket import redis.connection from manage import init_hq_python_path, run_patches os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") init_hq_python_path() run_patches() redis.connection.socket = gevent.socket from ws4redis.uwsgi_runserver import uWSGIWebsocketServer application = uWSGIWebsocketServer()
Fix websockets process after celery upgrade
Fix websockets process after celery upgrade make it do the same patching that manage.py does
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
import os import gevent.socket import redis.connection - from manage import _set_source_root_parent, _set_source_root + from manage import init_hq_python_path, run_patches os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") + init_hq_python_path() + run_patches() - _set_source_root_parent('submodules') - _set_source_root(os.path.join('corehq', 'ex-submodules')) - _set_source_root(os.path.join('custom', '_legacy')) redis.connection.socket = gevent.socket from ws4redis.uwsgi_runserver import uWSGIWebsocketServer application = uWSGIWebsocketServer()
Fix websockets process after celery upgrade
## Code Before: import os import gevent.socket import redis.connection from manage import _set_source_root_parent, _set_source_root os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") _set_source_root_parent('submodules') _set_source_root(os.path.join('corehq', 'ex-submodules')) _set_source_root(os.path.join('custom', '_legacy')) redis.connection.socket = gevent.socket from ws4redis.uwsgi_runserver import uWSGIWebsocketServer application = uWSGIWebsocketServer() ## Instruction: Fix websockets process after celery upgrade ## Code After: import os import gevent.socket import redis.connection from manage import init_hq_python_path, run_patches os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") init_hq_python_path() run_patches() redis.connection.socket = gevent.socket from ws4redis.uwsgi_runserver import uWSGIWebsocketServer application = uWSGIWebsocketServer()
import os import gevent.socket import redis.connection - from manage import _set_source_root_parent, _set_source_root + from manage import init_hq_python_path, run_patches os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") + init_hq_python_path() + run_patches() - _set_source_root_parent('submodules') - _set_source_root(os.path.join('corehq', 'ex-submodules')) - _set_source_root(os.path.join('custom', '_legacy')) redis.connection.socket = gevent.socket from ws4redis.uwsgi_runserver import uWSGIWebsocketServer application = uWSGIWebsocketServer()
7801c5d7430233eb78ab8b2a91f5960bd808b2c7
app/admin/views.py
app/admin/views.py
from flask import Blueprint, render_template from flask_security import login_required admin = Blueprint('admin', __name__) @admin.route('/') @admin.route('/index') @login_required def index(): return render_template('admin/index.html', title='Admin')
from flask import Blueprint, render_template, redirect, url_for from flask_security import current_user admin = Blueprint('admin', __name__) @admin.route('/') @admin.route('/index') def index(): return render_template('admin/index.html', title='Admin') @admin.before_request def require_login(): if not current_user.is_authenticated: return redirect(url_for('security.login', next='admin'))
Move admin authentication into before_request handler
Move admin authentication into before_request handler
Python
mit
Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger
- from flask import Blueprint, render_template + from flask import Blueprint, render_template, redirect, url_for - from flask_security import login_required + from flask_security import current_user admin = Blueprint('admin', __name__) @admin.route('/') @admin.route('/index') - @login_required def index(): return render_template('admin/index.html', title='Admin') + + @admin.before_request + def require_login(): + if not current_user.is_authenticated: + return redirect(url_for('security.login', next='admin')) +
Move admin authentication into before_request handler
## Code Before: from flask import Blueprint, render_template from flask_security import login_required admin = Blueprint('admin', __name__) @admin.route('/') @admin.route('/index') @login_required def index(): return render_template('admin/index.html', title='Admin') ## Instruction: Move admin authentication into before_request handler ## Code After: from flask import Blueprint, render_template, redirect, url_for from flask_security import current_user admin = Blueprint('admin', __name__) @admin.route('/') @admin.route('/index') def index(): return render_template('admin/index.html', title='Admin') @admin.before_request def require_login(): if not current_user.is_authenticated: return redirect(url_for('security.login', next='admin'))
- from flask import Blueprint, render_template + from flask import Blueprint, render_template, redirect, url_for ? +++++++++++++++++++ - from flask_security import login_required ? ^^^^^^ ^ ^ -- + from flask_security import current_user ? ^^^ ^^^ ^^ admin = Blueprint('admin', __name__) @admin.route('/') @admin.route('/index') - @login_required def index(): return render_template('admin/index.html', title='Admin') + + + @admin.before_request + def require_login(): + if not current_user.is_authenticated: + return redirect(url_for('security.login', next='admin'))
3a5a6db3b869841cf5c55eed2f5ec877a443a571
chrome/test/functional/chromeos_html_terminal.py
chrome/test/functional/chromeos_html_terminal.py
import os import pyauto_functional # must be imported before pyauto import pyauto class ChromeosHTMLTerminalTest(pyauto.PyUITest): """Basic tests for ChromeOS HTML Terminal. Requires ChromeOS to be logged in. """ def _GetExtensionInfoById(self, extensions, id): for x in extensions: if x['id'] == id: return x return None def testInstallHTMLTerminal(self): """Basic installation test for HTML Terminal on ChromeOS.""" crx_file_path = os.path.abspath( os.path.join(self.DataDir(), 'pyauto_private', 'apps', 'SecureShell-dev-0.7.9.3.crx')) ext_id = self.InstallExtension(crx_file_path) self.assertTrue(ext_id, 'Failed to install extension.') extension = self._GetExtensionInfoById(self.GetExtensionsInfo(), ext_id) self.assertTrue(extension['is_enabled'], msg='Extension was not enabled on installation.') self.assertFalse(extension['allowed_in_incognito'], msg='Extension was allowed in incognito on installation.') if __name__ == '__main__': pyauto_functional.Main()
import os import pyauto_functional # must be imported before pyauto import pyauto class ChromeosHTMLTerminalTest(pyauto.PyUITest): """Basic tests for ChromeOS HTML Terminal. Requires ChromeOS to be logged in. """ def _GetExtensionInfoById(self, extensions, id): for x in extensions: if x['id'] == id: return x return None def testInstallAndUninstallSecureShellExt(self): """Basic installation test for HTML Terminal on ChromeOS.""" crx_file_path = os.path.abspath( os.path.join(self.DataDir(), 'pyauto_private', 'apps', 'SecureShell-dev-0.7.9.3.crx')) ext_id = self.InstallExtension(crx_file_path) self.assertTrue(ext_id, 'Failed to install extension.') extension = self._GetExtensionInfoById(self.GetExtensionsInfo(), ext_id) self.assertTrue(extension['is_enabled'], msg='Extension was not enabled on installation.') self.assertFalse(extension['allowed_in_incognito'], msg='Extension was allowed in incognito on installation.') # Uninstall HTML Terminal extension self.assertTrue(self.UninstallExtensionById(ext_id), msg='Failed to uninstall extension.') if __name__ == '__main__': pyauto_functional.Main()
Add uninstall HTML Terminal extension
Add uninstall HTML Terminal extension BUG= TEST=This is a test to uninstall HTML terminal extension Review URL: https://chromiumcodereview.appspot.com/10332227 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@137790 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
hgl888/chromium-crosswalk,markYoungH/chromium.src,hujiajie/pa-chromium,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,Chilledheart/chromium,timopulkkinen/BubbleFish,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,littlstar/chromium.src,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,hujiajie/pa-chromium,chuan9/chromium-crosswalk,anirudhSK/chromium,markYoungH/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,jaruba/chromium.src,anirudhSK/chromium,keishi/chromium,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,jaruba/chromium.src,dednal/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,Chilledheart/chromium,keishi/chromium,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,axinging/chromium-crosswalk,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,littlstar/chromium.src,keishi/chromium,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,dednal/chromium.src,hujiajie/pa-chromium,ltilve/chromium,ChromiumWebApps/chromium,hujiajie/pa-chromium,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,littlstar/chromium.src,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,ltilve/chromium,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,dednal/chromium.src,Jonekee/chromium.src,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,ondra-novak/chromium.src,zcbenz/cefode-chromium,Chilledheart/chromium,Fireblend/chromium-crosswalk,jaruba/chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,M4sse/chromium.src,Jonekee/chromium.src,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,mogoweb/chromium-crosswalk,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,jaruba/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,dednal/chromium.src,patrickm/chromium.src,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,littlstar/chromium.src,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,ondra-novak/chromium.src,Chilledheart/chromium,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,dushu1203/chromium.src,Just-D/chromium-1,jaruba/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,keishi/chromium,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,Just-D/chromium-1,ltilve/chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,keishi/chromium,PeterWangIntel/chromium-crosswalk,keishi/chromium,jaruba/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,M4sse/chromium.src,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,Just-D/chromium-1,dednal/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,dushu1203/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,keishi/chromium,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,dednal/chromium.src,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,ltilve/chromium,patrickm/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,keishi/chromium,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,hujiajie/pa-chromium,ltilve/chromium,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,keishi/chromium,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,keishi/chromium,anirudhSK/chromium,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,hujiajie/pa-chromium,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,Chilledheart/chromium,nacl-webkit/chrome_deps,keishi/chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk
import os import pyauto_functional # must be imported before pyauto import pyauto class ChromeosHTMLTerminalTest(pyauto.PyUITest): """Basic tests for ChromeOS HTML Terminal. Requires ChromeOS to be logged in. """ def _GetExtensionInfoById(self, extensions, id): for x in extensions: if x['id'] == id: return x return None - def testInstallHTMLTerminal(self): + def testInstallAndUninstallSecureShellExt(self): """Basic installation test for HTML Terminal on ChromeOS.""" crx_file_path = os.path.abspath( os.path.join(self.DataDir(), 'pyauto_private', 'apps', 'SecureShell-dev-0.7.9.3.crx')) ext_id = self.InstallExtension(crx_file_path) self.assertTrue(ext_id, 'Failed to install extension.') extension = self._GetExtensionInfoById(self.GetExtensionsInfo(), ext_id) self.assertTrue(extension['is_enabled'], msg='Extension was not enabled on installation.') self.assertFalse(extension['allowed_in_incognito'], msg='Extension was allowed in incognito on installation.') + # Uninstall HTML Terminal extension + self.assertTrue(self.UninstallExtensionById(ext_id), + msg='Failed to uninstall extension.') if __name__ == '__main__': pyauto_functional.Main()
Add uninstall HTML Terminal extension
## Code Before: import os import pyauto_functional # must be imported before pyauto import pyauto class ChromeosHTMLTerminalTest(pyauto.PyUITest): """Basic tests for ChromeOS HTML Terminal. Requires ChromeOS to be logged in. """ def _GetExtensionInfoById(self, extensions, id): for x in extensions: if x['id'] == id: return x return None def testInstallHTMLTerminal(self): """Basic installation test for HTML Terminal on ChromeOS.""" crx_file_path = os.path.abspath( os.path.join(self.DataDir(), 'pyauto_private', 'apps', 'SecureShell-dev-0.7.9.3.crx')) ext_id = self.InstallExtension(crx_file_path) self.assertTrue(ext_id, 'Failed to install extension.') extension = self._GetExtensionInfoById(self.GetExtensionsInfo(), ext_id) self.assertTrue(extension['is_enabled'], msg='Extension was not enabled on installation.') self.assertFalse(extension['allowed_in_incognito'], msg='Extension was allowed in incognito on installation.') if __name__ == '__main__': pyauto_functional.Main() ## Instruction: Add uninstall HTML Terminal extension ## Code After: import os import pyauto_functional # must be imported before pyauto import pyauto class ChromeosHTMLTerminalTest(pyauto.PyUITest): """Basic tests for ChromeOS HTML Terminal. Requires ChromeOS to be logged in. """ def _GetExtensionInfoById(self, extensions, id): for x in extensions: if x['id'] == id: return x return None def testInstallAndUninstallSecureShellExt(self): """Basic installation test for HTML Terminal on ChromeOS.""" crx_file_path = os.path.abspath( os.path.join(self.DataDir(), 'pyauto_private', 'apps', 'SecureShell-dev-0.7.9.3.crx')) ext_id = self.InstallExtension(crx_file_path) self.assertTrue(ext_id, 'Failed to install extension.') extension = self._GetExtensionInfoById(self.GetExtensionsInfo(), ext_id) self.assertTrue(extension['is_enabled'], msg='Extension was not enabled on installation.') self.assertFalse(extension['allowed_in_incognito'], msg='Extension was allowed in incognito on installation.') # Uninstall HTML Terminal extension self.assertTrue(self.UninstallExtensionById(ext_id), msg='Failed to uninstall extension.') if __name__ == '__main__': pyauto_functional.Main()
import os import pyauto_functional # must be imported before pyauto import pyauto class ChromeosHTMLTerminalTest(pyauto.PyUITest): """Basic tests for ChromeOS HTML Terminal. Requires ChromeOS to be logged in. """ def _GetExtensionInfoById(self, extensions, id): for x in extensions: if x['id'] == id: return x return None - def testInstallHTMLTerminal(self): + def testInstallAndUninstallSecureShellExt(self): """Basic installation test for HTML Terminal on ChromeOS.""" crx_file_path = os.path.abspath( os.path.join(self.DataDir(), 'pyauto_private', 'apps', 'SecureShell-dev-0.7.9.3.crx')) ext_id = self.InstallExtension(crx_file_path) self.assertTrue(ext_id, 'Failed to install extension.') extension = self._GetExtensionInfoById(self.GetExtensionsInfo(), ext_id) self.assertTrue(extension['is_enabled'], msg='Extension was not enabled on installation.') self.assertFalse(extension['allowed_in_incognito'], msg='Extension was allowed in incognito on installation.') + # Uninstall HTML Terminal extension + self.assertTrue(self.UninstallExtensionById(ext_id), + msg='Failed to uninstall extension.') if __name__ == '__main__': pyauto_functional.Main()
b6afc5f1db5c416fde43567623161bbe2244897b
docs/conf.py
docs/conf.py
project = "dependencies" copyright = "2016-2018, Artem Malyshev" author = "Artem Malyshev" version = "0.15" release = "0.15" templates_path = ["templates"] source_suffix = ".rst" master_doc = "index" language = None exclude_patterns = ["_build"] pygments_style = "sphinx" html_theme = "alabaster" html_static_path = ["static"] html_sidebars = { "**": [ "sidebarlogo.html", "stats.html", "globaltoc.html", "relations.html", "updates.html", "links.html", "searchbox.html", "gitter_sidecar.html", ] } html_theme_options = { "show_powered_by": False, "show_related": True, "description": "Dependency Injection for Humans. It provides a simple low-impact implementation of an IoC container and resolution support for your classes.", "github_user": "dry-python", "github_repo": "dependencies", "github_type": "star", "github_count": True, "github_banner": True, }
project = "dependencies" copyright = "2016-2018, Artem Malyshev" author = "Artem Malyshev" version = "0.15" release = "0.15" templates_path = ["templates"] source_suffix = ".rst" master_doc = "index" language = None exclude_patterns = ["_build"] pygments_style = "sphinx" html_theme = "alabaster" html_static_path = ["static"] html_sidebars = { "**": [ "sidebarlogo.html", "stats.html", "globaltoc.html", "relations.html", "updates.html", "links.html", "searchbox.html", "gitter_sidecar.html", ] } html_theme_options = { "show_powered_by": False, "show_related": True, "show_relbars": True, "description": "Dependency Injection for Humans. It provides a simple low-impact implementation of an IoC container and resolution support for your classes.", "github_user": "dry-python", "github_repo": "dependencies", "github_type": "star", "github_count": True, "github_banner": True, }
Add Next/Previous page links to the docs.
Add Next/Previous page links to the docs.
Python
bsd-2-clause
proofit404/dependencies,proofit404/dependencies,proofit404/dependencies,proofit404/dependencies
project = "dependencies" copyright = "2016-2018, Artem Malyshev" author = "Artem Malyshev" version = "0.15" release = "0.15" templates_path = ["templates"] source_suffix = ".rst" master_doc = "index" language = None exclude_patterns = ["_build"] pygments_style = "sphinx" html_theme = "alabaster" html_static_path = ["static"] html_sidebars = { "**": [ "sidebarlogo.html", "stats.html", "globaltoc.html", "relations.html", "updates.html", "links.html", "searchbox.html", "gitter_sidecar.html", ] } html_theme_options = { "show_powered_by": False, "show_related": True, + "show_relbars": True, "description": "Dependency Injection for Humans. It provides a simple low-impact implementation of an IoC container and resolution support for your classes.", "github_user": "dry-python", "github_repo": "dependencies", "github_type": "star", "github_count": True, "github_banner": True, }
Add Next/Previous page links to the docs.
## Code Before: project = "dependencies" copyright = "2016-2018, Artem Malyshev" author = "Artem Malyshev" version = "0.15" release = "0.15" templates_path = ["templates"] source_suffix = ".rst" master_doc = "index" language = None exclude_patterns = ["_build"] pygments_style = "sphinx" html_theme = "alabaster" html_static_path = ["static"] html_sidebars = { "**": [ "sidebarlogo.html", "stats.html", "globaltoc.html", "relations.html", "updates.html", "links.html", "searchbox.html", "gitter_sidecar.html", ] } html_theme_options = { "show_powered_by": False, "show_related": True, "description": "Dependency Injection for Humans. It provides a simple low-impact implementation of an IoC container and resolution support for your classes.", "github_user": "dry-python", "github_repo": "dependencies", "github_type": "star", "github_count": True, "github_banner": True, } ## Instruction: Add Next/Previous page links to the docs. ## Code After: project = "dependencies" copyright = "2016-2018, Artem Malyshev" author = "Artem Malyshev" version = "0.15" release = "0.15" templates_path = ["templates"] source_suffix = ".rst" master_doc = "index" language = None exclude_patterns = ["_build"] pygments_style = "sphinx" html_theme = "alabaster" html_static_path = ["static"] html_sidebars = { "**": [ "sidebarlogo.html", "stats.html", "globaltoc.html", "relations.html", "updates.html", "links.html", "searchbox.html", "gitter_sidecar.html", ] } html_theme_options = { "show_powered_by": False, "show_related": True, "show_relbars": True, "description": "Dependency Injection for Humans. It provides a simple low-impact implementation of an IoC container and resolution support for your classes.", "github_user": "dry-python", "github_repo": "dependencies", "github_type": "star", "github_count": True, "github_banner": True, }
project = "dependencies" copyright = "2016-2018, Artem Malyshev" author = "Artem Malyshev" version = "0.15" release = "0.15" templates_path = ["templates"] source_suffix = ".rst" master_doc = "index" language = None exclude_patterns = ["_build"] pygments_style = "sphinx" html_theme = "alabaster" html_static_path = ["static"] html_sidebars = { "**": [ "sidebarlogo.html", "stats.html", "globaltoc.html", "relations.html", "updates.html", "links.html", "searchbox.html", "gitter_sidecar.html", ] } html_theme_options = { "show_powered_by": False, "show_related": True, + "show_relbars": True, "description": "Dependency Injection for Humans. It provides a simple low-impact implementation of an IoC container and resolution support for your classes.", "github_user": "dry-python", "github_repo": "dependencies", "github_type": "star", "github_count": True, "github_banner": True, }
f845fcfc145edd2ef55df3275971f5c940a61bb4
tests/list_match.py
tests/list_match.py
from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = Cons(1, Cons(2, Cons(3, Nil))) b = match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), ("_", lambda: 4)) assert b == 2, "List pattern match" return 0
from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = hint(Cons(1, Cons(2, Cons(3, Nil))), a='int') #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), # ("_", lambda: 4)), a='int') #assert b == 2, "List pattern match" return 0
Disable match() test for now
Disable match() test for now
Python
mit
pshc/archipelago,pshc/archipelago,pshc/archipelago
from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') - a = Cons(1, Cons(2, Cons(3, Nil))) + a = hint(Cons(1, Cons(2, Cons(3, Nil))), a='int') - b = match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), + #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), - ("_", lambda: 4)) + # ("_", lambda: 4)), a='int') - assert b == 2, "List pattern match" + #assert b == 2, "List pattern match" return 0
Disable match() test for now
## Code Before: from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = Cons(1, Cons(2, Cons(3, Nil))) b = match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), ("_", lambda: 4)) assert b == 2, "List pattern match" return 0 ## Instruction: Disable match() test for now ## Code After: from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') a = hint(Cons(1, Cons(2, Cons(3, Nil))), a='int') #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), # ("_", lambda: 4)), a='int') #assert b == 2, "List pattern match" return 0
from bedrock import * @annot('void -> int') def main(): a = hint(Cons(0, Cons(1, Nil())), a='int') - a = Cons(1, Cons(2, Cons(3, Nil))) + a = hint(Cons(1, Cons(2, Cons(3, Nil))), a='int') ? +++++ ++++++++++ - b = match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), + #b = hint(match(a, ("Cons(_, Cons(two, Cons(_, Nil())))", identity), ? + +++++ - ("_", lambda: 4)) + # ("_", lambda: 4)), a='int') ? + ++++++++++ - assert b == 2, "List pattern match" + #assert b == 2, "List pattern match" ? + return 0
072d8fd3ccff957b427fca5e61b5a410a6762615
pulldb/publishers.py
pulldb/publishers.py
from google.appengine.ext import ndb class Publisher(ndb.Model): '''Publisher object in datastore. Holds publisher data. ''' identifier = ndb.IntegerProperty() name = ndb.StringProperty() image = ndb.StringProperty() def fetch_or_store(identifier, publisher): publisher_key = Publisher.query(Publisher.identifier==identifier).get() if not publisher_key: publisher_key = Publisher(identifier=publisher.id, name=publisher.name, image=publisher.image['tiny_url']) publisher_key.put() return publisher_key
from google.appengine.ext import ndb class Publisher(ndb.Model): '''Publisher object in datastore. Holds publisher data. ''' identifier = ndb.IntegerProperty() name = ndb.StringProperty() image = ndb.StringProperty() def fetch_or_store(identifier, publisher): publisher_key = Publisher.query(Publisher.identifier==identifier).get() if not publisher_key: publisher_key = Publisher(identifier=publisher.id, name=publisher.name) if publisher.image: publisher_key.image=publisher.image.get('tiny_url') publisher_key.put() return publisher_key
Handle null image attribute on publisher
Handle null image attribute on publisher
Python
mit
xchewtoyx/pulldb
from google.appengine.ext import ndb class Publisher(ndb.Model): '''Publisher object in datastore. Holds publisher data. ''' identifier = ndb.IntegerProperty() name = ndb.StringProperty() image = ndb.StringProperty() def fetch_or_store(identifier, publisher): publisher_key = Publisher.query(Publisher.identifier==identifier).get() if not publisher_key: - publisher_key = Publisher(identifier=publisher.id, name=publisher.name, + publisher_key = Publisher(identifier=publisher.id, name=publisher.name) - image=publisher.image['tiny_url']) + if publisher.image: + publisher_key.image=publisher.image.get('tiny_url') publisher_key.put() return publisher_key
Handle null image attribute on publisher
## Code Before: from google.appengine.ext import ndb class Publisher(ndb.Model): '''Publisher object in datastore. Holds publisher data. ''' identifier = ndb.IntegerProperty() name = ndb.StringProperty() image = ndb.StringProperty() def fetch_or_store(identifier, publisher): publisher_key = Publisher.query(Publisher.identifier==identifier).get() if not publisher_key: publisher_key = Publisher(identifier=publisher.id, name=publisher.name, image=publisher.image['tiny_url']) publisher_key.put() return publisher_key ## Instruction: Handle null image attribute on publisher ## Code After: from google.appengine.ext import ndb class Publisher(ndb.Model): '''Publisher object in datastore. Holds publisher data. ''' identifier = ndb.IntegerProperty() name = ndb.StringProperty() image = ndb.StringProperty() def fetch_or_store(identifier, publisher): publisher_key = Publisher.query(Publisher.identifier==identifier).get() if not publisher_key: publisher_key = Publisher(identifier=publisher.id, name=publisher.name) if publisher.image: publisher_key.image=publisher.image.get('tiny_url') publisher_key.put() return publisher_key
from google.appengine.ext import ndb class Publisher(ndb.Model): '''Publisher object in datastore. Holds publisher data. ''' identifier = ndb.IntegerProperty() name = ndb.StringProperty() image = ndb.StringProperty() def fetch_or_store(identifier, publisher): publisher_key = Publisher.query(Publisher.identifier==identifier).get() if not publisher_key: - publisher_key = Publisher(identifier=publisher.id, name=publisher.name, ? ^ + publisher_key = Publisher(identifier=publisher.id, name=publisher.name) ? ^ - image=publisher.image['tiny_url']) + if publisher.image: + publisher_key.image=publisher.image.get('tiny_url') publisher_key.put() return publisher_key
a0f030cd03d28d97924a3277722d7a51cf3a3e92
cms/test_utils/project/extensionapp/models.py
cms/test_utils/project/extensionapp/models.py
from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension)
from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) favorite_users = models.ManyToManyField(User, blank=True, null=True) def copy_relations(self, other, language): for favorite_user in other.favorite_users.all(): favorite_user.pk = None favorite_user.mypageextension = self favorite_user.save() extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension)
Update extension app to include a M2M
Update extension app to include a M2M
Python
bsd-3-clause
kk9599/django-cms,jrclaramunt/django-cms,farhaadila/django-cms,FinalAngel/django-cms,leture/django-cms,yakky/django-cms,wuzhihui1123/django-cms,czpython/django-cms,jproffitt/django-cms,astagi/django-cms,DylannCordel/django-cms,evildmp/django-cms,jrclaramunt/django-cms,SachaMPS/django-cms,netzkolchose/django-cms,donce/django-cms,bittner/django-cms,jeffreylu9/django-cms,cyberintruder/django-cms,takeshineshiro/django-cms,Vegasvikk/django-cms,nostalgiaz/django-cms,kk9599/django-cms,rryan/django-cms,rscnt/django-cms,SmithsonianEnterprises/django-cms,jsma/django-cms,sephii/django-cms,selecsosi/django-cms,jsma/django-cms,SmithsonianEnterprises/django-cms,donce/django-cms,sznekol/django-cms,robmagee/django-cms,rsalmaso/django-cms,Livefyre/django-cms,divio/django-cms,owers19856/django-cms,isotoma/django-cms,intip/django-cms,qnub/django-cms,divio/django-cms,farhaadila/django-cms,iddqd1/django-cms,josjevv/django-cms,stefanfoulis/django-cms,farhaadila/django-cms,SofiaReis/django-cms,wuzhihui1123/django-cms,owers19856/django-cms,MagicSolutions/django-cms,jproffitt/django-cms,FinalAngel/django-cms,benzkji/django-cms,360youlun/django-cms,bittner/django-cms,netzkolchose/django-cms,jeffreylu9/django-cms,vstoykov/django-cms,stefanw/django-cms,jeffreylu9/django-cms,chkir/django-cms,nimbis/django-cms,vxsx/django-cms,selecsosi/django-cms,chkir/django-cms,qnub/django-cms,Jaccorot/django-cms,evildmp/django-cms,bittner/django-cms,wuzhihui1123/django-cms,iddqd1/django-cms,datakortet/django-cms,Vegasvikk/django-cms,benzkji/django-cms,wyg3958/django-cms,andyzsf/django-cms,MagicSolutions/django-cms,vstoykov/django-cms,intip/django-cms,intip/django-cms,memnonila/django-cms,takeshineshiro/django-cms,philippze/django-cms,vxsx/django-cms,jproffitt/django-cms,Livefyre/django-cms,SachaMPS/django-cms,stefanfoulis/django-cms,rryan/django-cms,AlexProfi/django-cms,petecummings/django-cms,vxsx/django-cms,rscnt/django-cms,dhorelik/django-cms,rsalmaso/django-cms,Vegasvikk/django-cms,liuyisiyisi/django-cms,youprofit/django-cms,wyg3958/django-cms,FinalAngel/django-cms,sznekol/django-cms,360youlun/django-cms,jrief/django-cms,andyzsf/django-cms,stefanw/django-cms,nostalgiaz/django-cms,selecsosi/django-cms,jsma/django-cms,donce/django-cms,360youlun/django-cms,rryan/django-cms,benzkji/django-cms,petecummings/django-cms,memnonila/django-cms,DylannCordel/django-cms,intgr/django-cms,Jaccorot/django-cms,rscnt/django-cms,frnhr/django-cms,astagi/django-cms,rsalmaso/django-cms,irudayarajisawa/django-cms,andyzsf/django-cms,chmberl/django-cms,saintbird/django-cms,evildmp/django-cms,frnhr/django-cms,MagicSolutions/django-cms,evildmp/django-cms,mkoistinen/django-cms,liuyisiyisi/django-cms,datakortet/django-cms,jeffreylu9/django-cms,intip/django-cms,vad/django-cms,isotoma/django-cms,divio/django-cms,mkoistinen/django-cms,intgr/django-cms,stefanw/django-cms,AlexProfi/django-cms,rryan/django-cms,stefanfoulis/django-cms,chmberl/django-cms,dhorelik/django-cms,nimbis/django-cms,mkoistinen/django-cms,Livefyre/django-cms,jrclaramunt/django-cms,saintbird/django-cms,yakky/django-cms,datakortet/django-cms,irudayarajisawa/django-cms,vstoykov/django-cms,jsma/django-cms,irudayarajisawa/django-cms,astagi/django-cms,FinalAngel/django-cms,wyg3958/django-cms,sephii/django-cms,kk9599/django-cms,saintbird/django-cms,divio/django-cms,chmberl/django-cms,josjevv/django-cms,intgr/django-cms,jrief/django-cms,wuzhihui1123/django-cms,webu/django-cms,frnhr/django-cms,sznekol/django-cms,SofiaReis/django-cms,philippze/django-cms,czpython/django-cms,frnhr/django-cms,vxsx/django-cms,cyberintruder/django-cms,cyberintruder/django-cms,rsalmaso/django-cms,timgraham/django-cms,yakky/django-cms,isotoma/django-cms,benzkji/django-cms,Livefyre/django-cms,nimbis/django-cms,AlexProfi/django-cms,robmagee/django-cms,jrief/django-cms,ScholzVolkmer/django-cms,robmagee/django-cms,webu/django-cms,netzkolchose/django-cms,intgr/django-cms,keimlink/django-cms,memnonila/django-cms,timgraham/django-cms,yakky/django-cms,datakortet/django-cms,mkoistinen/django-cms,philippze/django-cms,youprofit/django-cms,SmithsonianEnterprises/django-cms,SofiaReis/django-cms,chkir/django-cms,vad/django-cms,ScholzVolkmer/django-cms,takeshineshiro/django-cms,DylannCordel/django-cms,jrief/django-cms,liuyisiyisi/django-cms,stefanfoulis/django-cms,czpython/django-cms,owers19856/django-cms,petecummings/django-cms,keimlink/django-cms,nimbis/django-cms,ScholzVolkmer/django-cms,selecsosi/django-cms,leture/django-cms,jproffitt/django-cms,iddqd1/django-cms,keimlink/django-cms,qnub/django-cms,timgraham/django-cms,andyzsf/django-cms,SachaMPS/django-cms,czpython/django-cms,vad/django-cms,dhorelik/django-cms,vad/django-cms,youprofit/django-cms,netzkolchose/django-cms,Jaccorot/django-cms,sephii/django-cms,bittner/django-cms,isotoma/django-cms,josjevv/django-cms,nostalgiaz/django-cms,webu/django-cms,stefanw/django-cms,nostalgiaz/django-cms,sephii/django-cms,leture/django-cms
from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool + from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) + favorite_users = models.ManyToManyField(User, blank=True, null=True) + def copy_relations(self, other, language): + for favorite_user in other.favorite_users.all(): + favorite_user.pk = None + favorite_user.mypageextension = self + favorite_user.save() extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) - extension_pool.register(MyTitleExtension)
Update extension app to include a M2M
## Code Before: from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension) ## Instruction: Update extension app to include a M2M ## Code After: from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) favorite_users = models.ManyToManyField(User, blank=True, null=True) def copy_relations(self, other, language): for favorite_user in other.favorite_users.all(): favorite_user.pk = None favorite_user.mypageextension = self favorite_user.save() extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension)
from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool + from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) + favorite_users = models.ManyToManyField(User, blank=True, null=True) + def copy_relations(self, other, language): + for favorite_user in other.favorite_users.all(): + favorite_user.pk = None + favorite_user.mypageextension = self + favorite_user.save() extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) - extension_pool.register(MyTitleExtension)
f935a14967f8b66342d34efca9ceff9eecd384be
app.py
app.py
import os from flask import Flask, render_template app = Flask(__name__) @app.route('/') def root(): genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Rap' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'House' }\ ] return render_template('index.html', genres=genres, genre=genres[0], songs=songs) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
import os from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Hip Hop' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'Electronic' }\ ] @app.route('/') def index(): return render_template('index.html', genres=genres, genre=genres[0], songs=songs) @app.route('/submit') def submit(): title = request.args.get('Song Title') artist = request.args.get('Artist') year = request.args.get('Year') genre = request.args.get('Genre') songs.append({ 'rank':str(len(songs) + 1), 'title':title, 'artist':artist, 'year':year, 'genre':genre }) return redirect(url_for('index')) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
Enable submission of new songs via form.
Enable submission of new songs via form.
Python
mit
alykhank/Tunezout,alykhank/Tunezout
import os - from flask import Flask, render_template + from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) + genres = ('Hip Hop', 'Electronic', 'R&B') + songs = [\ + { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Hip Hop' },\ + { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ + { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'Electronic' }\ + ] @app.route('/') + def index(): - def root(): - genres = ('Hip Hop', 'Electronic', 'R&B') - songs = [\ - { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Rap' },\ - { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ - { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'House' }\ - ] return render_template('index.html', genres=genres, genre=genres[0], songs=songs) + + @app.route('/submit') + def submit(): + title = request.args.get('Song Title') + artist = request.args.get('Artist') + year = request.args.get('Year') + genre = request.args.get('Genre') + songs.append({ 'rank':str(len(songs) + 1), 'title':title, 'artist':artist, 'year':year, 'genre':genre }) + return redirect(url_for('index')) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
Enable submission of new songs via form.
## Code Before: import os from flask import Flask, render_template app = Flask(__name__) @app.route('/') def root(): genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Rap' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'House' }\ ] return render_template('index.html', genres=genres, genre=genres[0], songs=songs) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) ## Instruction: Enable submission of new songs via form. ## Code After: import os from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Hip Hop' },\ { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'Electronic' }\ ] @app.route('/') def index(): return render_template('index.html', genres=genres, genre=genres[0], songs=songs) @app.route('/submit') def submit(): title = request.args.get('Song Title') artist = request.args.get('Artist') year = request.args.get('Year') genre = request.args.get('Genre') songs.append({ 'rank':str(len(songs) + 1), 'title':title, 'artist':artist, 'year':year, 'genre':genre }) return redirect(url_for('index')) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
import os - from flask import Flask, render_template + from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) + genres = ('Hip Hop', 'Electronic', 'R&B') + songs = [\ + { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Hip Hop' },\ + { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ + { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'Electronic' }\ + ] @app.route('/') + def index(): - def root(): - genres = ('Hip Hop', 'Electronic', 'R&B') - songs = [\ - { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Rap' },\ - { 'rank':'2', 'title':'Started from the Bottom', 'artist':'Drake', 'year':'2012', 'genre':'Hip Hop' },\ - { 'rank':'3', 'title':'Thrift Shop', 'artist':'Macklemore', 'year':'2013', 'genre':'House' }\ - ] return render_template('index.html', genres=genres, genre=genres[0], songs=songs) + + @app.route('/submit') + def submit(): + title = request.args.get('Song Title') + artist = request.args.get('Artist') + year = request.args.get('Year') + genre = request.args.get('Genre') + songs.append({ 'rank':str(len(songs) + 1), 'title':title, 'artist':artist, 'year':year, 'genre':genre }) + return redirect(url_for('index')) if __name__ == "__main__": # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
7a98cd1c58985da9230ba5861731b6f252d2c611
source/update.py
source/update.py
"""updates subreddit css with compiled sass""" import time import sass import praw def css() -> str: """compiles sass and returns css""" return sass.compile(filename="index.scss", output_style="compressed") def uid() -> str: """return date and time""" return "Subreddit upload on {}".format(time.strftime("%c")) def update() -> None: """main function""" reddit: praw.Reddit = praw.Reddit() reddit.subreddit("neoliberal").stylesheet.update(css(), reason=uid()) return
"""updates subreddit css with compiled sass""" import os import time from typing import List, Dict, Any, Tuple import praw import sass WebhookResponse = Dict[str, Any] # pylint: disable=C0103 def css() -> str: """compiles sass and returns css""" return sass.compile(filename="index.scss", output_style="compressed") def uid() -> str: """return date and time""" return "Subreddit upload on {}".format(time.strftime("%c")) def changed_assets(data: WebhookResponse) -> Tuple[List[str], List[str]]: """identifies changed files to upload by checking if any changed files are images""" endings: List[str] = ["png", "jpg"] head_commit: Dict[str, Any] = data["head_commit"] uploading_files: List[str] = [ file for file in (head_commit["modified"] + head_commit["added"]) for ending in endings if os.path.splitext(file)[1] == ending ] removed_files: List[str] = [ file for file in head_commit["removed"] for ending in endings if os.path.splitext(file)[1] == ending ] return (uploading_files, removed_files) def update(data: WebhookResponse) -> None: """main function""" reddit: praw.Reddit = praw.Reddit() reddit.subreddit("neoliberal").stylesheet.update(css(), reason=uid()) return
Check for changed files from webhook
Check for changed files from webhook Prevents uploading everything, only the changed assets
Python
mit
neoliberal/css-updater
"""updates subreddit css with compiled sass""" + import os import time + from typing import List, Dict, Any, Tuple + import praw import sass - import praw + + WebhookResponse = Dict[str, Any] # pylint: disable=C0103 def css() -> str: """compiles sass and returns css""" return sass.compile(filename="index.scss", output_style="compressed") def uid() -> str: """return date and time""" return "Subreddit upload on {}".format(time.strftime("%c")) - def update() -> None: + + def changed_assets(data: WebhookResponse) -> Tuple[List[str], List[str]]: + """identifies changed files to upload by checking if any changed files are images""" + endings: List[str] = ["png", "jpg"] + + head_commit: Dict[str, Any] = data["head_commit"] + + uploading_files: List[str] = [ + file for file in (head_commit["modified"] + head_commit["added"]) + for ending in endings + if os.path.splitext(file)[1] == ending + ] + removed_files: List[str] = [ + file for file in head_commit["removed"] + for ending in endings + if os.path.splitext(file)[1] == ending + ] + return (uploading_files, removed_files) + + def update(data: WebhookResponse) -> None: """main function""" reddit: praw.Reddit = praw.Reddit() reddit.subreddit("neoliberal").stylesheet.update(css(), reason=uid()) return
Check for changed files from webhook
## Code Before: """updates subreddit css with compiled sass""" import time import sass import praw def css() -> str: """compiles sass and returns css""" return sass.compile(filename="index.scss", output_style="compressed") def uid() -> str: """return date and time""" return "Subreddit upload on {}".format(time.strftime("%c")) def update() -> None: """main function""" reddit: praw.Reddit = praw.Reddit() reddit.subreddit("neoliberal").stylesheet.update(css(), reason=uid()) return ## Instruction: Check for changed files from webhook ## Code After: """updates subreddit css with compiled sass""" import os import time from typing import List, Dict, Any, Tuple import praw import sass WebhookResponse = Dict[str, Any] # pylint: disable=C0103 def css() -> str: """compiles sass and returns css""" return sass.compile(filename="index.scss", output_style="compressed") def uid() -> str: """return date and time""" return "Subreddit upload on {}".format(time.strftime("%c")) def changed_assets(data: WebhookResponse) -> Tuple[List[str], List[str]]: """identifies changed files to upload by checking if any changed files are images""" endings: List[str] = ["png", "jpg"] head_commit: Dict[str, Any] = data["head_commit"] uploading_files: List[str] = [ file for file in (head_commit["modified"] + head_commit["added"]) for ending in endings if os.path.splitext(file)[1] == ending ] removed_files: List[str] = [ file for file in head_commit["removed"] for ending in endings if os.path.splitext(file)[1] == ending ] return (uploading_files, removed_files) def update(data: WebhookResponse) -> None: """main function""" reddit: praw.Reddit = praw.Reddit() reddit.subreddit("neoliberal").stylesheet.update(css(), reason=uid()) return
"""updates subreddit css with compiled sass""" + import os import time + from typing import List, Dict, Any, Tuple + import praw import sass - import praw + + WebhookResponse = Dict[str, Any] # pylint: disable=C0103 def css() -> str: """compiles sass and returns css""" return sass.compile(filename="index.scss", output_style="compressed") def uid() -> str: """return date and time""" return "Subreddit upload on {}".format(time.strftime("%c")) - def update() -> None: + + def changed_assets(data: WebhookResponse) -> Tuple[List[str], List[str]]: + """identifies changed files to upload by checking if any changed files are images""" + endings: List[str] = ["png", "jpg"] + + head_commit: Dict[str, Any] = data["head_commit"] + + uploading_files: List[str] = [ + file for file in (head_commit["modified"] + head_commit["added"]) + for ending in endings + if os.path.splitext(file)[1] == ending + ] + removed_files: List[str] = [ + file for file in head_commit["removed"] + for ending in endings + if os.path.splitext(file)[1] == ending + ] + return (uploading_files, removed_files) + + def update(data: WebhookResponse) -> None: """main function""" reddit: praw.Reddit = praw.Reddit() reddit.subreddit("neoliberal").stylesheet.update(css(), reason=uid()) return
9d70dc1f82fb807c02f4ccfa04bef7f6da36cbc6
cluster/context_processors.py
cluster/context_processors.py
from models import Job def running_jobs(request): if request.user.is_authenticated(): temp = len(Job.get_running_jobs(user=request.user)) return {"running_jobs": temp} else: return {"running_jobs": None}
from models import Job from interface import get_all_jobs def running_jobs(request): if request.user.is_authenticated(): # hack to get numbers to update get_all_jobs(request.user) temp = len(Job.get_running_jobs(user=request.user)) return {"running_jobs": temp} else: return {"running_jobs": None}
Add a hack so that the number of jobs running will update correctly
Add a hack so that the number of jobs running will update correctly
Python
mit
crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp
from models import Job + from interface import get_all_jobs def running_jobs(request): if request.user.is_authenticated(): + # hack to get numbers to update + get_all_jobs(request.user) temp = len(Job.get_running_jobs(user=request.user)) return {"running_jobs": temp} else: return {"running_jobs": None}
Add a hack so that the number of jobs running will update correctly
## Code Before: from models import Job def running_jobs(request): if request.user.is_authenticated(): temp = len(Job.get_running_jobs(user=request.user)) return {"running_jobs": temp} else: return {"running_jobs": None} ## Instruction: Add a hack so that the number of jobs running will update correctly ## Code After: from models import Job from interface import get_all_jobs def running_jobs(request): if request.user.is_authenticated(): # hack to get numbers to update get_all_jobs(request.user) temp = len(Job.get_running_jobs(user=request.user)) return {"running_jobs": temp} else: return {"running_jobs": None}
from models import Job + from interface import get_all_jobs def running_jobs(request): if request.user.is_authenticated(): + # hack to get numbers to update + get_all_jobs(request.user) temp = len(Job.get_running_jobs(user=request.user)) return {"running_jobs": temp} else: return {"running_jobs": None}
cc8f1507c90261947d9520859922bff44ef9c6b4
observatory/lib/InheritanceQuerySet.py
observatory/lib/InheritanceQuerySet.py
from django.db.models.query import QuerySet from django.db.models.fields.related import SingleRelatedObjectDescriptor class InheritanceQuerySet(QuerySet): def select_subclasses(self, *subclasses): if not subclasses: subclasses = [o for o in dir(self.model) if isinstance(getattr(self.model, o), SingleRelatedObjectDescriptor)\ and issubclass(getattr(self.model,o).related.model, self.model)] new_qs = self.select_related(*subclasses) new_qs.subclasses = subclasses return new_qs def _clone(self, klass=None, setup=False, **kwargs): try: kwargs.update({'subclasses': self.subclasses}) except AttributeError: pass return super(InheritanceQuerySet, self)._clone(klass, setup, **kwargs) def iterator(self): iter = super(InheritanceQuerySet, self).iterator() if getattr(self, 'subclasses', False): for obj in iter: obj = [getattr(obj, s) for s in self.subclasses if getattr(obj, s)] or [obj] yield obj[0] else: for obj in iter: yield obj
from django.db.models.query import QuerySet from django.db.models.fields.related import SingleRelatedObjectDescriptor from django.core.exceptions import ObjectDoesNotExist class InheritanceQuerySet(QuerySet): def select_subclasses(self, *subclasses): if not subclasses: subclasses = [o for o in dir(self.model) if isinstance(getattr(self.model, o), SingleRelatedObjectDescriptor)\ and issubclass(getattr(self.model,o).related.model, self.model)] new_qs = self.select_related(*subclasses) new_qs.subclasses = subclasses return new_qs def _clone(self, klass=None, setup=False, **kwargs): try: kwargs.update({'subclasses': self.subclasses}) except AttributeError: pass return super(InheritanceQuerySet, self)._clone(klass, setup, **kwargs) def _get_subclasses(self, obj): result = [] for s in getattr(self, 'subclassses', []): try: if getattr(obj, s): result += getattr(obj, s) except ObjectDoesNotExist: continue return result or [obj] def iterator(self): iter = super(InheritanceQuerySet, self).iterator() if getattr(self, 'subclasses', False): for obj in iter: yield self._get_subclasses(obj)[0] else: for obj in iter: yield obj
Fix the feed to work with new versions of django
Fix the feed to work with new versions of django
Python
isc
rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory
from django.db.models.query import QuerySet from django.db.models.fields.related import SingleRelatedObjectDescriptor + from django.core.exceptions import ObjectDoesNotExist class InheritanceQuerySet(QuerySet): def select_subclasses(self, *subclasses): if not subclasses: subclasses = [o for o in dir(self.model) if isinstance(getattr(self.model, o), SingleRelatedObjectDescriptor)\ and issubclass(getattr(self.model,o).related.model, self.model)] new_qs = self.select_related(*subclasses) new_qs.subclasses = subclasses return new_qs def _clone(self, klass=None, setup=False, **kwargs): try: kwargs.update({'subclasses': self.subclasses}) except AttributeError: pass return super(InheritanceQuerySet, self)._clone(klass, setup, **kwargs) + def _get_subclasses(self, obj): + result = [] + for s in getattr(self, 'subclassses', []): + try: + if getattr(obj, s): + result += getattr(obj, s) + except ObjectDoesNotExist: + continue + return result or [obj] + + def iterator(self): iter = super(InheritanceQuerySet, self).iterator() if getattr(self, 'subclasses', False): for obj in iter: + yield self._get_subclasses(obj)[0] - obj = [getattr(obj, s) for s in self.subclasses if getattr(obj, s)] or [obj] - yield obj[0] else: for obj in iter: yield obj
Fix the feed to work with new versions of django
## Code Before: from django.db.models.query import QuerySet from django.db.models.fields.related import SingleRelatedObjectDescriptor class InheritanceQuerySet(QuerySet): def select_subclasses(self, *subclasses): if not subclasses: subclasses = [o for o in dir(self.model) if isinstance(getattr(self.model, o), SingleRelatedObjectDescriptor)\ and issubclass(getattr(self.model,o).related.model, self.model)] new_qs = self.select_related(*subclasses) new_qs.subclasses = subclasses return new_qs def _clone(self, klass=None, setup=False, **kwargs): try: kwargs.update({'subclasses': self.subclasses}) except AttributeError: pass return super(InheritanceQuerySet, self)._clone(klass, setup, **kwargs) def iterator(self): iter = super(InheritanceQuerySet, self).iterator() if getattr(self, 'subclasses', False): for obj in iter: obj = [getattr(obj, s) for s in self.subclasses if getattr(obj, s)] or [obj] yield obj[0] else: for obj in iter: yield obj ## Instruction: Fix the feed to work with new versions of django ## Code After: from django.db.models.query import QuerySet from django.db.models.fields.related import SingleRelatedObjectDescriptor from django.core.exceptions import ObjectDoesNotExist class InheritanceQuerySet(QuerySet): def select_subclasses(self, *subclasses): if not subclasses: subclasses = [o for o in dir(self.model) if isinstance(getattr(self.model, o), SingleRelatedObjectDescriptor)\ and issubclass(getattr(self.model,o).related.model, self.model)] new_qs = self.select_related(*subclasses) new_qs.subclasses = subclasses return new_qs def _clone(self, klass=None, setup=False, **kwargs): try: kwargs.update({'subclasses': self.subclasses}) except AttributeError: pass return super(InheritanceQuerySet, self)._clone(klass, setup, **kwargs) def _get_subclasses(self, obj): result = [] for s in getattr(self, 'subclassses', []): try: if getattr(obj, s): result += getattr(obj, s) except ObjectDoesNotExist: continue return result or [obj] def iterator(self): iter = super(InheritanceQuerySet, self).iterator() if getattr(self, 'subclasses', False): for obj in iter: yield self._get_subclasses(obj)[0] else: for obj in iter: yield obj
from django.db.models.query import QuerySet from django.db.models.fields.related import SingleRelatedObjectDescriptor + from django.core.exceptions import ObjectDoesNotExist class InheritanceQuerySet(QuerySet): def select_subclasses(self, *subclasses): if not subclasses: subclasses = [o for o in dir(self.model) if isinstance(getattr(self.model, o), SingleRelatedObjectDescriptor)\ and issubclass(getattr(self.model,o).related.model, self.model)] new_qs = self.select_related(*subclasses) new_qs.subclasses = subclasses return new_qs def _clone(self, klass=None, setup=False, **kwargs): try: kwargs.update({'subclasses': self.subclasses}) except AttributeError: pass return super(InheritanceQuerySet, self)._clone(klass, setup, **kwargs) + def _get_subclasses(self, obj): + result = [] + for s in getattr(self, 'subclassses', []): + try: + if getattr(obj, s): + result += getattr(obj, s) + except ObjectDoesNotExist: + continue + return result or [obj] + + def iterator(self): iter = super(InheritanceQuerySet, self).iterator() if getattr(self, 'subclasses', False): for obj in iter: + yield self._get_subclasses(obj)[0] - obj = [getattr(obj, s) for s in self.subclasses if getattr(obj, s)] or [obj] - yield obj[0] else: for obj in iter: yield obj
3dc06581d07a204a3044e3a78deb84950a6ebf74
mtp_transaction_uploader/api_client.py
mtp_transaction_uploader/api_client.py
from urllib.parse import urljoin from oauthlib.oauth2 import LegacyApplicationClient from requests_oauthlib import OAuth2Session import slumber from . import settings REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/') def get_authenticated_connection(): """ Returns: an authenticated slumber connection """ session = OAuth2Session( client=LegacyApplicationClient( client_id=settings.API_CLIENT_ID ) ) session.fetch_token( token_url=REQUEST_TOKEN_URL, username=settings.API_USERNAME, password=settings.API_PASSWORD, client_id=settings.API_CLIENT_ID, client_secret=settings.API_CLIENT_SECRET ) return slumber.API( base_url=settings.API_URL, session=session )
from urllib.parse import urljoin from oauthlib.oauth2 import LegacyApplicationClient from requests.auth import HTTPBasicAuth from requests_oauthlib import OAuth2Session import slumber from . import settings REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/') def get_authenticated_connection(): """ Returns: an authenticated slumber connection """ session = OAuth2Session( client=LegacyApplicationClient( client_id=settings.API_CLIENT_ID ) ) session.fetch_token( token_url=REQUEST_TOKEN_URL, username=settings.API_USERNAME, password=settings.API_PASSWORD, auth=HTTPBasicAuth(settings.API_CLIENT_ID, settings.API_CLIENT_SECRET) ) return slumber.API( base_url=settings.API_URL, session=session )
Use HTTPBasicAuth when connecting to the API
Use HTTPBasicAuth when connecting to the API
Python
mit
ministryofjustice/money-to-prisoners-transaction-uploader
from urllib.parse import urljoin from oauthlib.oauth2 import LegacyApplicationClient + from requests.auth import HTTPBasicAuth from requests_oauthlib import OAuth2Session import slumber from . import settings REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/') def get_authenticated_connection(): """ Returns: an authenticated slumber connection """ session = OAuth2Session( client=LegacyApplicationClient( client_id=settings.API_CLIENT_ID ) ) session.fetch_token( token_url=REQUEST_TOKEN_URL, username=settings.API_USERNAME, password=settings.API_PASSWORD, + auth=HTTPBasicAuth(settings.API_CLIENT_ID, settings.API_CLIENT_SECRET) - client_id=settings.API_CLIENT_ID, - client_secret=settings.API_CLIENT_SECRET ) return slumber.API( base_url=settings.API_URL, session=session )
Use HTTPBasicAuth when connecting to the API
## Code Before: from urllib.parse import urljoin from oauthlib.oauth2 import LegacyApplicationClient from requests_oauthlib import OAuth2Session import slumber from . import settings REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/') def get_authenticated_connection(): """ Returns: an authenticated slumber connection """ session = OAuth2Session( client=LegacyApplicationClient( client_id=settings.API_CLIENT_ID ) ) session.fetch_token( token_url=REQUEST_TOKEN_URL, username=settings.API_USERNAME, password=settings.API_PASSWORD, client_id=settings.API_CLIENT_ID, client_secret=settings.API_CLIENT_SECRET ) return slumber.API( base_url=settings.API_URL, session=session ) ## Instruction: Use HTTPBasicAuth when connecting to the API ## Code After: from urllib.parse import urljoin from oauthlib.oauth2 import LegacyApplicationClient from requests.auth import HTTPBasicAuth from requests_oauthlib import OAuth2Session import slumber from . import settings REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/') def get_authenticated_connection(): """ Returns: an authenticated slumber connection """ session = OAuth2Session( client=LegacyApplicationClient( client_id=settings.API_CLIENT_ID ) ) session.fetch_token( token_url=REQUEST_TOKEN_URL, username=settings.API_USERNAME, password=settings.API_PASSWORD, auth=HTTPBasicAuth(settings.API_CLIENT_ID, settings.API_CLIENT_SECRET) ) return slumber.API( base_url=settings.API_URL, session=session )
from urllib.parse import urljoin from oauthlib.oauth2 import LegacyApplicationClient + from requests.auth import HTTPBasicAuth from requests_oauthlib import OAuth2Session import slumber from . import settings REQUEST_TOKEN_URL = urljoin(settings.API_URL, '/oauth2/token/') def get_authenticated_connection(): """ Returns: an authenticated slumber connection """ session = OAuth2Session( client=LegacyApplicationClient( client_id=settings.API_CLIENT_ID ) ) session.fetch_token( token_url=REQUEST_TOKEN_URL, username=settings.API_USERNAME, password=settings.API_PASSWORD, + auth=HTTPBasicAuth(settings.API_CLIENT_ID, settings.API_CLIENT_SECRET) - client_id=settings.API_CLIENT_ID, - client_secret=settings.API_CLIENT_SECRET ) return slumber.API( base_url=settings.API_URL, session=session )
fb0eae3a9a760460f664adeef2ff71b2e8daac0f
twelve/env.py
twelve/env.py
import os import extensions class Environment(object): def __init__(self, adapter=None, environ=None, names=None, *args, **kwargs): super(Environment, self).__init__(*args, **kwargs) if names is None: names = {} self.adapter = adapter self.environ = environ self.names = names self.values = {} self._load_all() def __getattr__(self, name): return self.values.get(name) def _load_all(self): # Load Services self._load_services() def _load_services(self): for plugin in extensions.get(group="twelve.services"): service = plugin.load() value = service( self.environ if self.environ is not None else os.environ, self.names.get(plugin.name) ) if self.adapter is not None: adapters = list(extensions.get(group="twelve.adapters", name="{0}.{1}".format(self.adapter, plugin.name))) if len(adapters): adapter = adapters[0].load() value = adapter(value) self.values[plugin.name] = value
import os import extensions class Environment(object): def __init__(self, adapter=None, environ=None, names=None, *args, **kwargs): super(Environment, self).__init__(*args, **kwargs) if names is None: names = {} self.adapter = adapter self.environ = environ self.names = names self.values = {} self._load_all() def __getattr__(self, name): return self.values.get(name) def __repr__(self): return "<twelve.Environment [{0}]>".format(",".join(self.values)) def _load_all(self): # Load Services self._load_services() def _load_services(self): for plugin in extensions.get(group="twelve.services"): service = plugin.load() value = service( self.environ if self.environ is not None else os.environ, self.names.get(plugin.name) ) if self.adapter is not None: adapters = list(extensions.get(group="twelve.adapters", name="{0}.{1}".format(self.adapter, plugin.name))) if len(adapters): adapter = adapters[0].load() value = adapter(value) self.values[plugin.name] = value
Add a repr for twelve.Environment
Add a repr for twelve.Environment
Python
bsd-3-clause
dstufft/twelve
import os import extensions class Environment(object): def __init__(self, adapter=None, environ=None, names=None, *args, **kwargs): super(Environment, self).__init__(*args, **kwargs) if names is None: names = {} self.adapter = adapter self.environ = environ self.names = names self.values = {} self._load_all() def __getattr__(self, name): return self.values.get(name) + def __repr__(self): + return "<twelve.Environment [{0}]>".format(",".join(self.values)) + def _load_all(self): # Load Services self._load_services() def _load_services(self): for plugin in extensions.get(group="twelve.services"): service = plugin.load() value = service( self.environ if self.environ is not None else os.environ, self.names.get(plugin.name) ) if self.adapter is not None: adapters = list(extensions.get(group="twelve.adapters", name="{0}.{1}".format(self.adapter, plugin.name))) if len(adapters): adapter = adapters[0].load() value = adapter(value) self.values[plugin.name] = value
Add a repr for twelve.Environment
## Code Before: import os import extensions class Environment(object): def __init__(self, adapter=None, environ=None, names=None, *args, **kwargs): super(Environment, self).__init__(*args, **kwargs) if names is None: names = {} self.adapter = adapter self.environ = environ self.names = names self.values = {} self._load_all() def __getattr__(self, name): return self.values.get(name) def _load_all(self): # Load Services self._load_services() def _load_services(self): for plugin in extensions.get(group="twelve.services"): service = plugin.load() value = service( self.environ if self.environ is not None else os.environ, self.names.get(plugin.name) ) if self.adapter is not None: adapters = list(extensions.get(group="twelve.adapters", name="{0}.{1}".format(self.adapter, plugin.name))) if len(adapters): adapter = adapters[0].load() value = adapter(value) self.values[plugin.name] = value ## Instruction: Add a repr for twelve.Environment ## Code After: import os import extensions class Environment(object): def __init__(self, adapter=None, environ=None, names=None, *args, **kwargs): super(Environment, self).__init__(*args, **kwargs) if names is None: names = {} self.adapter = adapter self.environ = environ self.names = names self.values = {} self._load_all() def __getattr__(self, name): return self.values.get(name) def __repr__(self): return "<twelve.Environment [{0}]>".format(",".join(self.values)) def _load_all(self): # Load Services self._load_services() def _load_services(self): for plugin in extensions.get(group="twelve.services"): service = plugin.load() value = service( self.environ if self.environ is not None else os.environ, self.names.get(plugin.name) ) if self.adapter is not None: adapters = list(extensions.get(group="twelve.adapters", name="{0}.{1}".format(self.adapter, plugin.name))) if len(adapters): adapter = adapters[0].load() value = adapter(value) self.values[plugin.name] = value
import os import extensions class Environment(object): def __init__(self, adapter=None, environ=None, names=None, *args, **kwargs): super(Environment, self).__init__(*args, **kwargs) if names is None: names = {} self.adapter = adapter self.environ = environ self.names = names self.values = {} self._load_all() def __getattr__(self, name): return self.values.get(name) + def __repr__(self): + return "<twelve.Environment [{0}]>".format(",".join(self.values)) + def _load_all(self): # Load Services self._load_services() def _load_services(self): for plugin in extensions.get(group="twelve.services"): service = plugin.load() value = service( self.environ if self.environ is not None else os.environ, self.names.get(plugin.name) ) if self.adapter is not None: adapters = list(extensions.get(group="twelve.adapters", name="{0}.{1}".format(self.adapter, plugin.name))) if len(adapters): adapter = adapters[0].load() value = adapter(value) self.values[plugin.name] = value
5344c97e7486229f9fae40bef2b73488d5aa2ffd
uchicagohvz/users/tasks.py
uchicagohvz/users/tasks.py
from celery import task from django.conf import settings from django.core import mail import smtplib @task(rate_limit=0.2) def do_sympa_update(user, listname, subscribe): if subscribe: body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name()) else: body = "QUIET DELETE %s %s" % (listname, user.email) email = mail.EmailMessage(subject='', body=body, from_email=settings.SYMPA_FROM_EMAIL, to=[settings.SYMPA_TO_EMAIL]) email.send() @task def smtp_localhost_send(from_addr, to_addrs, msg): server = smtplib.SMTP('localhost') server.sendmail(from_addr, to_addrs, msg) server.quit()
from celery import task from django.conf import settings from django.core import mail import smtplib @task def do_sympa_update(user, listname, subscribe): if subscribe: body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name()) else: body = "QUIET DELETE %s %s" % (listname, user.email) email = mail.EmailMessage(subject='', body=body, from_email=settings.SYMPA_FROM_EMAIL, to=[settings.SYMPA_TO_EMAIL]) email.send() @task def smtp_localhost_send(from_addr, to_addrs, msg): server = smtplib.SMTP('localhost') server.sendmail(from_addr, to_addrs, msg) server.quit()
Remove rate limit from do_sympa_update
Remove rate limit from do_sympa_update
Python
mit
kz26/uchicago-hvz,kz26/uchicago-hvz,kz26/uchicago-hvz
from celery import task from django.conf import settings from django.core import mail import smtplib - @task(rate_limit=0.2) + @task def do_sympa_update(user, listname, subscribe): if subscribe: body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name()) else: body = "QUIET DELETE %s %s" % (listname, user.email) email = mail.EmailMessage(subject='', body=body, from_email=settings.SYMPA_FROM_EMAIL, to=[settings.SYMPA_TO_EMAIL]) email.send() @task def smtp_localhost_send(from_addr, to_addrs, msg): server = smtplib.SMTP('localhost') server.sendmail(from_addr, to_addrs, msg) server.quit()
Remove rate limit from do_sympa_update
## Code Before: from celery import task from django.conf import settings from django.core import mail import smtplib @task(rate_limit=0.2) def do_sympa_update(user, listname, subscribe): if subscribe: body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name()) else: body = "QUIET DELETE %s %s" % (listname, user.email) email = mail.EmailMessage(subject='', body=body, from_email=settings.SYMPA_FROM_EMAIL, to=[settings.SYMPA_TO_EMAIL]) email.send() @task def smtp_localhost_send(from_addr, to_addrs, msg): server = smtplib.SMTP('localhost') server.sendmail(from_addr, to_addrs, msg) server.quit() ## Instruction: Remove rate limit from do_sympa_update ## Code After: from celery import task from django.conf import settings from django.core import mail import smtplib @task def do_sympa_update(user, listname, subscribe): if subscribe: body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name()) else: body = "QUIET DELETE %s %s" % (listname, user.email) email = mail.EmailMessage(subject='', body=body, from_email=settings.SYMPA_FROM_EMAIL, to=[settings.SYMPA_TO_EMAIL]) email.send() @task def smtp_localhost_send(from_addr, to_addrs, msg): server = smtplib.SMTP('localhost') server.sendmail(from_addr, to_addrs, msg) server.quit()
from celery import task from django.conf import settings from django.core import mail import smtplib - @task(rate_limit=0.2) + @task def do_sympa_update(user, listname, subscribe): if subscribe: body = "QUIET ADD %s %s %s" % (listname, user.email, user.get_full_name()) else: body = "QUIET DELETE %s %s" % (listname, user.email) email = mail.EmailMessage(subject='', body=body, from_email=settings.SYMPA_FROM_EMAIL, to=[settings.SYMPA_TO_EMAIL]) email.send() @task def smtp_localhost_send(from_addr, to_addrs, msg): server = smtplib.SMTP('localhost') server.sendmail(from_addr, to_addrs, msg) server.quit()
bb6b6b46860f6e03abc4ac9c47751fe4309f0e17
md2pdf/core.py
md2pdf/core.py
from markdown2 import markdown, markdown_path from weasyprint import HTML, CSS from .exceptions import ValidationError __title__ = 'md2pdf' __version__ = '0.2.1' __author__ = 'Julien Maupetit' __license__ = 'MIT' __copyright__ = 'Copyright 2013 Julien Maupetit' def md2pdf(pdf_file_path, md_content=None, md_file_path=None, css_file_path=None): """ Convert markdown file to pdf with styles """ # Convert markdown to html raw_html = "" extras = ["cuddled-lists"] if md_file_path: raw_html = markdown_path(md_file_path, extras=extras) elif md_content: raw_html = markdown(md_content, extras=extras) if not len(raw_html): raise ValidationError('Input markdown seems empty') # Weasyprint HTML object html = HTML(string=raw_html) # Get styles css = [] if css_file_path: css.append(CSS(filename=css_file_path)) # Generate PDF html.write_pdf(pdf_file_path, stylesheets=css) return
from markdown2 import markdown, markdown_path from weasyprint import HTML, CSS from .exceptions import ValidationError __title__ = 'md2pdf' __version__ = '0.2.1' __author__ = 'Julien Maupetit' __license__ = 'MIT' __copyright__ = 'Copyright 2013 Julien Maupetit' def md2pdf(pdf_file_path, md_content=None, md_file_path=None, css_file_path=None, base_url=None): """ Convert markdown file to pdf with styles """ # Convert markdown to html raw_html = "" extras = ["cuddled-lists"] if md_file_path: raw_html = markdown_path(md_file_path, extras=extras) elif md_content: raw_html = markdown(md_content, extras=extras) if not len(raw_html): raise ValidationError('Input markdown seems empty') # Weasyprint HTML object html = HTML(string=raw_html, base_url=base_url) # Get styles css = [] if css_file_path: css.append(CSS(filename=css_file_path)) # Generate PDF html.write_pdf(pdf_file_path, stylesheets=css) return
Allow to add a base url to find media
Allow to add a base url to find media
Python
mit
jmaupetit/md2pdf
from markdown2 import markdown, markdown_path from weasyprint import HTML, CSS from .exceptions import ValidationError __title__ = 'md2pdf' __version__ = '0.2.1' __author__ = 'Julien Maupetit' __license__ = 'MIT' __copyright__ = 'Copyright 2013 Julien Maupetit' def md2pdf(pdf_file_path, md_content=None, md_file_path=None, - css_file_path=None): + css_file_path=None, base_url=None): """ Convert markdown file to pdf with styles """ # Convert markdown to html raw_html = "" extras = ["cuddled-lists"] if md_file_path: raw_html = markdown_path(md_file_path, extras=extras) elif md_content: raw_html = markdown(md_content, extras=extras) if not len(raw_html): raise ValidationError('Input markdown seems empty') # Weasyprint HTML object - html = HTML(string=raw_html) + html = HTML(string=raw_html, base_url=base_url) # Get styles css = [] if css_file_path: css.append(CSS(filename=css_file_path)) # Generate PDF html.write_pdf(pdf_file_path, stylesheets=css) return
Allow to add a base url to find media
## Code Before: from markdown2 import markdown, markdown_path from weasyprint import HTML, CSS from .exceptions import ValidationError __title__ = 'md2pdf' __version__ = '0.2.1' __author__ = 'Julien Maupetit' __license__ = 'MIT' __copyright__ = 'Copyright 2013 Julien Maupetit' def md2pdf(pdf_file_path, md_content=None, md_file_path=None, css_file_path=None): """ Convert markdown file to pdf with styles """ # Convert markdown to html raw_html = "" extras = ["cuddled-lists"] if md_file_path: raw_html = markdown_path(md_file_path, extras=extras) elif md_content: raw_html = markdown(md_content, extras=extras) if not len(raw_html): raise ValidationError('Input markdown seems empty') # Weasyprint HTML object html = HTML(string=raw_html) # Get styles css = [] if css_file_path: css.append(CSS(filename=css_file_path)) # Generate PDF html.write_pdf(pdf_file_path, stylesheets=css) return ## Instruction: Allow to add a base url to find media ## Code After: from markdown2 import markdown, markdown_path from weasyprint import HTML, CSS from .exceptions import ValidationError __title__ = 'md2pdf' __version__ = '0.2.1' __author__ = 'Julien Maupetit' __license__ = 'MIT' __copyright__ = 'Copyright 2013 Julien Maupetit' def md2pdf(pdf_file_path, md_content=None, md_file_path=None, css_file_path=None, base_url=None): """ Convert markdown file to pdf with styles """ # Convert markdown to html raw_html = "" extras = ["cuddled-lists"] if md_file_path: raw_html = markdown_path(md_file_path, extras=extras) elif md_content: raw_html = markdown(md_content, extras=extras) if not len(raw_html): raise ValidationError('Input markdown seems empty') # Weasyprint HTML object html = HTML(string=raw_html, base_url=base_url) # Get styles css = [] if css_file_path: css.append(CSS(filename=css_file_path)) # Generate PDF html.write_pdf(pdf_file_path, stylesheets=css) return
from markdown2 import markdown, markdown_path from weasyprint import HTML, CSS from .exceptions import ValidationError __title__ = 'md2pdf' __version__ = '0.2.1' __author__ = 'Julien Maupetit' __license__ = 'MIT' __copyright__ = 'Copyright 2013 Julien Maupetit' def md2pdf(pdf_file_path, md_content=None, md_file_path=None, - css_file_path=None): + css_file_path=None, base_url=None): ? +++++++++++++++ """ Convert markdown file to pdf with styles """ # Convert markdown to html raw_html = "" extras = ["cuddled-lists"] if md_file_path: raw_html = markdown_path(md_file_path, extras=extras) elif md_content: raw_html = markdown(md_content, extras=extras) if not len(raw_html): raise ValidationError('Input markdown seems empty') # Weasyprint HTML object - html = HTML(string=raw_html) + html = HTML(string=raw_html, base_url=base_url) ? +++++++++++++++++++ # Get styles css = [] if css_file_path: css.append(CSS(filename=css_file_path)) # Generate PDF html.write_pdf(pdf_file_path, stylesheets=css) return
37be9141cbcafb51ebef4ba76a5c2f1dcd9449d1
example/test1_autograder.py
example/test1_autograder.py
from nose.tools import eq_ as assert_eq @score(problem="hello", points=0.5) def grade_hello1(): """Grade 'hello' with input 'Jessica'""" msg = hello("Jessica") assert_eq(msg, "Hello, Jessica!") @score(problem="hello", points=0.5) def grade_hello2(): """Grade 'hello' with input 'Python'""" msg = hello("Python") assert_eq(msg, "Hello, Python!") @score(problem="goodbye", points=0.5) def grade_goodbye1(): """Grade 'goodbye' with input 'Jessica'""" msg = goodbye("Jessica") assert_eq(msg, "Goodbye, Jessica") @score(problem="goodbye", points=0.5) def grade_goodbye2(): """Grade 'goodbye' with input 'Python'""" msg = goodbye("Python") assert_eq(msg, "Goodbye, Python")
from nose.tools import eq_ as assert_eq @score(problem="Problem 1/Part A", points=0.5) def grade_hello1(): """Grade 'hello' with input 'Jessica'""" msg = hello("Jessica") assert_eq(msg, "Hello, Jessica!") @score(problem="Problem 1/Part A", points=0.5) def grade_hello2(): """Grade 'hello' with input 'Python'""" msg = hello("Python") assert_eq(msg, "Hello, Python!") @score(problem="Problem 1/Part B", points=0.5) def grade_goodbye1(): """Grade 'goodbye' with input 'Jessica'""" msg = goodbye("Jessica") assert_eq(msg, "Goodbye, Jessica") @score(problem="Problem 1/Part B", points=0.5) def grade_goodbye2(): """Grade 'goodbye' with input 'Python'""" msg = goodbye("Python") assert_eq(msg, "Goodbye, Python")
Update example autograding code to use heading names
Update example autograding code to use heading names
Python
mit
jhamrick/original-nbgrader,jhamrick/original-nbgrader
from nose.tools import eq_ as assert_eq + - @score(problem="hello", points=0.5) + @score(problem="Problem 1/Part A", points=0.5) def grade_hello1(): """Grade 'hello' with input 'Jessica'""" msg = hello("Jessica") assert_eq(msg, "Hello, Jessica!") + - @score(problem="hello", points=0.5) + @score(problem="Problem 1/Part A", points=0.5) def grade_hello2(): """Grade 'hello' with input 'Python'""" msg = hello("Python") assert_eq(msg, "Hello, Python!") + - @score(problem="goodbye", points=0.5) + @score(problem="Problem 1/Part B", points=0.5) def grade_goodbye1(): """Grade 'goodbye' with input 'Jessica'""" msg = goodbye("Jessica") assert_eq(msg, "Goodbye, Jessica") + - @score(problem="goodbye", points=0.5) + @score(problem="Problem 1/Part B", points=0.5) def grade_goodbye2(): """Grade 'goodbye' with input 'Python'""" msg = goodbye("Python") assert_eq(msg, "Goodbye, Python")
Update example autograding code to use heading names
## Code Before: from nose.tools import eq_ as assert_eq @score(problem="hello", points=0.5) def grade_hello1(): """Grade 'hello' with input 'Jessica'""" msg = hello("Jessica") assert_eq(msg, "Hello, Jessica!") @score(problem="hello", points=0.5) def grade_hello2(): """Grade 'hello' with input 'Python'""" msg = hello("Python") assert_eq(msg, "Hello, Python!") @score(problem="goodbye", points=0.5) def grade_goodbye1(): """Grade 'goodbye' with input 'Jessica'""" msg = goodbye("Jessica") assert_eq(msg, "Goodbye, Jessica") @score(problem="goodbye", points=0.5) def grade_goodbye2(): """Grade 'goodbye' with input 'Python'""" msg = goodbye("Python") assert_eq(msg, "Goodbye, Python") ## Instruction: Update example autograding code to use heading names ## Code After: from nose.tools import eq_ as assert_eq @score(problem="Problem 1/Part A", points=0.5) def grade_hello1(): """Grade 'hello' with input 'Jessica'""" msg = hello("Jessica") assert_eq(msg, "Hello, Jessica!") @score(problem="Problem 1/Part A", points=0.5) def grade_hello2(): """Grade 'hello' with input 'Python'""" msg = hello("Python") assert_eq(msg, "Hello, Python!") @score(problem="Problem 1/Part B", points=0.5) def grade_goodbye1(): """Grade 'goodbye' with input 'Jessica'""" msg = goodbye("Jessica") assert_eq(msg, "Goodbye, Jessica") @score(problem="Problem 1/Part B", points=0.5) def grade_goodbye2(): """Grade 'goodbye' with input 'Python'""" msg = goodbye("Python") assert_eq(msg, "Goodbye, Python")
from nose.tools import eq_ as assert_eq + - @score(problem="hello", points=0.5) ? ^ ^^^ + @score(problem="Problem 1/Part A", points=0.5) ? ^^^^^ ^^^^^^^^^^ def grade_hello1(): """Grade 'hello' with input 'Jessica'""" msg = hello("Jessica") assert_eq(msg, "Hello, Jessica!") + - @score(problem="hello", points=0.5) ? ^ ^^^ + @score(problem="Problem 1/Part A", points=0.5) ? ^^^^^ ^^^^^^^^^^ def grade_hello2(): """Grade 'hello' with input 'Python'""" msg = hello("Python") assert_eq(msg, "Hello, Python!") + - @score(problem="goodbye", points=0.5) ? ^ -- ^ + @score(problem="Problem 1/Part B", points=0.5) ? ^^ ^ ++++++++++ def grade_goodbye1(): """Grade 'goodbye' with input 'Jessica'""" msg = goodbye("Jessica") assert_eq(msg, "Goodbye, Jessica") + - @score(problem="goodbye", points=0.5) ? ^ -- ^ + @score(problem="Problem 1/Part B", points=0.5) ? ^^ ^ ++++++++++ def grade_goodbye2(): """Grade 'goodbye' with input 'Python'""" msg = goodbye("Python") assert_eq(msg, "Goodbye, Python")
3ede283ed3f656dc8f73c962eb452ce4b849dfd9
guardhouse/main/forms.py
guardhouse/main/forms.py
from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('verified',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates')
from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('belongs_to', 'verification_state',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates')
Remove internal fields form from
Remove internal fields form from
Python
bsd-3-clause
ulope/guardhouse,ulope/guardhouse
from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site - exclude = ('verified',) + exclude = ('belongs_to', 'verification_state',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates')
Remove internal fields form from
## Code Before: from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('verified',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates') ## Instruction: Remove internal fields form from ## Code After: from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site exclude = ('belongs_to', 'verification_state',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates')
from django.forms import ModelForm from .models import Account, Site class SiteForm(ModelForm): class Meta(object): model = Site - exclude = ('verified',) + exclude = ('belongs_to', 'verification_state',) class AccountForm(ModelForm): class Meta(object): model = Account exclude = ('owner', 'delegates')
81904effd492e2b2cea64dc98b29033261ae8b62
tests/generator_test.py
tests/generator_test.py
from fixture import GeneratorTest from google.appengine.ext import testbed, ndb class GeneratorTest(GeneratorTest): def testLotsaModelsGenerated(self): for klass in self.klasses: k = klass._get_kind() assert ndb.Model._lookup_model(k) == klass, klass
from fixture import GeneratorTest from google.appengine.ext import testbed, ndb class GeneratorTest(GeneratorTest): def testLotsaModelsGenerated(self): for klass in self.klasses: k = klass._get_kind() assert ndb.Model._lookup_model(k) == klass, klass assert len(self.klasses) > 100
Check that we are creating Test Classes
Check that we are creating Test Classes
Python
mit
talkiq/gaend,samedhi/gaend,talkiq/gaend,samedhi/gaend
from fixture import GeneratorTest from google.appengine.ext import testbed, ndb class GeneratorTest(GeneratorTest): def testLotsaModelsGenerated(self): for klass in self.klasses: k = klass._get_kind() assert ndb.Model._lookup_model(k) == klass, klass + assert len(self.klasses) > 100 +
Check that we are creating Test Classes
## Code Before: from fixture import GeneratorTest from google.appengine.ext import testbed, ndb class GeneratorTest(GeneratorTest): def testLotsaModelsGenerated(self): for klass in self.klasses: k = klass._get_kind() assert ndb.Model._lookup_model(k) == klass, klass ## Instruction: Check that we are creating Test Classes ## Code After: from fixture import GeneratorTest from google.appengine.ext import testbed, ndb class GeneratorTest(GeneratorTest): def testLotsaModelsGenerated(self): for klass in self.klasses: k = klass._get_kind() assert ndb.Model._lookup_model(k) == klass, klass assert len(self.klasses) > 100
from fixture import GeneratorTest from google.appengine.ext import testbed, ndb class GeneratorTest(GeneratorTest): def testLotsaModelsGenerated(self): for klass in self.klasses: k = klass._get_kind() assert ndb.Model._lookup_model(k) == klass, klass + + assert len(self.klasses) > 100
f3cd06721efaf3045d09f2d3c2c067e01b27953a
tests/som_test.py
tests/som_test.py
import unittest from parameterized import parameterized from som.vm.universe import Universe class SomTest(unittest.TestCase): @parameterized.expand([ ("ClassStructure",), ("Array" ,), ("Block" ,), ("ClassLoading" ,), ("Closure" ,), ("Coercion" ,), ("CompilerReturn",), ("Double" ,), ("DoesNotUnderstand",), ("Empty" ,), ("Global" ,), ("Hash" ,), ("Integer" ,), ("Preliminary" ,), ("Reflection" ,), ("SelfBlock" ,), ("Set",), ("SpecialSelectors",), ("Super" ,), ("String" ,), ("Symbol" ,), ("System" ,), ("Vector" ,)]) def test_som_test(self, test_name): args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name] u = Universe(True) u.interpret(args) self.assertEquals(0, u.last_exit_code()) import sys if 'pytest' in sys.modules: # hack to make pytest not to collect the unexpanded test method delattr(SomTest, "test_som_test")
import unittest from parameterized import parameterized from som.vm.universe import Universe class SomTest(unittest.TestCase): @parameterized.expand([ ("Array" ,), ("Block" ,), ("ClassLoading" ,), ("ClassStructure",), ("Closure" ,), ("Coercion" ,), ("CompilerReturn",), ("DoesNotUnderstand",), ("Double" ,), ("Empty" ,), ("Global" ,), ("Hash" ,), ("Integer" ,), ("Preliminary" ,), ("Reflection" ,), ("SelfBlock" ,), ("SpecialSelectors",), ("Super" ,), ("Set",), ("String" ,), ("Symbol" ,), ("System" ,), ("Vector" ,)]) def test_som_test(self, test_name): args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name] u = Universe(True) u.interpret(args) self.assertEquals(0, u.last_exit_code()) import sys if 'pytest' in sys.modules: # hack to make pytest not to collect the unexpanded test method delattr(SomTest, "test_som_test")
Sort tests, to verify they are complete
Sort tests, to verify they are complete Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
Python
mit
SOM-st/PySOM,SOM-st/RPySOM,SOM-st/RTruffleSOM,SOM-st/RPySOM,smarr/PySOM,smarr/PySOM,smarr/RTruffleSOM,SOM-st/RTruffleSOM,smarr/RTruffleSOM,SOM-st/PySOM
import unittest from parameterized import parameterized from som.vm.universe import Universe class SomTest(unittest.TestCase): @parameterized.expand([ - ("ClassStructure",), ("Array" ,), ("Block" ,), ("ClassLoading" ,), + ("ClassStructure",), ("Closure" ,), ("Coercion" ,), ("CompilerReturn",), + ("DoesNotUnderstand",), ("Double" ,), - ("DoesNotUnderstand",), ("Empty" ,), ("Global" ,), ("Hash" ,), ("Integer" ,), ("Preliminary" ,), ("Reflection" ,), ("SelfBlock" ,), - ("Set",), ("SpecialSelectors",), ("Super" ,), + ("Set",), ("String" ,), ("Symbol" ,), ("System" ,), ("Vector" ,)]) def test_som_test(self, test_name): args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name] u = Universe(True) u.interpret(args) self.assertEquals(0, u.last_exit_code()) import sys if 'pytest' in sys.modules: # hack to make pytest not to collect the unexpanded test method delattr(SomTest, "test_som_test")
Sort tests, to verify they are complete
## Code Before: import unittest from parameterized import parameterized from som.vm.universe import Universe class SomTest(unittest.TestCase): @parameterized.expand([ ("ClassStructure",), ("Array" ,), ("Block" ,), ("ClassLoading" ,), ("Closure" ,), ("Coercion" ,), ("CompilerReturn",), ("Double" ,), ("DoesNotUnderstand",), ("Empty" ,), ("Global" ,), ("Hash" ,), ("Integer" ,), ("Preliminary" ,), ("Reflection" ,), ("SelfBlock" ,), ("Set",), ("SpecialSelectors",), ("Super" ,), ("String" ,), ("Symbol" ,), ("System" ,), ("Vector" ,)]) def test_som_test(self, test_name): args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name] u = Universe(True) u.interpret(args) self.assertEquals(0, u.last_exit_code()) import sys if 'pytest' in sys.modules: # hack to make pytest not to collect the unexpanded test method delattr(SomTest, "test_som_test") ## Instruction: Sort tests, to verify they are complete ## Code After: import unittest from parameterized import parameterized from som.vm.universe import Universe class SomTest(unittest.TestCase): @parameterized.expand([ ("Array" ,), ("Block" ,), ("ClassLoading" ,), ("ClassStructure",), ("Closure" ,), ("Coercion" ,), ("CompilerReturn",), ("DoesNotUnderstand",), ("Double" ,), ("Empty" ,), ("Global" ,), ("Hash" ,), ("Integer" ,), ("Preliminary" ,), ("Reflection" ,), ("SelfBlock" ,), ("SpecialSelectors",), ("Super" ,), ("Set",), ("String" ,), ("Symbol" ,), ("System" ,), ("Vector" ,)]) def test_som_test(self, test_name): args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name] u = Universe(True) u.interpret(args) self.assertEquals(0, u.last_exit_code()) import sys if 'pytest' in sys.modules: # hack to make pytest not to collect the unexpanded test method delattr(SomTest, "test_som_test")
import unittest from parameterized import parameterized from som.vm.universe import Universe class SomTest(unittest.TestCase): @parameterized.expand([ - ("ClassStructure",), ("Array" ,), ("Block" ,), ("ClassLoading" ,), + ("ClassStructure",), ("Closure" ,), ("Coercion" ,), ("CompilerReturn",), + ("DoesNotUnderstand",), ("Double" ,), - ("DoesNotUnderstand",), ("Empty" ,), ("Global" ,), ("Hash" ,), ("Integer" ,), ("Preliminary" ,), ("Reflection" ,), ("SelfBlock" ,), - ("Set",), ("SpecialSelectors",), ("Super" ,), + ("Set",), ("String" ,), ("Symbol" ,), ("System" ,), ("Vector" ,)]) def test_som_test(self, test_name): args = ["-cp", "Smalltalk", "TestSuite/TestHarness.som", test_name] u = Universe(True) u.interpret(args) self.assertEquals(0, u.last_exit_code()) import sys if 'pytest' in sys.modules: # hack to make pytest not to collect the unexpanded test method delattr(SomTest, "test_som_test")
7d362cfc37398a22440173fa7209224a2542778e
eng100l/ambulances/urls.py
eng100l/ambulances/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^update/(?P<pk>[0-9]+)$', views.AmbulanceUpdateView.as_view(), name="ambulance_update"), url(r'^info/(?P<pk>[0-9]+)$', views.AmbulanceInfoView.as_view(), name="ambulance_info"), url(r'^ambulance_create$', views.AmbulanceCreateView.as_view(), name="ambulance_create"), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^update/(?P<pk>[0-9]+)$', views.AmbulanceUpdateView.as_view(), name="ambulance_update"), url(r'^info/(?P<pk>[0-9]+)$', views.AmbulanceInfoView.as_view(), name="ambulance_info"), url(r'^create$', views.AmbulanceCreateView.as_view(), name="ambulance_create"), ]
Simplify URL for ambulance creation
Simplify URL for ambulance creation
Python
bsd-3-clause
EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient
from django.conf.urls import url from . import views urlpatterns = [ url(r'^update/(?P<pk>[0-9]+)$', views.AmbulanceUpdateView.as_view(), name="ambulance_update"), url(r'^info/(?P<pk>[0-9]+)$', views.AmbulanceInfoView.as_view(), name="ambulance_info"), - url(r'^ambulance_create$', + url(r'^create$', views.AmbulanceCreateView.as_view(), name="ambulance_create"), ]
Simplify URL for ambulance creation
## Code Before: from django.conf.urls import url from . import views urlpatterns = [ url(r'^update/(?P<pk>[0-9]+)$', views.AmbulanceUpdateView.as_view(), name="ambulance_update"), url(r'^info/(?P<pk>[0-9]+)$', views.AmbulanceInfoView.as_view(), name="ambulance_info"), url(r'^ambulance_create$', views.AmbulanceCreateView.as_view(), name="ambulance_create"), ] ## Instruction: Simplify URL for ambulance creation ## Code After: from django.conf.urls import url from . import views urlpatterns = [ url(r'^update/(?P<pk>[0-9]+)$', views.AmbulanceUpdateView.as_view(), name="ambulance_update"), url(r'^info/(?P<pk>[0-9]+)$', views.AmbulanceInfoView.as_view(), name="ambulance_info"), url(r'^create$', views.AmbulanceCreateView.as_view(), name="ambulance_create"), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^update/(?P<pk>[0-9]+)$', views.AmbulanceUpdateView.as_view(), name="ambulance_update"), url(r'^info/(?P<pk>[0-9]+)$', views.AmbulanceInfoView.as_view(), name="ambulance_info"), - url(r'^ambulance_create$', ? ---------- + url(r'^create$', views.AmbulanceCreateView.as_view(), name="ambulance_create"), ]
2b05a59b09e72f263761dae2feac360f5abd1f82
promgen/__init__.py
promgen/__init__.py
default_app_config = 'promgen.apps.PromgenConfig' import logging logging.basicConfig(level=logging.DEBUG)
default_app_config = 'promgen.apps.PromgenConfig'
Remove some debug logging config
Remove some debug logging config
Python
mit
kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen
default_app_config = 'promgen.apps.PromgenConfig' - import logging - logging.basicConfig(level=logging.DEBUG)
Remove some debug logging config
## Code Before: default_app_config = 'promgen.apps.PromgenConfig' import logging logging.basicConfig(level=logging.DEBUG) ## Instruction: Remove some debug logging config ## Code After: default_app_config = 'promgen.apps.PromgenConfig'
default_app_config = 'promgen.apps.PromgenConfig' - import logging - logging.basicConfig(level=logging.DEBUG)
7e015e6955dfe392649b5ca0cdeb5a7701700f24
laalaa/apps/advisers/serializers.py
laalaa/apps/advisers/serializers.py
from rest_framework import serializers from rest_framework_gis import serializers as gis_serializers from .models import Location, Office, Organisation class DistanceField(serializers.ReadOnlyField): def to_representation(self, obj): # miles return obj.mi class OrganisationSerializer(serializers.ModelSerializer): class Meta: model = Organisation fields = ('name', 'website',) class LocationSerializer(gis_serializers.GeoModelSerializer): class Meta: model = Location fields = ( 'address', 'city', 'postcode', 'point', 'type') class OfficeSerializer(gis_serializers.GeoModelSerializer): location = LocationSerializer() organisation = OrganisationSerializer() distance = DistanceField() class Meta: model = Office fields = ( 'telephone', 'location', 'organisation', 'distance')
from rest_framework import serializers from rest_framework_gis import serializers as gis_serializers from .models import Location, Office, Organisation class DistanceField(serializers.ReadOnlyField): def to_representation(self, obj): # miles return obj.mi class OrganisationSerializer(serializers.ModelSerializer): class Meta: model = Organisation fields = ('name', 'website',) class LocationSerializer(gis_serializers.GeoModelSerializer): class Meta: model = Location fields = ( 'address', 'city', 'postcode', 'point', 'type') class OfficeSerializer(gis_serializers.GeoModelSerializer): location = LocationSerializer() organisation = OrganisationSerializer() distance = DistanceField() categories = serializers.SlugRelatedField( slug_field='code', many=True, read_only=True) class Meta: model = Office fields = ( 'telephone', 'location', 'organisation', 'distance', 'categories')
Add list of category codes to offices
Add list of category codes to offices
Python
mit
ministryofjustice/laa-legal-adviser-api,ministryofjustice/laa-legal-adviser-api,ministryofjustice/laa-legal-adviser-api
from rest_framework import serializers from rest_framework_gis import serializers as gis_serializers from .models import Location, Office, Organisation class DistanceField(serializers.ReadOnlyField): def to_representation(self, obj): # miles return obj.mi class OrganisationSerializer(serializers.ModelSerializer): class Meta: model = Organisation fields = ('name', 'website',) class LocationSerializer(gis_serializers.GeoModelSerializer): class Meta: model = Location fields = ( 'address', 'city', 'postcode', 'point', 'type') class OfficeSerializer(gis_serializers.GeoModelSerializer): location = LocationSerializer() organisation = OrganisationSerializer() distance = DistanceField() + categories = serializers.SlugRelatedField( + slug_field='code', many=True, read_only=True) class Meta: model = Office fields = ( - 'telephone', 'location', 'organisation', 'distance') + 'telephone', 'location', 'organisation', 'distance', + 'categories')
Add list of category codes to offices
## Code Before: from rest_framework import serializers from rest_framework_gis import serializers as gis_serializers from .models import Location, Office, Organisation class DistanceField(serializers.ReadOnlyField): def to_representation(self, obj): # miles return obj.mi class OrganisationSerializer(serializers.ModelSerializer): class Meta: model = Organisation fields = ('name', 'website',) class LocationSerializer(gis_serializers.GeoModelSerializer): class Meta: model = Location fields = ( 'address', 'city', 'postcode', 'point', 'type') class OfficeSerializer(gis_serializers.GeoModelSerializer): location = LocationSerializer() organisation = OrganisationSerializer() distance = DistanceField() class Meta: model = Office fields = ( 'telephone', 'location', 'organisation', 'distance') ## Instruction: Add list of category codes to offices ## Code After: from rest_framework import serializers from rest_framework_gis import serializers as gis_serializers from .models import Location, Office, Organisation class DistanceField(serializers.ReadOnlyField): def to_representation(self, obj): # miles return obj.mi class OrganisationSerializer(serializers.ModelSerializer): class Meta: model = Organisation fields = ('name', 'website',) class LocationSerializer(gis_serializers.GeoModelSerializer): class Meta: model = Location fields = ( 'address', 'city', 'postcode', 'point', 'type') class OfficeSerializer(gis_serializers.GeoModelSerializer): location = LocationSerializer() organisation = OrganisationSerializer() distance = DistanceField() categories = serializers.SlugRelatedField( slug_field='code', many=True, read_only=True) class Meta: model = Office fields = ( 'telephone', 'location', 'organisation', 'distance', 'categories')
from rest_framework import serializers from rest_framework_gis import serializers as gis_serializers from .models import Location, Office, Organisation class DistanceField(serializers.ReadOnlyField): def to_representation(self, obj): # miles return obj.mi class OrganisationSerializer(serializers.ModelSerializer): class Meta: model = Organisation fields = ('name', 'website',) class LocationSerializer(gis_serializers.GeoModelSerializer): class Meta: model = Location fields = ( 'address', 'city', 'postcode', 'point', 'type') class OfficeSerializer(gis_serializers.GeoModelSerializer): location = LocationSerializer() organisation = OrganisationSerializer() distance = DistanceField() + categories = serializers.SlugRelatedField( + slug_field='code', many=True, read_only=True) class Meta: model = Office fields = ( - 'telephone', 'location', 'organisation', 'distance') ? ^ + 'telephone', 'location', 'organisation', 'distance', ? ^ + 'categories')
fe65e85e0a29341a6eebbb1bafb28b8d1225abfc
harvester/rq_worker_sns_msgs.py
harvester/rq_worker_sns_msgs.py
'''A custom rq worker class to add start & stop SNS messages to all jobs''' import logging from rq.worker import Worker from harvester.sns_message import publish_to_harvesting logger = logging.getLogger(__name__) class SNSWorker(Worker): def execute_job(self, job, queue): """Spawns a work horse to perform the actual work and passes it a job. The worker will wait for the work horse and make sure it executes within the given timeout bounds, or will end the work horse with SIGALRM. """ worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0] subject = 'Worker {} starting job {}'.format( worker_name, job.description) publish_to_harvesting(subject, subject) self.set_state('busy') self.fork_work_horse(job, queue) self.monitor_work_horse(job) subject = 'Worker {} finished job {}'.format( worker_name, job.description) publish_to_harvesting(subject, subject) self.set_state('idle')
'''A custom rq worker class to add start & stop SNS messages to all jobs''' import logging from rq.worker import Worker from harvester.sns_message import publish_to_harvesting logger = logging.getLogger(__name__) def exception_to_sns(job, *exc_info): '''Make an exception handler to report exceptions to SNS msg queue''' subject = 'FAILED: job {}'.format(job.description) message = 'ERROR: job {} failed\n{}'.format( job.description, exc_info[1]) logging.error(message) publish_to_harvesting(subject, message) class SNSWorker(Worker): def execute_job(self, job, queue): """Spawns a work horse to perform the actual work and passes it a job. The worker will wait for the work horse and make sure it executes within the given timeout bounds, or will end the work horse with SIGALRM. """ worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0] subject = 'Worker {} starting job {}'.format( worker_name, job.description) #publish_to_harvesting(subject, subject) self.set_state('busy') self.fork_work_horse(job, queue) self.monitor_work_horse(job) subject = 'Worker {} finished job {}'.format( worker_name, job.description) #publish_to_harvesting(subject, subject) self.set_state('idle')
Add RQ exception handler to report to SNS topic
Add RQ exception handler to report to SNS topic
Python
bsd-3-clause
mredar/harvester,barbarahui/harvester,barbarahui/harvester,mredar/harvester,ucldc/harvester,ucldc/harvester
'''A custom rq worker class to add start & stop SNS messages to all jobs''' import logging from rq.worker import Worker from harvester.sns_message import publish_to_harvesting logger = logging.getLogger(__name__) + + + def exception_to_sns(job, *exc_info): + '''Make an exception handler to report exceptions to SNS msg queue''' + subject = 'FAILED: job {}'.format(job.description) + message = 'ERROR: job {} failed\n{}'.format( + job.description, + exc_info[1]) + logging.error(message) + publish_to_harvesting(subject, message) class SNSWorker(Worker): def execute_job(self, job, queue): """Spawns a work horse to perform the actual work and passes it a job. The worker will wait for the work horse and make sure it executes within the given timeout bounds, or will end the work horse with SIGALRM. """ worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0] subject = 'Worker {} starting job {}'.format( worker_name, job.description) - publish_to_harvesting(subject, subject) + #publish_to_harvesting(subject, subject) self.set_state('busy') self.fork_work_horse(job, queue) self.monitor_work_horse(job) subject = 'Worker {} finished job {}'.format( worker_name, job.description) - publish_to_harvesting(subject, subject) + #publish_to_harvesting(subject, subject) self.set_state('idle')
Add RQ exception handler to report to SNS topic
## Code Before: '''A custom rq worker class to add start & stop SNS messages to all jobs''' import logging from rq.worker import Worker from harvester.sns_message import publish_to_harvesting logger = logging.getLogger(__name__) class SNSWorker(Worker): def execute_job(self, job, queue): """Spawns a work horse to perform the actual work and passes it a job. The worker will wait for the work horse and make sure it executes within the given timeout bounds, or will end the work horse with SIGALRM. """ worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0] subject = 'Worker {} starting job {}'.format( worker_name, job.description) publish_to_harvesting(subject, subject) self.set_state('busy') self.fork_work_horse(job, queue) self.monitor_work_horse(job) subject = 'Worker {} finished job {}'.format( worker_name, job.description) publish_to_harvesting(subject, subject) self.set_state('idle') ## Instruction: Add RQ exception handler to report to SNS topic ## Code After: '''A custom rq worker class to add start & stop SNS messages to all jobs''' import logging from rq.worker import Worker from harvester.sns_message import publish_to_harvesting logger = logging.getLogger(__name__) def exception_to_sns(job, *exc_info): '''Make an exception handler to report exceptions to SNS msg queue''' subject = 'FAILED: job {}'.format(job.description) message = 'ERROR: job {} failed\n{}'.format( job.description, exc_info[1]) logging.error(message) publish_to_harvesting(subject, message) class SNSWorker(Worker): def execute_job(self, job, queue): """Spawns a work horse to perform the actual work and passes it a job. The worker will wait for the work horse and make sure it executes within the given timeout bounds, or will end the work horse with SIGALRM. """ worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0] subject = 'Worker {} starting job {}'.format( worker_name, job.description) #publish_to_harvesting(subject, subject) self.set_state('busy') self.fork_work_horse(job, queue) self.monitor_work_horse(job) subject = 'Worker {} finished job {}'.format( worker_name, job.description) #publish_to_harvesting(subject, subject) self.set_state('idle')
'''A custom rq worker class to add start & stop SNS messages to all jobs''' import logging from rq.worker import Worker from harvester.sns_message import publish_to_harvesting logger = logging.getLogger(__name__) + + + def exception_to_sns(job, *exc_info): + '''Make an exception handler to report exceptions to SNS msg queue''' + subject = 'FAILED: job {}'.format(job.description) + message = 'ERROR: job {} failed\n{}'.format( + job.description, + exc_info[1]) + logging.error(message) + publish_to_harvesting(subject, message) class SNSWorker(Worker): def execute_job(self, job, queue): """Spawns a work horse to perform the actual work and passes it a job. The worker will wait for the work horse and make sure it executes within the given timeout bounds, or will end the work horse with SIGALRM. """ worker_name = (self.key.rsplit(':', 1)[1]).rsplit('.', 1)[0] subject = 'Worker {} starting job {}'.format( worker_name, job.description) - publish_to_harvesting(subject, subject) + #publish_to_harvesting(subject, subject) ? + self.set_state('busy') self.fork_work_horse(job, queue) self.monitor_work_horse(job) subject = 'Worker {} finished job {}'.format( worker_name, job.description) - publish_to_harvesting(subject, subject) + #publish_to_harvesting(subject, subject) ? + self.set_state('idle')
c83a680603b83edafe61f6d41b34989c70a4e4ae
clowder/clowder/cli/save_controller.py
clowder/clowder/cli/save_controller.py
from cement.ext.ext_argparse import expose from clowder.cli.abstract_base_controller import AbstractBaseController class SaveController(AbstractBaseController): class Meta: label = 'save' stacked_on = 'base' stacked_type = 'nested' description = 'Create version of clowder.yaml for current repos' arguments = [ (['version'], dict(help='version to save', metavar='VERSION')) ] @expose(help="second-controller default command", hide=True) def default(self): print("Inside SecondController.default()")
import os import sys from cement.ext.ext_argparse import expose import clowder.util.formatting as fmt from clowder.cli.abstract_base_controller import AbstractBaseController from clowder.util.decorators import valid_clowder_yaml_required from clowder.commands.util import ( validate_groups, validate_projects_exist ) from clowder.yaml.saving import save_yaml class SaveController(AbstractBaseController): class Meta: label = 'save' stacked_on = 'base' stacked_type = 'nested' description = 'Create version of clowder.yaml for current repos' arguments = [ (['version'], dict(help='version to save', metavar='VERSION')) ] @expose(help="second-controller default command", hide=True) @valid_clowder_yaml_required def default(self): if self.app.pargs.version.lower() == 'default': print(fmt.save_default_error(self.app.pargs.version)) sys.exit(1) self.clowder_repo.print_status() validate_projects_exist(self.clowder) validate_groups(self.clowder.groups) version_name = self.app.pargs.version.replace('/', '-') # Replace path separators with dashes version_dir = os.path.join(self.clowder.root_directory, '.clowder', 'versions', version_name) _make_dir(version_dir) yaml_file = os.path.join(version_dir, 'clowder.yaml') if os.path.exists(yaml_file): print(fmt.save_version_exists_error(version_name, yaml_file) + '\n') sys.exit(1) print(fmt.save_version(version_name, yaml_file)) save_yaml(self.clowder.get_yaml(), yaml_file) def _make_dir(directory): """Make directory if it doesn't exist :param str directory: Directory path to create :raise OSError: """ if not os.path.exists(directory): try: os.makedirs(directory) except OSError as err: if err.errno != os.errno.EEXIST: raise
Add `clowder save` logic to Cement controller
Add `clowder save` logic to Cement controller
Python
mit
JrGoodle/clowder,JrGoodle/clowder,JrGoodle/clowder
+ import os + import sys + from cement.ext.ext_argparse import expose + import clowder.util.formatting as fmt from clowder.cli.abstract_base_controller import AbstractBaseController + from clowder.util.decorators import valid_clowder_yaml_required + from clowder.commands.util import ( + validate_groups, + validate_projects_exist + ) + from clowder.yaml.saving import save_yaml class SaveController(AbstractBaseController): class Meta: label = 'save' stacked_on = 'base' stacked_type = 'nested' description = 'Create version of clowder.yaml for current repos' arguments = [ (['version'], dict(help='version to save', metavar='VERSION')) ] @expose(help="second-controller default command", hide=True) + @valid_clowder_yaml_required def default(self): - print("Inside SecondController.default()") + if self.app.pargs.version.lower() == 'default': + print(fmt.save_default_error(self.app.pargs.version)) + sys.exit(1) + self.clowder_repo.print_status() + validate_projects_exist(self.clowder) + validate_groups(self.clowder.groups) + + version_name = self.app.pargs.version.replace('/', '-') # Replace path separators with dashes + version_dir = os.path.join(self.clowder.root_directory, '.clowder', 'versions', version_name) + _make_dir(version_dir) + + yaml_file = os.path.join(version_dir, 'clowder.yaml') + if os.path.exists(yaml_file): + print(fmt.save_version_exists_error(version_name, yaml_file) + '\n') + sys.exit(1) + + print(fmt.save_version(version_name, yaml_file)) + save_yaml(self.clowder.get_yaml(), yaml_file) + + + def _make_dir(directory): + """Make directory if it doesn't exist + + :param str directory: Directory path to create + :raise OSError: + """ + + if not os.path.exists(directory): + try: + os.makedirs(directory) + except OSError as err: + if err.errno != os.errno.EEXIST: + raise +
Add `clowder save` logic to Cement controller
## Code Before: from cement.ext.ext_argparse import expose from clowder.cli.abstract_base_controller import AbstractBaseController class SaveController(AbstractBaseController): class Meta: label = 'save' stacked_on = 'base' stacked_type = 'nested' description = 'Create version of clowder.yaml for current repos' arguments = [ (['version'], dict(help='version to save', metavar='VERSION')) ] @expose(help="second-controller default command", hide=True) def default(self): print("Inside SecondController.default()") ## Instruction: Add `clowder save` logic to Cement controller ## Code After: import os import sys from cement.ext.ext_argparse import expose import clowder.util.formatting as fmt from clowder.cli.abstract_base_controller import AbstractBaseController from clowder.util.decorators import valid_clowder_yaml_required from clowder.commands.util import ( validate_groups, validate_projects_exist ) from clowder.yaml.saving import save_yaml class SaveController(AbstractBaseController): class Meta: label = 'save' stacked_on = 'base' stacked_type = 'nested' description = 'Create version of clowder.yaml for current repos' arguments = [ (['version'], dict(help='version to save', metavar='VERSION')) ] @expose(help="second-controller default command", hide=True) @valid_clowder_yaml_required def default(self): if self.app.pargs.version.lower() == 'default': print(fmt.save_default_error(self.app.pargs.version)) sys.exit(1) self.clowder_repo.print_status() validate_projects_exist(self.clowder) validate_groups(self.clowder.groups) version_name = self.app.pargs.version.replace('/', '-') # Replace path separators with dashes version_dir = os.path.join(self.clowder.root_directory, '.clowder', 'versions', version_name) _make_dir(version_dir) yaml_file = os.path.join(version_dir, 'clowder.yaml') if os.path.exists(yaml_file): print(fmt.save_version_exists_error(version_name, yaml_file) + '\n') sys.exit(1) print(fmt.save_version(version_name, yaml_file)) save_yaml(self.clowder.get_yaml(), yaml_file) def _make_dir(directory): """Make directory if it doesn't exist :param str directory: Directory path to create :raise OSError: """ if not os.path.exists(directory): try: os.makedirs(directory) except OSError as err: if err.errno != os.errno.EEXIST: raise
+ import os + import sys + from cement.ext.ext_argparse import expose + import clowder.util.formatting as fmt from clowder.cli.abstract_base_controller import AbstractBaseController + from clowder.util.decorators import valid_clowder_yaml_required + from clowder.commands.util import ( + validate_groups, + validate_projects_exist + ) + from clowder.yaml.saving import save_yaml class SaveController(AbstractBaseController): class Meta: label = 'save' stacked_on = 'base' stacked_type = 'nested' description = 'Create version of clowder.yaml for current repos' arguments = [ (['version'], dict(help='version to save', metavar='VERSION')) ] @expose(help="second-controller default command", hide=True) + @valid_clowder_yaml_required def default(self): - print("Inside SecondController.default()") + if self.app.pargs.version.lower() == 'default': + print(fmt.save_default_error(self.app.pargs.version)) + sys.exit(1) + + self.clowder_repo.print_status() + validate_projects_exist(self.clowder) + validate_groups(self.clowder.groups) + + version_name = self.app.pargs.version.replace('/', '-') # Replace path separators with dashes + version_dir = os.path.join(self.clowder.root_directory, '.clowder', 'versions', version_name) + _make_dir(version_dir) + + yaml_file = os.path.join(version_dir, 'clowder.yaml') + if os.path.exists(yaml_file): + print(fmt.save_version_exists_error(version_name, yaml_file) + '\n') + sys.exit(1) + + print(fmt.save_version(version_name, yaml_file)) + save_yaml(self.clowder.get_yaml(), yaml_file) + + + def _make_dir(directory): + """Make directory if it doesn't exist + + :param str directory: Directory path to create + :raise OSError: + """ + + if not os.path.exists(directory): + try: + os.makedirs(directory) + except OSError as err: + if err.errno != os.errno.EEXIST: + raise
3eaf93f2ecee68fafa1ff4f75d4c6e7f09a37043
api/streams/views.py
api/streams/views.py
from api.streams.models import StreamConfiguration from django.http import JsonResponse from django.http.request import HttpRequest import requests def get_stream_status(request: HttpRequest, stream_slug: str): stream = StreamConfiguration.objects.get(slug=stream_slug) r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream)) r.raise_for_status() return JsonResponse(r.json())
from api.streams.models import StreamConfiguration from django.http import JsonResponse from django.http.request import HttpRequest import requests def get_stream_status(request: HttpRequest, stream_slug: str): stream = StreamConfiguration.objects.get(slug=stream_slug) r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream), timeout=5) r.raise_for_status() return JsonResponse(r.json())
Add timeout to Icecast status request
Add timeout to Icecast status request
Python
mit
urfonline/api,urfonline/api,urfonline/api
from api.streams.models import StreamConfiguration from django.http import JsonResponse from django.http.request import HttpRequest import requests def get_stream_status(request: HttpRequest, stream_slug: str): stream = StreamConfiguration.objects.get(slug=stream_slug) - r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream)) + r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream), timeout=5) r.raise_for_status() return JsonResponse(r.json())
Add timeout to Icecast status request
## Code Before: from api.streams.models import StreamConfiguration from django.http import JsonResponse from django.http.request import HttpRequest import requests def get_stream_status(request: HttpRequest, stream_slug: str): stream = StreamConfiguration.objects.get(slug=stream_slug) r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream)) r.raise_for_status() return JsonResponse(r.json()) ## Instruction: Add timeout to Icecast status request ## Code After: from api.streams.models import StreamConfiguration from django.http import JsonResponse from django.http.request import HttpRequest import requests def get_stream_status(request: HttpRequest, stream_slug: str): stream = StreamConfiguration.objects.get(slug=stream_slug) r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream), timeout=5) r.raise_for_status() return JsonResponse(r.json())
from api.streams.models import StreamConfiguration from django.http import JsonResponse from django.http.request import HttpRequest import requests def get_stream_status(request: HttpRequest, stream_slug: str): stream = StreamConfiguration.objects.get(slug=stream_slug) - r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream)) + r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream), timeout=5) ? +++++++++++ r.raise_for_status() return JsonResponse(r.json())
61cebe12c001bb42350d8e9e99a7fa7d26fc7667
openedx/stanford/lms/lib/courseware_search/lms_filter_generator.py
openedx/stanford/lms/lib/courseware_search/lms_filter_generator.py
from search.filter_generator import SearchFilterGenerator from branding_stanford.models import TileConfiguration from lms.lib.courseware_search.lms_filter_generator import LmsSearchFilterGenerator class TileSearchFilterGenerator(LmsSearchFilterGenerator): """ SearchFilterGenerator for LMS Search. """ def field_dictionary(self, **kwargs): """ Return field filter dictionary for search. """ field_dictionary = super(TileSearchFilterGenerator, self).field_dictionary(**kwargs) if not kwargs.get('user'): # Adds tile courses for discovery search course_tiles_ids = TileConfiguration.objects.filter( enabled=True, ).values_list('course_id', flat=True).order_by('-change_date') field_dictionary['course'] = list(course_tiles_ids) return field_dictionary
from search.filter_generator import SearchFilterGenerator from branding_stanford.models import TileConfiguration from lms.lib.courseware_search.lms_filter_generator import LmsSearchFilterGenerator class TileSearchFilterGenerator(LmsSearchFilterGenerator): """ SearchFilterGenerator for LMS Search. """ def field_dictionary(self, **kwargs): """ Return field filter dictionary for search. """ field_dictionary = super(TileSearchFilterGenerator, self).field_dictionary(**kwargs) if not kwargs.get('user'): # Adds tile courses for discovery search course_tiles_ids = TileConfiguration.objects.filter( enabled=True, ).values_list('course_id', flat=True).order_by('-change_date') courses = list(course_tiles_ids) if len(courses): field_dictionary['course'] = courses return field_dictionary
Use stanford search logic only if configured
Use stanford search logic only if configured
Python
agpl-3.0
Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform
from search.filter_generator import SearchFilterGenerator from branding_stanford.models import TileConfiguration from lms.lib.courseware_search.lms_filter_generator import LmsSearchFilterGenerator class TileSearchFilterGenerator(LmsSearchFilterGenerator): """ SearchFilterGenerator for LMS Search. """ def field_dictionary(self, **kwargs): """ Return field filter dictionary for search. """ field_dictionary = super(TileSearchFilterGenerator, self).field_dictionary(**kwargs) if not kwargs.get('user'): # Adds tile courses for discovery search course_tiles_ids = TileConfiguration.objects.filter( enabled=True, ).values_list('course_id', flat=True).order_by('-change_date') + courses = list(course_tiles_ids) + if len(courses): - field_dictionary['course'] = list(course_tiles_ids) + field_dictionary['course'] = courses return field_dictionary
Use stanford search logic only if configured
## Code Before: from search.filter_generator import SearchFilterGenerator from branding_stanford.models import TileConfiguration from lms.lib.courseware_search.lms_filter_generator import LmsSearchFilterGenerator class TileSearchFilterGenerator(LmsSearchFilterGenerator): """ SearchFilterGenerator for LMS Search. """ def field_dictionary(self, **kwargs): """ Return field filter dictionary for search. """ field_dictionary = super(TileSearchFilterGenerator, self).field_dictionary(**kwargs) if not kwargs.get('user'): # Adds tile courses for discovery search course_tiles_ids = TileConfiguration.objects.filter( enabled=True, ).values_list('course_id', flat=True).order_by('-change_date') field_dictionary['course'] = list(course_tiles_ids) return field_dictionary ## Instruction: Use stanford search logic only if configured ## Code After: from search.filter_generator import SearchFilterGenerator from branding_stanford.models import TileConfiguration from lms.lib.courseware_search.lms_filter_generator import LmsSearchFilterGenerator class TileSearchFilterGenerator(LmsSearchFilterGenerator): """ SearchFilterGenerator for LMS Search. """ def field_dictionary(self, **kwargs): """ Return field filter dictionary for search. """ field_dictionary = super(TileSearchFilterGenerator, self).field_dictionary(**kwargs) if not kwargs.get('user'): # Adds tile courses for discovery search course_tiles_ids = TileConfiguration.objects.filter( enabled=True, ).values_list('course_id', flat=True).order_by('-change_date') courses = list(course_tiles_ids) if len(courses): field_dictionary['course'] = courses return field_dictionary
from search.filter_generator import SearchFilterGenerator from branding_stanford.models import TileConfiguration from lms.lib.courseware_search.lms_filter_generator import LmsSearchFilterGenerator class TileSearchFilterGenerator(LmsSearchFilterGenerator): """ SearchFilterGenerator for LMS Search. """ def field_dictionary(self, **kwargs): """ Return field filter dictionary for search. """ field_dictionary = super(TileSearchFilterGenerator, self).field_dictionary(**kwargs) if not kwargs.get('user'): # Adds tile courses for discovery search course_tiles_ids = TileConfiguration.objects.filter( enabled=True, ).values_list('course_id', flat=True).order_by('-change_date') + courses = list(course_tiles_ids) + if len(courses): - field_dictionary['course'] = list(course_tiles_ids) ? ----- ----- ----- + field_dictionary['course'] = courses ? ++++ return field_dictionary
0bdd2df16823f129b39549a0e41adf1b29470d88
challenges/__init__.py
challenges/__init__.py
from os.path import dirname, basename, isfile import glob import sys modules = glob.glob(dirname(__file__)+"/c*[0-9].py") sys.path.append(dirname(__file__)) # Load all of the modules containing the challenge classes modules = [basename(path)[:-3] for path in modules] modules.sort() # Ensure that modules are in c1-c* order modules = [__import__(mod) for mod in modules] # Extract the challenge class from each module challengeClasses = [] for i in range(1, len(modules)+1): challengeClasses.append(getattr(modules[i-1], 'c' + str(i)))
from os.path import dirname, basename, isfile import glob import sys modules = glob.glob(dirname(__file__)+"/c*[0-9].py") sys.path.append(dirname(__file__)) # Load all of the modules containing the challenge classes modules = [basename(path)[:-3] for path in modules] modules.sort() # Ensure that modules are in c1-c* order modules = [__import__(mod) for mod in modules] # Extract the challenge class from each module challengeClasses = [] for i in range(1, len(modules)+1): try: challengeClasses.append(getattr(modules[i-1], 'c' + str(i))) except: continue
Fix bug in loading of c* modules
Fix bug in loading of c* modules
Python
mit
GunshipPenguin/billionaire_challenge,GunshipPenguin/billionaire_challenge
from os.path import dirname, basename, isfile import glob import sys modules = glob.glob(dirname(__file__)+"/c*[0-9].py") sys.path.append(dirname(__file__)) # Load all of the modules containing the challenge classes modules = [basename(path)[:-3] for path in modules] modules.sort() # Ensure that modules are in c1-c* order modules = [__import__(mod) for mod in modules] # Extract the challenge class from each module challengeClasses = [] for i in range(1, len(modules)+1): + try: - challengeClasses.append(getattr(modules[i-1], 'c' + str(i))) + challengeClasses.append(getattr(modules[i-1], 'c' + str(i))) + except: + continue
Fix bug in loading of c* modules
## Code Before: from os.path import dirname, basename, isfile import glob import sys modules = glob.glob(dirname(__file__)+"/c*[0-9].py") sys.path.append(dirname(__file__)) # Load all of the modules containing the challenge classes modules = [basename(path)[:-3] for path in modules] modules.sort() # Ensure that modules are in c1-c* order modules = [__import__(mod) for mod in modules] # Extract the challenge class from each module challengeClasses = [] for i in range(1, len(modules)+1): challengeClasses.append(getattr(modules[i-1], 'c' + str(i))) ## Instruction: Fix bug in loading of c* modules ## Code After: from os.path import dirname, basename, isfile import glob import sys modules = glob.glob(dirname(__file__)+"/c*[0-9].py") sys.path.append(dirname(__file__)) # Load all of the modules containing the challenge classes modules = [basename(path)[:-3] for path in modules] modules.sort() # Ensure that modules are in c1-c* order modules = [__import__(mod) for mod in modules] # Extract the challenge class from each module challengeClasses = [] for i in range(1, len(modules)+1): try: challengeClasses.append(getattr(modules[i-1], 'c' + str(i))) except: continue
from os.path import dirname, basename, isfile import glob import sys modules = glob.glob(dirname(__file__)+"/c*[0-9].py") sys.path.append(dirname(__file__)) # Load all of the modules containing the challenge classes modules = [basename(path)[:-3] for path in modules] modules.sort() # Ensure that modules are in c1-c* order modules = [__import__(mod) for mod in modules] # Extract the challenge class from each module challengeClasses = [] for i in range(1, len(modules)+1): + try: - challengeClasses.append(getattr(modules[i-1], 'c' + str(i))) + challengeClasses.append(getattr(modules[i-1], 'c' + str(i))) ? ++++ + except: + continue
4974f83d9ed1e085ef2daaeba4db56a4001055cf
comics/comics/ctrlaltdel.py
comics/comics/ctrlaltdel.py
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Ctrl+Alt+Del" language = "en" url = "http://www.cad-comic.com/cad/" start_date = "2002-10-23" rights = "Tim Buckley" class Crawler(CrawlerBase): history_capable_date = "2002-10-23" schedule = "Mo,We,Fr" time_zone = "US/Eastern" # Without User-Agent set, the server returns empty responses headers = {"User-Agent": "Mozilla/4.0"} def crawl(self, pub_date): page = self.parse_page( "http://www.cad-comic.com/cad/%s" % pub_date.strftime("%Y%m%d") ) url = page.src('img[src*="/comics/"]') title = page.alt('img[src*="/comics/"]') return CrawlerImage(url, title)
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Ctrl+Alt+Del" language = "en" url = "https://cad-comic.com/category/ctrl-alt-del/" start_date = "2002-10-23" rights = "Tim Buckley" class Crawler(CrawlerBase): # history_capable_date = "2002-10-23" history_capable_days = 20 schedule = "Mo,We,Fr" time_zone = "US/Eastern" # Without User-Agent set, the server returns empty responses headers = {"User-Agent": "Mozilla/4.0"} def crawl(self, pub_date): feed = self.parse_feed("https://cad-comic.com/feed/") for entry in feed.for_date(pub_date): url = entry.summary.src("img") title = entry.title return CrawlerImage(url, title)
Update "Ctrl+Alt+Del" after site change
Update "Ctrl+Alt+Del" after site change
Python
agpl-3.0
datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Ctrl+Alt+Del" language = "en" - url = "http://www.cad-comic.com/cad/" + url = "https://cad-comic.com/category/ctrl-alt-del/" start_date = "2002-10-23" rights = "Tim Buckley" class Crawler(CrawlerBase): - history_capable_date = "2002-10-23" + # history_capable_date = "2002-10-23" + history_capable_days = 20 schedule = "Mo,We,Fr" time_zone = "US/Eastern" # Without User-Agent set, the server returns empty responses headers = {"User-Agent": "Mozilla/4.0"} def crawl(self, pub_date): + feed = self.parse_feed("https://cad-comic.com/feed/") - page = self.parse_page( - "http://www.cad-comic.com/cad/%s" % pub_date.strftime("%Y%m%d") - ) - url = page.src('img[src*="/comics/"]') - title = page.alt('img[src*="/comics/"]') - return CrawlerImage(url, title) + for entry in feed.for_date(pub_date): + url = entry.summary.src("img") + title = entry.title + return CrawlerImage(url, title) +
Update "Ctrl+Alt+Del" after site change
## Code Before: from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Ctrl+Alt+Del" language = "en" url = "http://www.cad-comic.com/cad/" start_date = "2002-10-23" rights = "Tim Buckley" class Crawler(CrawlerBase): history_capable_date = "2002-10-23" schedule = "Mo,We,Fr" time_zone = "US/Eastern" # Without User-Agent set, the server returns empty responses headers = {"User-Agent": "Mozilla/4.0"} def crawl(self, pub_date): page = self.parse_page( "http://www.cad-comic.com/cad/%s" % pub_date.strftime("%Y%m%d") ) url = page.src('img[src*="/comics/"]') title = page.alt('img[src*="/comics/"]') return CrawlerImage(url, title) ## Instruction: Update "Ctrl+Alt+Del" after site change ## Code After: from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Ctrl+Alt+Del" language = "en" url = "https://cad-comic.com/category/ctrl-alt-del/" start_date = "2002-10-23" rights = "Tim Buckley" class Crawler(CrawlerBase): # history_capable_date = "2002-10-23" history_capable_days = 20 schedule = "Mo,We,Fr" time_zone = "US/Eastern" # Without User-Agent set, the server returns empty responses headers = {"User-Agent": "Mozilla/4.0"} def crawl(self, pub_date): feed = self.parse_feed("https://cad-comic.com/feed/") for entry in feed.for_date(pub_date): url = entry.summary.src("img") title = entry.title return CrawlerImage(url, title)
from comics.aggregator.crawler import CrawlerBase, CrawlerImage from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = "Ctrl+Alt+Del" language = "en" - url = "http://www.cad-comic.com/cad/" ? ---- + url = "https://cad-comic.com/category/ctrl-alt-del/" ? + ++++++++++++++++ ++ start_date = "2002-10-23" rights = "Tim Buckley" class Crawler(CrawlerBase): - history_capable_date = "2002-10-23" + # history_capable_date = "2002-10-23" ? ++ + history_capable_days = 20 schedule = "Mo,We,Fr" time_zone = "US/Eastern" # Without User-Agent set, the server returns empty responses headers = {"User-Agent": "Mozilla/4.0"} def crawl(self, pub_date): - page = self.parse_page( - "http://www.cad-comic.com/cad/%s" % pub_date.strftime("%Y%m%d") - ) - url = page.src('img[src*="/comics/"]') - title = page.alt('img[src*="/comics/"]') + feed = self.parse_feed("https://cad-comic.com/feed/") + + for entry in feed.for_date(pub_date): + url = entry.summary.src("img") + title = entry.title - return CrawlerImage(url, title) + return CrawlerImage(url, title) ? ++++