commit
stringlengths
40
40
old_file
stringlengths
4
234
new_file
stringlengths
4
234
old_contents
stringlengths
10
3.01k
new_contents
stringlengths
19
3.38k
subject
stringlengths
16
736
message
stringlengths
17
2.63k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
82.6k
config
stringclasses
4 values
content
stringlengths
134
4.41k
fuzzy_diff
stringlengths
29
3.44k
c8aec8f354cc1166e2f9e6d8e1fc9be454708c36
setup.py
setup.py
from os.path import exists from setuptools import setup setup(name='cachey', version='0.2.0', description='Caching mindful of computation/storage costs', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Topic :: Scientific/Engineering", ], url='http://github.com/dask/cachey/', maintainer='Matthew Rocklin', maintainer_email='[email protected]', license='BSD', keywords='', packages=['cachey'], python_requires='>=3.6', install_requires=list(open('requirements.txt').read().strip().split('\n')), long_description=(open('README.md').read() if exists('README.md') else ''), zip_safe=False)
from os.path import exists from setuptools import setup setup(name='cachey', version='0.2.0', description='Caching mindful of computation/storage costs', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Topic :: Scientific/Engineering", ], url='http://github.com/dask/cachey/', maintainer='Matthew Rocklin', maintainer_email='[email protected]', license='BSD', keywords='', packages=['cachey'], python_requires='>=3.6', install_requires=list(open('requirements.txt').read().strip().split('\n')), long_description=(open('README.md').read() if exists('README.md') else ''), long_description_content_type='text/markdown', zip_safe=False)
Update content type for description
DOC: Update content type for description PyPI rejects uploads that fail to render.
Python
bsd-3-clause
blaze/cachey
python
## Code Before: from os.path import exists from setuptools import setup setup(name='cachey', version='0.2.0', description='Caching mindful of computation/storage costs', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Topic :: Scientific/Engineering", ], url='http://github.com/dask/cachey/', maintainer='Matthew Rocklin', maintainer_email='[email protected]', license='BSD', keywords='', packages=['cachey'], python_requires='>=3.6', install_requires=list(open('requirements.txt').read().strip().split('\n')), long_description=(open('README.md').read() if exists('README.md') else ''), zip_safe=False) ## Instruction: DOC: Update content type for description PyPI rejects uploads that fail to render. ## Code After: from os.path import exists from setuptools import setup setup(name='cachey', version='0.2.0', description='Caching mindful of computation/storage costs', classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Topic :: Scientific/Engineering", ], url='http://github.com/dask/cachey/', maintainer='Matthew Rocklin', maintainer_email='[email protected]', license='BSD', keywords='', packages=['cachey'], python_requires='>=3.6', install_requires=list(open('requirements.txt').read().strip().split('\n')), long_description=(open('README.md').read() if exists('README.md') else ''), long_description_content_type='text/markdown', zip_safe=False)
... install_requires=list(open('requirements.txt').read().strip().split('\n')), long_description=(open('README.md').read() if exists('README.md') else ''), long_description_content_type='text/markdown', zip_safe=False) ...
00e5ca59b78be88293a9e41f4ad1f9283cc41021
src/main/java/com/royalrangers/controller/SubscribeController.java
src/main/java/com/royalrangers/controller/SubscribeController.java
package com.royalrangers.controller; import com.royalrangers.dto.ResponseResult; import com.royalrangers.dto.user.EmailDto; import com.royalrangers.service.SubscribeService; import com.royalrangers.utils.ResponseBuilder; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @Slf4j @RestController @RequestMapping("/subscribe") public class SubscribeController { @Autowired private SubscribeService subscribeService; @PostMapping @ApiOperation(value = "Create subscriber") public ResponseResult subscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Add subscriber: " + email); try { subscribeService.add(email); return ResponseBuilder.success(String.format("Email %s added to subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } @DeleteMapping @ApiOperation(value = "Delete subscriber") public ResponseResult unsubscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Remove subscriber: " + email); try { subscribeService.remove(email); return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } }
package com.royalrangers.controller; import com.royalrangers.dto.ResponseResult; import com.royalrangers.dto.user.EmailDto; import com.royalrangers.service.SubscribeService; import com.royalrangers.utils.ResponseBuilder; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @Slf4j @RestController @RequestMapping("/subscribe") public class SubscribeController { @Autowired private SubscribeService subscribeService; @PostMapping @ApiOperation(value = "Add email to subscribers list") public ResponseResult subscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Add subscriber: " + email); try { subscribeService.add(email); return ResponseBuilder.success(String.format("Email %s added to subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } @DeleteMapping @ApiOperation(value = "Remove email from subscribers list") public ResponseResult unsubscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Remove subscriber: " + email); try { subscribeService.remove(email); return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } }
Fix API description for Subscribe Controller
Fix API description for Subscribe Controller
Java
apache-2.0
royalrangers-ck/rr-api,royalrangers-ck/rr-api
java
## Code Before: package com.royalrangers.controller; import com.royalrangers.dto.ResponseResult; import com.royalrangers.dto.user.EmailDto; import com.royalrangers.service.SubscribeService; import com.royalrangers.utils.ResponseBuilder; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @Slf4j @RestController @RequestMapping("/subscribe") public class SubscribeController { @Autowired private SubscribeService subscribeService; @PostMapping @ApiOperation(value = "Create subscriber") public ResponseResult subscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Add subscriber: " + email); try { subscribeService.add(email); return ResponseBuilder.success(String.format("Email %s added to subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } @DeleteMapping @ApiOperation(value = "Delete subscriber") public ResponseResult unsubscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Remove subscriber: " + email); try { subscribeService.remove(email); return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } } ## Instruction: Fix API description for Subscribe Controller ## Code After: package com.royalrangers.controller; import com.royalrangers.dto.ResponseResult; import com.royalrangers.dto.user.EmailDto; import com.royalrangers.service.SubscribeService; import com.royalrangers.utils.ResponseBuilder; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @Slf4j @RestController @RequestMapping("/subscribe") public class SubscribeController { @Autowired private SubscribeService subscribeService; @PostMapping @ApiOperation(value = "Add email to subscribers list") public ResponseResult subscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Add subscriber: " + email); try { subscribeService.add(email); return ResponseBuilder.success(String.format("Email %s added to subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } @DeleteMapping @ApiOperation(value = "Remove email from subscribers list") public ResponseResult unsubscribe(@RequestBody EmailDto request) { String email = request.getMail(); log.info("Remove subscriber: " + email); try { subscribeService.remove(email); return ResponseBuilder.success(String.format("Email %s removed from subscribers list", email)); } catch (Exception e) { return ResponseBuilder.fail(e.getMessage()); } } }
# ... existing code ... private SubscribeService subscribeService; @PostMapping @ApiOperation(value = "Add email to subscribers list") public ResponseResult subscribe(@RequestBody EmailDto request) { String email = request.getMail(); # ... modified code ... } @DeleteMapping @ApiOperation(value = "Remove email from subscribers list") public ResponseResult unsubscribe(@RequestBody EmailDto request) { String email = request.getMail(); # ... rest of the code ...
939998db349c364aa0f5ba4705d4feb2da7104d5
nn/flags.py
nn/flags.py
import functools import tensorflow as tf FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string("batch-size", 64, "") tf.app.flags.DEFINE_float("dropout-prob", 0, "") tf.app.flags.DEFINE_string("word-file", None, "") tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "") tf.app.flags.DEFINE_integer("queue-capacity", 2, "") tf.app.flags.DEFINE_string("length-boundaries", "", "") tf.app.flags.DEFINE_string("rnn-cell", "ln_lstm", "Default RNN cell") tf.app.flags.DEFINE_string("float32", "", "") @functools.lru_cache() def words(): with open(tf.app.flags.FLAGS.word_file) as file_: return sorted([line.strip() for line in file_.readlines()]) @functools.lru_cache() def word_indices(): # 0 -> null, 1 -> unknown return { word: index + 2 for index, word in enumerate(flags.words()) } @functools.lru_cache() def word_space_size(): return len(words()) def rnn_cell(): from .rnn import cell return getattr(cell, FLAGS.rnn_cell) def float_type(): return getattr(tf, FLAGS.float_type)
import functools import tensorflow as tf FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string("batch-size", 64, "") tf.app.flags.DEFINE_float("dropout-prob", 0, "") tf.app.flags.DEFINE_string("word-file", None, "") tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "") tf.app.flags.DEFINE_integer("queue-capacity", 2, "") tf.app.flags.DEFINE_string("length-boundaries", "", "") tf.app.flags.DEFINE_string("rnn-cell", "ln_lstm", "Default RNN cell") tf.app.flags.DEFINE_string("float-type", "float32", "") @functools.lru_cache() def words(): with open(tf.app.flags.FLAGS.word_file) as file_: return sorted([line.strip() for line in file_.readlines()]) @functools.lru_cache() def word_indices(): # 0 -> null, 1 -> unknown return { word: index + 2 for index, word in enumerate(flags.words()) } @functools.lru_cache() def word_space_size(): return len(words()) def rnn_cell(): from .rnn import cell return getattr(cell, FLAGS.rnn_cell) def float_type(): return getattr(tf, FLAGS.float_type)
Fix float type flag definition
Fix float type flag definition
Python
unlicense
raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten
python
## Code Before: import functools import tensorflow as tf FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string("batch-size", 64, "") tf.app.flags.DEFINE_float("dropout-prob", 0, "") tf.app.flags.DEFINE_string("word-file", None, "") tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "") tf.app.flags.DEFINE_integer("queue-capacity", 2, "") tf.app.flags.DEFINE_string("length-boundaries", "", "") tf.app.flags.DEFINE_string("rnn-cell", "ln_lstm", "Default RNN cell") tf.app.flags.DEFINE_string("float32", "", "") @functools.lru_cache() def words(): with open(tf.app.flags.FLAGS.word_file) as file_: return sorted([line.strip() for line in file_.readlines()]) @functools.lru_cache() def word_indices(): # 0 -> null, 1 -> unknown return { word: index + 2 for index, word in enumerate(flags.words()) } @functools.lru_cache() def word_space_size(): return len(words()) def rnn_cell(): from .rnn import cell return getattr(cell, FLAGS.rnn_cell) def float_type(): return getattr(tf, FLAGS.float_type) ## Instruction: Fix float type flag definition ## Code After: import functools import tensorflow as tf FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string("batch-size", 64, "") tf.app.flags.DEFINE_float("dropout-prob", 0, "") tf.app.flags.DEFINE_string("word-file", None, "") tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "") tf.app.flags.DEFINE_integer("queue-capacity", 2, "") tf.app.flags.DEFINE_string("length-boundaries", "", "") tf.app.flags.DEFINE_string("rnn-cell", "ln_lstm", "Default RNN cell") tf.app.flags.DEFINE_string("float-type", "float32", "") @functools.lru_cache() def words(): with open(tf.app.flags.FLAGS.word_file) as file_: return sorted([line.strip() for line in file_.readlines()]) @functools.lru_cache() def word_indices(): # 0 -> null, 1 -> unknown return { word: index + 2 for index, word in enumerate(flags.words()) } @functools.lru_cache() def word_space_size(): return len(words()) def rnn_cell(): from .rnn import cell return getattr(cell, FLAGS.rnn_cell) def float_type(): return getattr(tf, FLAGS.float_type)
... tf.app.flags.DEFINE_integer("queue-capacity", 2, "") tf.app.flags.DEFINE_string("length-boundaries", "", "") tf.app.flags.DEFINE_string("rnn-cell", "ln_lstm", "Default RNN cell") tf.app.flags.DEFINE_string("float-type", "float32", "") @functools.lru_cache() ...
d540b7c14b9411acdedfe41a77fd4911ef2eb660
src/cmdtree/tests/functional/test_command.py
src/cmdtree/tests/functional/test_command.py
from cmdtree import INT from cmdtree import command, argument, option @argument("host", help="server listen address") @option("reload", is_flag=True, help="if auto-reload on") @option("port", help="server port", type=INT, default=8888) @command(help="run a http server on given address") def run_server(host, reload, port): return host, port, reload def test_should_return_given_argument(): from cmdtree import entry result = entry( ["run_server", "host", "--reload", "--port", "8888"] ) assert result == ("host", 8888, True)
import pytest from cmdtree import INT from cmdtree import command, argument, option @argument("host", help="server listen address") @option("reload", is_flag=True, help="if auto-reload on") @option("port", help="server port", type=INT, default=8888) @command(help="run a http server on given address") def run_server(host, reload, port): return host, port, reload @command(help="run a http server on given address") @argument("host", help="server listen address") @option("port", help="server port", type=INT, default=8888) def order(port, host): return host, port def test_should_return_given_argument(): from cmdtree import entry result = entry( ["run_server", "host", "--reload", "--port", "8888"] ) assert result == ("host", 8888, True) def test_should_reverse_decorator_order_has_no_side_effect(): from cmdtree import entry result = entry( ["order", "host", "--port", "8888"] ) assert result == ("host", 8888)
Add functional test for reverse decorator order
Update: Add functional test for reverse decorator order
Python
mit
winkidney/cmdtree,winkidney/cmdtree
python
## Code Before: from cmdtree import INT from cmdtree import command, argument, option @argument("host", help="server listen address") @option("reload", is_flag=True, help="if auto-reload on") @option("port", help="server port", type=INT, default=8888) @command(help="run a http server on given address") def run_server(host, reload, port): return host, port, reload def test_should_return_given_argument(): from cmdtree import entry result = entry( ["run_server", "host", "--reload", "--port", "8888"] ) assert result == ("host", 8888, True) ## Instruction: Update: Add functional test for reverse decorator order ## Code After: import pytest from cmdtree import INT from cmdtree import command, argument, option @argument("host", help="server listen address") @option("reload", is_flag=True, help="if auto-reload on") @option("port", help="server port", type=INT, default=8888) @command(help="run a http server on given address") def run_server(host, reload, port): return host, port, reload @command(help="run a http server on given address") @argument("host", help="server listen address") @option("port", help="server port", type=INT, default=8888) def order(port, host): return host, port def test_should_return_given_argument(): from cmdtree import entry result = entry( ["run_server", "host", "--reload", "--port", "8888"] ) assert result == ("host", 8888, True) def test_should_reverse_decorator_order_has_no_side_effect(): from cmdtree import entry result = entry( ["order", "host", "--port", "8888"] ) assert result == ("host", 8888)
# ... existing code ... import pytest from cmdtree import INT from cmdtree import command, argument, option # ... modified code ... return host, port, reload @command(help="run a http server on given address") @argument("host", help="server listen address") @option("port", help="server port", type=INT, default=8888) def order(port, host): return host, port def test_should_return_given_argument(): from cmdtree import entry result = entry( ... ["run_server", "host", "--reload", "--port", "8888"] ) assert result == ("host", 8888, True) def test_should_reverse_decorator_order_has_no_side_effect(): from cmdtree import entry result = entry( ["order", "host", "--port", "8888"] ) assert result == ("host", 8888) # ... rest of the code ...
030f8fec423acb99574bc2a9b8760e3b9a8e0025
tests/apptest.py
tests/apptest.py
import pytest import os from PyQt4.QtGui import * from PyQt4.QtCore import * from mp3wav.application import Mp3WavApp from mp3wav.exceptions.fileexception import FileTypeException from mp3wav.exceptions.libraryexception import LibraryException from mp3wav.exceptions.filenotexistexception import FileNotExistException from mp3wav.exceptions.samefileexception import SameFileException from mp3wav.exceptions.overwriteexception import OverWriteException def windowTest(qtbot): testapp = Mp3WavApp() testapp.show() qtbot.addWidget(testapp) assert testapp.isVisible() assert testapp.close() def correctConvertTest(qtbot, tmpdir): testapp = Mp3WavApp() qtbot.addWidget(testapp) infile = tmpdir.mkdir("files").join("demo.mp3") infile.write("something") testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3"))) testapp.outputFileLine.setText(str(tmpdir.join('files'))) testapp.outputFileLineName.setText(str(tmpdir.join('files', 'demo.wav'))) qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton) assert os.path.exists(str(tmpdir.join('files', 'demo.wav')))
import pytest import os from PyQt4.QtGui import * from PyQt4.QtCore import * from mp3wav.application import Mp3WavApp from mp3wav.exceptions.fileexception import FileTypeException from mp3wav.exceptions.libraryexception import LibraryException from mp3wav.exceptions.filenotexistexception import FileNotExistException from mp3wav.exceptions.samefileexception import SameFileException from mp3wav.exceptions.overwriteexception import OverWriteException def windowTest(qtbot): testapp = Mp3WavApp() testapp.show() qtbot.addWidget(testapp) assert testapp.isVisible() assert testapp.close() def fileTypeTest(qtbot, tmpdir): testapp = Mp3WavApp() qtbot.addWidget(testapp) infile = tmpdir.mkdir("files").join("demo.mp3") infile.write("something") testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3"))) testapp.outputFileLine.setText(str(tmpdir.join('files'))) testapp.outputFileLineName.setText('demo.wave') with pytest.raises(FileTypeException): qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton)
Test modified to check for exception in lack of ffmpeg in travis
Test modified to check for exception in lack of ffmpeg in travis
Python
mit
kapilgarg1996/mp3wav
python
## Code Before: import pytest import os from PyQt4.QtGui import * from PyQt4.QtCore import * from mp3wav.application import Mp3WavApp from mp3wav.exceptions.fileexception import FileTypeException from mp3wav.exceptions.libraryexception import LibraryException from mp3wav.exceptions.filenotexistexception import FileNotExistException from mp3wav.exceptions.samefileexception import SameFileException from mp3wav.exceptions.overwriteexception import OverWriteException def windowTest(qtbot): testapp = Mp3WavApp() testapp.show() qtbot.addWidget(testapp) assert testapp.isVisible() assert testapp.close() def correctConvertTest(qtbot, tmpdir): testapp = Mp3WavApp() qtbot.addWidget(testapp) infile = tmpdir.mkdir("files").join("demo.mp3") infile.write("something") testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3"))) testapp.outputFileLine.setText(str(tmpdir.join('files'))) testapp.outputFileLineName.setText(str(tmpdir.join('files', 'demo.wav'))) qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton) assert os.path.exists(str(tmpdir.join('files', 'demo.wav'))) ## Instruction: Test modified to check for exception in lack of ffmpeg in travis ## Code After: import pytest import os from PyQt4.QtGui import * from PyQt4.QtCore import * from mp3wav.application import Mp3WavApp from mp3wav.exceptions.fileexception import FileTypeException from mp3wav.exceptions.libraryexception import LibraryException from mp3wav.exceptions.filenotexistexception import FileNotExistException from mp3wav.exceptions.samefileexception import SameFileException from mp3wav.exceptions.overwriteexception import OverWriteException def windowTest(qtbot): testapp = Mp3WavApp() testapp.show() qtbot.addWidget(testapp) assert testapp.isVisible() assert testapp.close() def fileTypeTest(qtbot, tmpdir): testapp = Mp3WavApp() qtbot.addWidget(testapp) infile = tmpdir.mkdir("files").join("demo.mp3") infile.write("something") testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3"))) testapp.outputFileLine.setText(str(tmpdir.join('files'))) testapp.outputFileLineName.setText('demo.wave') with pytest.raises(FileTypeException): qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton)
// ... existing code ... assert testapp.isVisible() assert testapp.close() def fileTypeTest(qtbot, tmpdir): testapp = Mp3WavApp() qtbot.addWidget(testapp) infile = tmpdir.mkdir("files").join("demo.mp3") // ... modified code ... infile.write("something") testapp.inputFileLine.setText(str(tmpdir.join("files", "demo.mp3"))) testapp.outputFileLine.setText(str(tmpdir.join('files'))) testapp.outputFileLineName.setText('demo.wave') with pytest.raises(FileTypeException): qtbot.mouseClick(testapp.conversionButton, Qt.LeftButton) // ... rest of the code ...
82973662e9cc8234e741d7595c95137df77296bb
tests/unit/utils/vt_test.py
tests/unit/utils/vt_test.py
''' :codeauthor: :email:`Pedro Algarvio ([email protected])` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False)
''' :codeauthor: :email:`Pedro Algarvio ([email protected])` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' self.skipTest('The code is not mature enough. Test disabled.') cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False)
Disable the VT test, the code ain't mature enough.
Disable the VT test, the code ain't mature enough.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
python
## Code Before: ''' :codeauthor: :email:`Pedro Algarvio ([email protected])` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False) ## Instruction: Disable the VT test, the code ain't mature enough. ## Code After: ''' :codeauthor: :email:`Pedro Algarvio ([email protected])` :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.unit.utils.vt_test ~~~~~~~~~~~~~~~~~~~~~~~~ VirtualTerminal tests ''' # Import python libs import random # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs from salt.utils import vt class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' self.skipTest('The code is not mature enough. Test disabled.') cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', shell=True, cols=cols ) # First the assertion self.assertEqual( terminal.getwinsize(), (24, cols) ) # Then wait for the terminal child to exit terminal.wait() if __name__ == '__main__': from integration import run_tests run_tests(VTTestCase, needs_daemon=False)
# ... existing code ... class VTTestCase(TestCase): def test_vt_size(self): '''Confirm that the terminal size is being set''' self.skipTest('The code is not mature enough. Test disabled.') cols = random.choice(range(80, 250)) terminal = vt.Terminal( 'echo Foo!', # ... rest of the code ...
ebb0c49aa4b45a4778ec270c99b872873d4d37a6
starlight.h
starlight.h
int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } int Strnicmp(const char* str1, const char* str2, int count) { int d = 0; while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } return d; } #endif #ifdef _MSC_VER #define SL_CALL __vectorcall #else #define SL_CALL #endif #define COUNT_OF(X) (sizeof(X) / sizeof((X)[0])) #define ZERO_MEM(X, Y) (memset(X, 0, Y));
int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } int Strnicmp(const char* str1, const char* str2, int count) { int d = 0; while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } return d; } #endif #if defined(_MSC_VER) && (_MSC_VER >= 1800) #define SL_CALL __vectorcall #else #define SL_CALL #endif #define COUNT_OF(X) (sizeof(X) / sizeof((X)[0])) #define ZERO_MEM(X, Y) (memset(X, 0, Y));
Remove __vectorcall calling convention on older versions of MSVC++
Remove __vectorcall calling convention on older versions of MSVC++
C
mit
darkedge/starlight,darkedge/starlight,darkedge/starlight
c
## Code Before: int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } int Strnicmp(const char* str1, const char* str2, int count) { int d = 0; while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } return d; } #endif #ifdef _MSC_VER #define SL_CALL __vectorcall #else #define SL_CALL #endif #define COUNT_OF(X) (sizeof(X) / sizeof((X)[0])) #define ZERO_MEM(X, Y) (memset(X, 0, Y)); ## Instruction: Remove __vectorcall calling convention on older versions of MSVC++ ## Code After: int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } int Strnicmp(const char* str1, const char* str2, int count) { int d = 0; while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } return d; } #endif #if defined(_MSC_VER) && (_MSC_VER >= 1800) #define SL_CALL __vectorcall #else #define SL_CALL #endif #define COUNT_OF(X) (sizeof(X) / sizeof((X)[0])) #define ZERO_MEM(X, Y) (memset(X, 0, Y));
// ... existing code ... } #endif #if defined(_MSC_VER) && (_MSC_VER >= 1800) #define SL_CALL __vectorcall #else #define SL_CALL // ... rest of the code ...
2995accb21d9b8c45792d12402470cfcf322d6a1
models/phase3_eval/process_sparser.py
models/phase3_eval/process_sparser.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import os import glob from indra import sparser base_folder = os.path.join(os.environ['HOME'], 'data/darpa/phase3_eval/sources/sparser-20170210') def get_file_names(base_dir): fnames = glob.glob(os.path.join(base_dir, '*.xml')) return fnames def get_file_stmts(fname): with open(fname, 'rb') as fh: xml_bytes = fh.read() xml_bytes = xml_bytes.replace(b'hmsid', b'pmid') sp = sparser.process_xml(xml_bytes) if sp is None: print('ERROR: Could not process %s' % fname.split('/')[-1]) print('----') return [] return sp.statements def read_stmts(folder): fnames = get_file_names(folder) all_stmts = [] for fname in fnames: st = get_file_stmts(fname) all_stmts += st return all_stmts if __name__ == '__main__': stmts = read_stmts(base_folder)
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import os import glob from indra import sparser base_folder = os.path.join(os.environ['HOME'], 'data/darpa/phase3_eval/sources/sparser-20170330') def get_file_names(base_dir): fnames = glob.glob(os.path.join(base_dir, '*.xml')) return fnames def get_file_stmts(fname): with open(fname, 'rb') as fh: print(fname) xml_bytes = fh.read() sp = sparser.process_xml(xml_bytes) if sp is None: print('ERROR: Could not process %s' % fname.split('/')[-1]) print('----') return [] return sp.statements def read_stmts(folder): fnames = get_file_names(folder) all_stmts = [] for fname in fnames: st = get_file_stmts(fname) all_stmts += st return all_stmts if __name__ == '__main__': stmts = read_stmts(base_folder)
Update Sparser script for phase3
Update Sparser script for phase3
Python
bsd-2-clause
johnbachman/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,johnbachman/indra,pvtodorov/indra,bgyori/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy
python
## Code Before: from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import os import glob from indra import sparser base_folder = os.path.join(os.environ['HOME'], 'data/darpa/phase3_eval/sources/sparser-20170210') def get_file_names(base_dir): fnames = glob.glob(os.path.join(base_dir, '*.xml')) return fnames def get_file_stmts(fname): with open(fname, 'rb') as fh: xml_bytes = fh.read() xml_bytes = xml_bytes.replace(b'hmsid', b'pmid') sp = sparser.process_xml(xml_bytes) if sp is None: print('ERROR: Could not process %s' % fname.split('/')[-1]) print('----') return [] return sp.statements def read_stmts(folder): fnames = get_file_names(folder) all_stmts = [] for fname in fnames: st = get_file_stmts(fname) all_stmts += st return all_stmts if __name__ == '__main__': stmts = read_stmts(base_folder) ## Instruction: Update Sparser script for phase3 ## Code After: from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import os import glob from indra import sparser base_folder = os.path.join(os.environ['HOME'], 'data/darpa/phase3_eval/sources/sparser-20170330') def get_file_names(base_dir): fnames = glob.glob(os.path.join(base_dir, '*.xml')) return fnames def get_file_stmts(fname): with open(fname, 'rb') as fh: print(fname) xml_bytes = fh.read() sp = sparser.process_xml(xml_bytes) if sp is None: print('ERROR: Could not process %s' % fname.split('/')[-1]) print('----') return [] return sp.statements def read_stmts(folder): fnames = get_file_names(folder) all_stmts = [] for fname in fnames: st = get_file_stmts(fname) all_stmts += st return all_stmts if __name__ == '__main__': stmts = read_stmts(base_folder)
// ... existing code ... from indra import sparser base_folder = os.path.join(os.environ['HOME'], 'data/darpa/phase3_eval/sources/sparser-20170330') def get_file_names(base_dir): fnames = glob.glob(os.path.join(base_dir, '*.xml')) // ... modified code ... def get_file_stmts(fname): with open(fname, 'rb') as fh: print(fname) xml_bytes = fh.read() sp = sparser.process_xml(xml_bytes) if sp is None: print('ERROR: Could not process %s' % fname.split('/')[-1]) // ... rest of the code ...
82a080813c8def8caace0d3b11079cfa20c72766
src/modules/conf_randr/e_smart_monitor.h
src/modules/conf_randr/e_smart_monitor.h
Evas_Object *e_smart_monitor_add(Evas *evas); # endif #endif
Evas_Object *e_smart_monitor_add(Evas *evas); void e_smart_monitor_crtc_set(Evas_Object *obj, E_Randr_Crtc_Config *crtc); void e_smart_monitor_output_set(Evas_Object *obj, E_Randr_Output_Config *output); # endif #endif
Add function prototypes for setting monitor crtc and output config.
Add function prototypes for setting monitor crtc and output config. Signed-off-by: Christopher Michael <[email protected]> SVN revision: 84129
C
bsd-2-clause
tasn/enlightenment,rvandegrift/e,rvandegrift/e,rvandegrift/e,FlorentRevest/Enlightenment,tizenorg/platform.upstream.enlightenment,tasn/enlightenment,tasn/enlightenment,tizenorg/platform.upstream.enlightenment,FlorentRevest/Enlightenment,FlorentRevest/Enlightenment,tizenorg/platform.upstream.enlightenment
c
## Code Before: Evas_Object *e_smart_monitor_add(Evas *evas); # endif #endif ## Instruction: Add function prototypes for setting monitor crtc and output config. Signed-off-by: Christopher Michael <[email protected]> SVN revision: 84129 ## Code After: Evas_Object *e_smart_monitor_add(Evas *evas); void e_smart_monitor_crtc_set(Evas_Object *obj, E_Randr_Crtc_Config *crtc); void e_smart_monitor_output_set(Evas_Object *obj, E_Randr_Output_Config *output); # endif #endif
# ... existing code ... Evas_Object *e_smart_monitor_add(Evas *evas); void e_smart_monitor_crtc_set(Evas_Object *obj, E_Randr_Crtc_Config *crtc); void e_smart_monitor_output_set(Evas_Object *obj, E_Randr_Output_Config *output); # endif #endif # ... rest of the code ...
6067e96b0c5462f9d3e9391cc3193a28ba7ad808
DebianChangesBot/mailparsers/security_announce.py
DebianChangesBot/mailparsers/security_announce.py
from DebianChangesBot import MailParser class SecurityAnnounce(MailParser): def parse(self, msg): if self._get_header(msg, 'List-Id') != '<debian-security-announce.lists.debian.org>': return False fmt = SecurityAnnounceFormatter() data = { 'dsa_number' : None, 'package' : None, 'problem' : None, 'year' : None, 'url' : None, } m = re.match(r'^\[SECURITY\] \[DSA ([-\d]+)\] New (.*?) packages fix (.*)$', self._get_header(msg, 'Subject')) if m: fmt.dsa_number = m.group(1) fmt.package = m.group(2) fmt.problem = m.group(3) else: return False m = re.match(r'.*(20\d\d)', self._get_header(msg, 'Date')) if m: data['year'] = m.group(1) else: return False data['url'] = "http://www.debian.org/security/%s/dsa-%s" % (data['year'], re.sub(r'-\d+$', '', data['dsa_number'])) data = self._tidy_data(data) for k, v in data.iteritems(): data[k] = str(v.decode('ascii')) return colourise(_("[red][Security][reset] ([yellow]DSA-%(dsa_number)s[reset]) - New [green]%(package)s[reset] packages fix %(problem)s. %(url)s") % data)
from DebianChangesBot import MailParser class SecurityAnnounce(MailParser): def parse(self, msg): if self._get_header(msg, 'List-Id') != '<debian-security-announce.lists.debian.org>': return None fmt = SecurityAnnounceFormatter() m = re.match(r'^\[SECURITY\] \[DSA ([-\d]+)\] New (.*?) packages fix (.*)$', self._get_header(msg, 'Subject')) if m: fmt.dsa_number = m.group(1) fmt.package = m.group(2) fmt.problem = m.group(3) m = re.match(r'.*(20\d\d)', self._get_header(msg, 'Date')) if m: fmt.year = m.group(1) return fmt
Make formatter example more realistic
Make formatter example more realistic Signed-off-by: Chris Lamb <[email protected]>
Python
agpl-3.0
lamby/debian-devel-changes-bot,lamby/debian-devel-changes-bot,xtaran/debian-devel-changes-bot,sebastinas/debian-devel-changes-bot,lamby/debian-devel-changes-bot,xtaran/debian-devel-changes-bot
python
## Code Before: from DebianChangesBot import MailParser class SecurityAnnounce(MailParser): def parse(self, msg): if self._get_header(msg, 'List-Id') != '<debian-security-announce.lists.debian.org>': return False fmt = SecurityAnnounceFormatter() data = { 'dsa_number' : None, 'package' : None, 'problem' : None, 'year' : None, 'url' : None, } m = re.match(r'^\[SECURITY\] \[DSA ([-\d]+)\] New (.*?) packages fix (.*)$', self._get_header(msg, 'Subject')) if m: fmt.dsa_number = m.group(1) fmt.package = m.group(2) fmt.problem = m.group(3) else: return False m = re.match(r'.*(20\d\d)', self._get_header(msg, 'Date')) if m: data['year'] = m.group(1) else: return False data['url'] = "http://www.debian.org/security/%s/dsa-%s" % (data['year'], re.sub(r'-\d+$', '', data['dsa_number'])) data = self._tidy_data(data) for k, v in data.iteritems(): data[k] = str(v.decode('ascii')) return colourise(_("[red][Security][reset] ([yellow]DSA-%(dsa_number)s[reset]) - New [green]%(package)s[reset] packages fix %(problem)s. %(url)s") % data) ## Instruction: Make formatter example more realistic Signed-off-by: Chris Lamb <[email protected]> ## Code After: from DebianChangesBot import MailParser class SecurityAnnounce(MailParser): def parse(self, msg): if self._get_header(msg, 'List-Id') != '<debian-security-announce.lists.debian.org>': return None fmt = SecurityAnnounceFormatter() m = re.match(r'^\[SECURITY\] \[DSA ([-\d]+)\] New (.*?) packages fix (.*)$', self._get_header(msg, 'Subject')) if m: fmt.dsa_number = m.group(1) fmt.package = m.group(2) fmt.problem = m.group(3) m = re.match(r'.*(20\d\d)', self._get_header(msg, 'Date')) if m: fmt.year = m.group(1) return fmt
... def parse(self, msg): if self._get_header(msg, 'List-Id') != '<debian-security-announce.lists.debian.org>': return None fmt = SecurityAnnounceFormatter() m = re.match(r'^\[SECURITY\] \[DSA ([-\d]+)\] New (.*?) packages fix (.*)$', self._get_header(msg, 'Subject')) if m: ... fmt.dsa_number = m.group(1) fmt.package = m.group(2) fmt.problem = m.group(3) m = re.match(r'.*(20\d\d)', self._get_header(msg, 'Date')) if m: fmt.year = m.group(1) return fmt ...
597aa268386eb4adb5f82d11046b11a2a13693b8
composer-c1x/src/main/java/io/piano/android/composer/c1x/ShowRecommendationsController.kt
composer-c1x/src/main/java/io/piano/android/composer/c1x/ShowRecommendationsController.kt
package io.piano.android.composer.c1x import android.annotation.SuppressLint import android.webkit.WebView import io.piano.android.composer.model.Event import io.piano.android.composer.model.events.ShowRecommendations import io.piano.android.showhelper.BaseShowController class ShowRecommendationsController(event: Event<ShowRecommendations>) : BaseShowController<ShowRecommendations, WidgetJs>( event.eventData, with(event.eventData) { WidgetJs(widgetId, siteId) } ) { private val trackingId = event.eventExecutionContext.trackingId override val url = URL override val fragmentTag = FRAGMENT_TAG override val fragmentProvider = { with(eventData) { ShowRecommendationsDialogFragment(widgetId, siteId, trackingId) } } override fun close(data: String?) = jsInterface.close() override fun WebView.configure() = prepare(jsInterface) companion object { private const val FRAGMENT_TAG = "ShowRecommendationsDialogFragment" private const val JAVASCRIPT_INTERFACE = "cXNative" internal const val URL = "https://cdn.cxense.com/recommendations.html" @SuppressLint("SetJavaScriptEnabled") internal fun WebView.prepare( jsInterface: WidgetJs, dialogFragment: ShowRecommendationsDialogFragment? = null ) { settings.javaScriptEnabled = true jsInterface.init(dialogFragment, this) addJavascriptInterface(jsInterface, JAVASCRIPT_INTERFACE) } } }
package io.piano.android.composer.c1x import android.annotation.SuppressLint import android.webkit.WebView import io.piano.android.composer.model.Event import io.piano.android.composer.model.events.ShowRecommendations import io.piano.android.showhelper.BaseShowController class ShowRecommendationsController(event: Event<ShowRecommendations>) : BaseShowController<ShowRecommendations, WidgetJs>( event.eventData, with(event.eventData) { WidgetJs(widgetId, siteId) } ) { private val trackingId = event.eventExecutionContext.trackingId override val url = URL override val fragmentTag = FRAGMENT_TAG override val fragmentProvider = { with(eventData) { ShowRecommendationsDialogFragment(widgetId, siteId, trackingId) } } override fun close(data: String?) = jsInterface.close() override fun WebView.configure() = prepare(jsInterface) companion object { private const val FRAGMENT_TAG = "ShowRecommendationsDialogFragment" private const val JAVASCRIPT_INTERFACE = "cXNative" internal const val URL = "https://cdn.cxense.com/recommendations.html" @SuppressLint("SetJavaScriptEnabled") internal fun WebView.prepare( jsInterface: WidgetJs, dialogFragment: ShowRecommendationsDialogFragment? = null ) { settings.domStorageEnabled = true settings.javaScriptEnabled = true jsInterface.init(dialogFragment, this) addJavascriptInterface(jsInterface, JAVASCRIPT_INTERFACE) } } }
Fix access to local storage for cx.js
Fix access to local storage for cx.js
Kotlin
apache-2.0
tinypass/piano-sdk-for-android
kotlin
## Code Before: package io.piano.android.composer.c1x import android.annotation.SuppressLint import android.webkit.WebView import io.piano.android.composer.model.Event import io.piano.android.composer.model.events.ShowRecommendations import io.piano.android.showhelper.BaseShowController class ShowRecommendationsController(event: Event<ShowRecommendations>) : BaseShowController<ShowRecommendations, WidgetJs>( event.eventData, with(event.eventData) { WidgetJs(widgetId, siteId) } ) { private val trackingId = event.eventExecutionContext.trackingId override val url = URL override val fragmentTag = FRAGMENT_TAG override val fragmentProvider = { with(eventData) { ShowRecommendationsDialogFragment(widgetId, siteId, trackingId) } } override fun close(data: String?) = jsInterface.close() override fun WebView.configure() = prepare(jsInterface) companion object { private const val FRAGMENT_TAG = "ShowRecommendationsDialogFragment" private const val JAVASCRIPT_INTERFACE = "cXNative" internal const val URL = "https://cdn.cxense.com/recommendations.html" @SuppressLint("SetJavaScriptEnabled") internal fun WebView.prepare( jsInterface: WidgetJs, dialogFragment: ShowRecommendationsDialogFragment? = null ) { settings.javaScriptEnabled = true jsInterface.init(dialogFragment, this) addJavascriptInterface(jsInterface, JAVASCRIPT_INTERFACE) } } } ## Instruction: Fix access to local storage for cx.js ## Code After: package io.piano.android.composer.c1x import android.annotation.SuppressLint import android.webkit.WebView import io.piano.android.composer.model.Event import io.piano.android.composer.model.events.ShowRecommendations import io.piano.android.showhelper.BaseShowController class ShowRecommendationsController(event: Event<ShowRecommendations>) : BaseShowController<ShowRecommendations, WidgetJs>( event.eventData, with(event.eventData) { WidgetJs(widgetId, siteId) } ) { private val trackingId = event.eventExecutionContext.trackingId override val url = URL override val fragmentTag = FRAGMENT_TAG override val fragmentProvider = { with(eventData) { ShowRecommendationsDialogFragment(widgetId, siteId, trackingId) } } override fun close(data: String?) = jsInterface.close() override fun WebView.configure() = prepare(jsInterface) companion object { private const val FRAGMENT_TAG = "ShowRecommendationsDialogFragment" private const val JAVASCRIPT_INTERFACE = "cXNative" internal const val URL = "https://cdn.cxense.com/recommendations.html" @SuppressLint("SetJavaScriptEnabled") internal fun WebView.prepare( jsInterface: WidgetJs, dialogFragment: ShowRecommendationsDialogFragment? = null ) { settings.domStorageEnabled = true settings.javaScriptEnabled = true jsInterface.init(dialogFragment, this) addJavascriptInterface(jsInterface, JAVASCRIPT_INTERFACE) } } }
// ... existing code ... jsInterface: WidgetJs, dialogFragment: ShowRecommendationsDialogFragment? = null ) { settings.domStorageEnabled = true settings.javaScriptEnabled = true jsInterface.init(dialogFragment, this) addJavascriptInterface(jsInterface, JAVASCRIPT_INTERFACE) // ... rest of the code ...
4f9735afe464ad7e87a6316197db2d6c320ad67a
src/main/java/de/prob2/ui/consoles/b/BConsole.java
src/main/java/de/prob2/ui/consoles/b/BConsole.java
package de.prob2.ui.consoles.b; import java.io.File; import java.util.ResourceBundle; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob2.ui.consoles.Console; import de.prob2.ui.prob2fx.CurrentTrace; @Singleton public final class BConsole extends Console { @Inject private BConsole(BInterpreter bInterpreter, ResourceBundle bundle, CurrentTrace currentTrace) { super(bundle, bundle.getString("consoles.b.header"), bundle.getString("consoles.b.prompt.classicalB"), bInterpreter); currentTrace.addListener((o, from, to) -> { final String message; if (to == null) { message = bundle.getString("consoles.b.message.modelUnloaded"); } else { final File modelFile = to.getStateSpace().getModel().getModelFile(); final String name = modelFile == null ? to.getStateSpace().getMainComponent().toString() : modelFile.getName(); message = String.format(bundle.getString("consoles.b.message.modelLoaded"), name); } this.insertText(this.getLineNumber(), 0, message + '\n'); this.requestFollowCaret(); }); } }
package de.prob2.ui.consoles.b; import java.io.File; import java.util.ResourceBundle; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob2.ui.consoles.Console; import de.prob2.ui.prob2fx.CurrentTrace; @Singleton public final class BConsole extends Console { @Inject private BConsole(BInterpreter bInterpreter, ResourceBundle bundle, CurrentTrace currentTrace) { super(bundle, bundle.getString("consoles.b.header"), bundle.getString("consoles.b.prompt.classicalB"), bInterpreter); currentTrace.stateSpaceProperty().addListener((o, from, to) -> { final String message; if (to == null) { message = bundle.getString("consoles.b.message.modelUnloaded"); } else { final File modelFile = to.getModel().getModelFile(); final String name = modelFile == null ? to.getMainComponent().toString() : modelFile.getName(); message = String.format(bundle.getString("consoles.b.message.modelLoaded"), name); } this.insertText(this.getLineNumber(), 0, message + '\n'); this.requestFollowCaret(); }); } }
Fix "Model loaded" messages appearing when animating
Fix "Model loaded" messages appearing when animating
Java
epl-1.0
bendisposto/prob2-ui,bendisposto/prob2-ui,bendisposto/prob2-ui,bendisposto/prob2-ui
java
## Code Before: package de.prob2.ui.consoles.b; import java.io.File; import java.util.ResourceBundle; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob2.ui.consoles.Console; import de.prob2.ui.prob2fx.CurrentTrace; @Singleton public final class BConsole extends Console { @Inject private BConsole(BInterpreter bInterpreter, ResourceBundle bundle, CurrentTrace currentTrace) { super(bundle, bundle.getString("consoles.b.header"), bundle.getString("consoles.b.prompt.classicalB"), bInterpreter); currentTrace.addListener((o, from, to) -> { final String message; if (to == null) { message = bundle.getString("consoles.b.message.modelUnloaded"); } else { final File modelFile = to.getStateSpace().getModel().getModelFile(); final String name = modelFile == null ? to.getStateSpace().getMainComponent().toString() : modelFile.getName(); message = String.format(bundle.getString("consoles.b.message.modelLoaded"), name); } this.insertText(this.getLineNumber(), 0, message + '\n'); this.requestFollowCaret(); }); } } ## Instruction: Fix "Model loaded" messages appearing when animating ## Code After: package de.prob2.ui.consoles.b; import java.io.File; import java.util.ResourceBundle; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob2.ui.consoles.Console; import de.prob2.ui.prob2fx.CurrentTrace; @Singleton public final class BConsole extends Console { @Inject private BConsole(BInterpreter bInterpreter, ResourceBundle bundle, CurrentTrace currentTrace) { super(bundle, bundle.getString("consoles.b.header"), bundle.getString("consoles.b.prompt.classicalB"), bInterpreter); currentTrace.stateSpaceProperty().addListener((o, from, to) -> { final String message; if (to == null) { message = bundle.getString("consoles.b.message.modelUnloaded"); } else { final File modelFile = to.getModel().getModelFile(); final String name = modelFile == null ? to.getMainComponent().toString() : modelFile.getName(); message = String.format(bundle.getString("consoles.b.message.modelLoaded"), name); } this.insertText(this.getLineNumber(), 0, message + '\n'); this.requestFollowCaret(); }); } }
# ... existing code ... private BConsole(BInterpreter bInterpreter, ResourceBundle bundle, CurrentTrace currentTrace) { super(bundle, bundle.getString("consoles.b.header"), bundle.getString("consoles.b.prompt.classicalB"), bInterpreter); currentTrace.stateSpaceProperty().addListener((o, from, to) -> { final String message; if (to == null) { message = bundle.getString("consoles.b.message.modelUnloaded"); } else { final File modelFile = to.getModel().getModelFile(); final String name = modelFile == null ? to.getMainComponent().toString() : modelFile.getName(); message = String.format(bundle.getString("consoles.b.message.modelLoaded"), name); } this.insertText(this.getLineNumber(), 0, message + '\n'); # ... rest of the code ...
23df1ed7a02f3c120a0d5075b27cc92f3e1b6429
src/chime_dash/app/components/navbar.py
src/chime_dash/app/components/navbar.py
from typing import List import dash_html_components as html import dash_bootstrap_components as dbc from dash.development.base_component import ComponentMeta from penn_chime.defaults import Constants from penn_chime.settings import DEFAULTS from chime_dash.app.components.base import Component from chime_dash.app.components.menu import Menu class Navbar(Component): """ """ def __init__(self, language: str = "en", defaults: Constants = DEFAULTS): """Sets up self, menue and header """ super().__init__(language, defaults=defaults) self.menu = Menu(language, defaults=defaults) def get_html(self) -> List[ComponentMeta]: """Initialize the navigation bar """ nav = dbc.Navbar( dbc.Container( [ html.A( dbc.Row( children=[ dbc.Col( dbc.NavbarBrand( children="Penn Medicine CHIME", href="/" ) ), ], align="center", no_gutters=True, ), href="https://www.pennmedicine.org/", ), ] + self.menu.html ) ) return [nav]
from typing import List import dash_html_components as html import dash_bootstrap_components as dbc from dash.development.base_component import ComponentMeta from penn_chime.defaults import Constants from penn_chime.settings import DEFAULTS from chime_dash.app.components.base import Component from chime_dash.app.components.menu import Menu class Navbar(Component): """ """ def __init__(self, language: str = "en", defaults: Constants = DEFAULTS): """Sets up self, menue and header """ super().__init__(language, defaults=defaults) self.menu = Menu(language, defaults=defaults) def get_html(self) -> List[ComponentMeta]: """Initialize the navigation bar """ nav = dbc.Navbar( children=dbc.Container( [ html.A( dbc.Row( children=[ dbc.Col( dbc.NavbarBrand( children="Penn Medicine CHIME", href="/" ) ), ], align="center", no_gutters=True, ), href="https://www.pennmedicine.org/", ), ] + self.menu.html ), dark=True, fixed="top", color="dark" ) return [nav]
Fix nav at top of window. Use dark theme to distinguish from content.
Fix nav at top of window. Use dark theme to distinguish from content.
Python
mit
CodeForPhilly/chime,CodeForPhilly/chime,CodeForPhilly/chime
python
## Code Before: from typing import List import dash_html_components as html import dash_bootstrap_components as dbc from dash.development.base_component import ComponentMeta from penn_chime.defaults import Constants from penn_chime.settings import DEFAULTS from chime_dash.app.components.base import Component from chime_dash.app.components.menu import Menu class Navbar(Component): """ """ def __init__(self, language: str = "en", defaults: Constants = DEFAULTS): """Sets up self, menue and header """ super().__init__(language, defaults=defaults) self.menu = Menu(language, defaults=defaults) def get_html(self) -> List[ComponentMeta]: """Initialize the navigation bar """ nav = dbc.Navbar( dbc.Container( [ html.A( dbc.Row( children=[ dbc.Col( dbc.NavbarBrand( children="Penn Medicine CHIME", href="/" ) ), ], align="center", no_gutters=True, ), href="https://www.pennmedicine.org/", ), ] + self.menu.html ) ) return [nav] ## Instruction: Fix nav at top of window. Use dark theme to distinguish from content. ## Code After: from typing import List import dash_html_components as html import dash_bootstrap_components as dbc from dash.development.base_component import ComponentMeta from penn_chime.defaults import Constants from penn_chime.settings import DEFAULTS from chime_dash.app.components.base import Component from chime_dash.app.components.menu import Menu class Navbar(Component): """ """ def __init__(self, language: str = "en", defaults: Constants = DEFAULTS): """Sets up self, menue and header """ super().__init__(language, defaults=defaults) self.menu = Menu(language, defaults=defaults) def get_html(self) -> List[ComponentMeta]: """Initialize the navigation bar """ nav = dbc.Navbar( children=dbc.Container( [ html.A( dbc.Row( children=[ dbc.Col( dbc.NavbarBrand( children="Penn Medicine CHIME", href="/" ) ), ], align="center", no_gutters=True, ), href="https://www.pennmedicine.org/", ), ] + self.menu.html ), dark=True, fixed="top", color="dark" ) return [nav]
... """Initialize the navigation bar """ nav = dbc.Navbar( children=dbc.Container( [ html.A( dbc.Row( ... ), ] + self.menu.html ), dark=True, fixed="top", color="dark" ) return [nav] ...
007cd14cd3fd215cd91403ebe09cd5c0bb555f23
armstrong/apps/related_content/admin.py
armstrong/apps/related_content/admin.py
from django.contrib import admin from django.contrib.contenttypes.generic import GenericTabularInline from .models import RelatedContent from .models import RelatedType class RelatedContentInline(GenericTabularInline): ct_field = "source_type" ct_fk_field = "source_id" model = RelatedContent admin.site.register(RelatedType)
from django import forms from django.contrib import admin from django.contrib.contenttypes.generic import GenericTabularInline from armstrong.hatband import widgets from .models import RelatedContent from .models import RelatedType class RelatedContentInlineForm(forms.ModelForm): class Meta: widgets = { "destination_type": forms.HiddenInput(), "destination_id": widgets.GenericKeyWidget( object_id_name="destination_id", content_type_name="destination_type", ), "order": forms.HiddenInput(), } class RelatedContentInline(GenericTabularInline): ct_field = "source_type" ct_fk_field = "source_id" model = RelatedContent template = "admin/edit_inline/generickey.html" form = RelatedContentInlineForm admin.site.register(RelatedType)
Add in visualsearch for GFK
Add in visualsearch for GFK
Python
apache-2.0
texastribune/armstrong.apps.related_content,armstrong/armstrong.apps.related_content,armstrong/armstrong.apps.related_content,texastribune/armstrong.apps.related_content
python
## Code Before: from django.contrib import admin from django.contrib.contenttypes.generic import GenericTabularInline from .models import RelatedContent from .models import RelatedType class RelatedContentInline(GenericTabularInline): ct_field = "source_type" ct_fk_field = "source_id" model = RelatedContent admin.site.register(RelatedType) ## Instruction: Add in visualsearch for GFK ## Code After: from django import forms from django.contrib import admin from django.contrib.contenttypes.generic import GenericTabularInline from armstrong.hatband import widgets from .models import RelatedContent from .models import RelatedType class RelatedContentInlineForm(forms.ModelForm): class Meta: widgets = { "destination_type": forms.HiddenInput(), "destination_id": widgets.GenericKeyWidget( object_id_name="destination_id", content_type_name="destination_type", ), "order": forms.HiddenInput(), } class RelatedContentInline(GenericTabularInline): ct_field = "source_type" ct_fk_field = "source_id" model = RelatedContent template = "admin/edit_inline/generickey.html" form = RelatedContentInlineForm admin.site.register(RelatedType)
// ... existing code ... from django import forms from django.contrib import admin from django.contrib.contenttypes.generic import GenericTabularInline from armstrong.hatband import widgets from .models import RelatedContent from .models import RelatedType class RelatedContentInlineForm(forms.ModelForm): class Meta: widgets = { "destination_type": forms.HiddenInput(), "destination_id": widgets.GenericKeyWidget( object_id_name="destination_id", content_type_name="destination_type", ), "order": forms.HiddenInput(), } class RelatedContentInline(GenericTabularInline): // ... modified code ... ct_fk_field = "source_id" model = RelatedContent template = "admin/edit_inline/generickey.html" form = RelatedContentInlineForm admin.site.register(RelatedType) // ... rest of the code ...
9e4ca0829bcd7b3d5181bb452c80fb99c41f9820
source/tyr/tyr/rabbit_mq_handler.py
source/tyr/tyr/rabbit_mq_handler.py
from kombu import Exchange, Connection, Producer import logging class RabbitMqHandler(object): def __init__(self, connection, exchange_name, type='direct', durable=True): self._logger = logging.getLogger(__name__) try: self._connection = Connection(connection) self._producer = Producer(self._connection) self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable) except Exception: self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer') raise def errback(exc, interval): self._logger.info('Error: %r', exc, exc_info=1) self._logger.info('Retry in %s seconds.', interval) def publish(self, payload, routing_key=None, serializer=None): publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3) publish(payload, serializer=serializer, exchange=self._task_exchange, declare=[self._task_exchange], routing_key=routing_key) self._connection.release()
from kombu import Exchange, Connection, Producer import logging class RabbitMqHandler(object): def __init__(self, connection, exchange_name, type='direct', durable=True): self._logger = logging.getLogger(__name__) try: self._connection = Connection(connection) self._producer = Producer(self._connection) self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable) except Exception: self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer') raise def errback(exc, interval): self._logger.info('Error: %r', exc, exc_info=1) self._logger.info('Retry in %s seconds.', interval) def publish(self, payload, routing_key=None, serializer=None): publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3) publish(payload, serializer=serializer, exchange=self._task_exchange, declare=[self._task_exchange], routing_key=routing_key)
Fix error message 'ChannelError: channel disconnected'
Fix error message 'ChannelError: channel disconnected'
Python
agpl-3.0
patochectp/navitia,ballouche/navitia,ballouche/navitia,CanalTP/navitia,patochectp/navitia,kinnou02/navitia,antoine-de/navitia,antoine-de/navitia,patochectp/navitia,pbougue/navitia,xlqian/navitia,pbougue/navitia,xlqian/navitia,Tisseo/navitia,CanalTP/navitia,CanalTP/navitia,ballouche/navitia,Tisseo/navitia,ballouche/navitia,kinnou02/navitia,xlqian/navitia,kadhikari/navitia,antoine-de/navitia,Tisseo/navitia,kadhikari/navitia,pbougue/navitia,patochectp/navitia,xlqian/navitia,pbougue/navitia,Tisseo/navitia,CanalTP/navitia,kinnou02/navitia,kadhikari/navitia,Tisseo/navitia,kadhikari/navitia,xlqian/navitia,kinnou02/navitia,antoine-de/navitia,CanalTP/navitia
python
## Code Before: from kombu import Exchange, Connection, Producer import logging class RabbitMqHandler(object): def __init__(self, connection, exchange_name, type='direct', durable=True): self._logger = logging.getLogger(__name__) try: self._connection = Connection(connection) self._producer = Producer(self._connection) self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable) except Exception: self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer') raise def errback(exc, interval): self._logger.info('Error: %r', exc, exc_info=1) self._logger.info('Retry in %s seconds.', interval) def publish(self, payload, routing_key=None, serializer=None): publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3) publish(payload, serializer=serializer, exchange=self._task_exchange, declare=[self._task_exchange], routing_key=routing_key) self._connection.release() ## Instruction: Fix error message 'ChannelError: channel disconnected' ## Code After: from kombu import Exchange, Connection, Producer import logging class RabbitMqHandler(object): def __init__(self, connection, exchange_name, type='direct', durable=True): self._logger = logging.getLogger(__name__) try: self._connection = Connection(connection) self._producer = Producer(self._connection) self._task_exchange = Exchange(name=exchange_name, type=type, durable=durable) except Exception: self._logger.info('badly formated token %s', auth).exception('Unable to activate the producer') raise def errback(exc, interval): self._logger.info('Error: %r', exc, exc_info=1) self._logger.info('Retry in %s seconds.', interval) def publish(self, payload, routing_key=None, serializer=None): publish = self._connection.ensure(self._producer, self._producer.publish, errback = self.errback, max_retries=3) publish(payload, serializer=serializer, exchange=self._task_exchange, declare=[self._task_exchange], routing_key=routing_key)
... exchange=self._task_exchange, declare=[self._task_exchange], routing_key=routing_key) ...
77ff64c858aa21c9651ccf58c95b739db45cd97b
Instanssi/kompomaatti/templatetags/kompomaatti_base_tags.py
Instanssi/kompomaatti/templatetags/kompomaatti_base_tags.py
from django import template from Instanssi.kompomaatti.models import Compo, Competition register = template.Library() @register.inclusion_tag('kompomaatti/compo_nav_items.html') def render_base_compos_nav(event_id): return { 'event_id': event_id, 'compos': Compo.objects.filter(active=True, event_id=event_id) } @register.inclusion_tag('kompomaatti/competition_nav_items.html') def render_base_competitions_nav(event_id): return { 'event_id': event_id, 'competitions': Competition.objects.filter(active=True, event_id=event_id) }
from django import template from Instanssi.kompomaatti.models import Compo, Competition register = template.Library() @register.inclusion_tag('kompomaatti/tags/compo_nav_items.html') def render_base_compos_nav(event_id): return { 'event_id': event_id, 'compos': Compo.objects.filter(active=True, event_id=event_id) } @register.inclusion_tag('kompomaatti/tags/competition_nav_items.html') def render_base_competitions_nav(event_id): return { 'event_id': event_id, 'competitions': Competition.objects.filter(active=True, event_id=event_id) }
Update tags to use new template subdirectory.
kompomaatti: Update tags to use new template subdirectory.
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
python
## Code Before: from django import template from Instanssi.kompomaatti.models import Compo, Competition register = template.Library() @register.inclusion_tag('kompomaatti/compo_nav_items.html') def render_base_compos_nav(event_id): return { 'event_id': event_id, 'compos': Compo.objects.filter(active=True, event_id=event_id) } @register.inclusion_tag('kompomaatti/competition_nav_items.html') def render_base_competitions_nav(event_id): return { 'event_id': event_id, 'competitions': Competition.objects.filter(active=True, event_id=event_id) } ## Instruction: kompomaatti: Update tags to use new template subdirectory. ## Code After: from django import template from Instanssi.kompomaatti.models import Compo, Competition register = template.Library() @register.inclusion_tag('kompomaatti/tags/compo_nav_items.html') def render_base_compos_nav(event_id): return { 'event_id': event_id, 'compos': Compo.objects.filter(active=True, event_id=event_id) } @register.inclusion_tag('kompomaatti/tags/competition_nav_items.html') def render_base_competitions_nav(event_id): return { 'event_id': event_id, 'competitions': Competition.objects.filter(active=True, event_id=event_id) }
# ... existing code ... register = template.Library() @register.inclusion_tag('kompomaatti/tags/compo_nav_items.html') def render_base_compos_nav(event_id): return { 'event_id': event_id, # ... modified code ... 'compos': Compo.objects.filter(active=True, event_id=event_id) } @register.inclusion_tag('kompomaatti/tags/competition_nav_items.html') def render_base_competitions_nav(event_id): return { 'event_id': event_id, # ... rest of the code ...
b5e45c4d0917a79ef02ba04b4c6c7bcba45193dc
examples/helloElektra.c
examples/helloElektra.c
/** * @file * * @brief * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include <kdb.h> #include <stdio.h> int main (void) { KeySet * config = ksNew (0, KS_END); Key * root = keyNew ("user/test", KEY_END); printf ("Open key database\n"); KDB * handle = kdbOpen (root); printf ("Retrieve key set\n"); kdbGet (handle, config, root); printf ("Number of key-value pairs: %zu\n", ksGetSize (config)); Key * key = keyNew ("user/test/hello", KEY_VALUE, "elektra", KEY_END); printf ("Add key %s\n", keyName (key)); ksAppendKey (config, key); printf ("Number of key-value pairs: %zu\n", ksGetSize (config)); printf ("\n%s, %s\n\n", keyBaseName (key), keyString (key)); // If you want to store the key database on disk, then please uncomment the following two lines // printf ("Write key set to disk\n"); // kdbSet (handle, config, root); printf ("Delete mappings inside memory\n"); ksDel (config); printf ("Close key database\n"); kdbClose (handle, 0); return 0; }
/** * @file * * @brief * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include <kdb.h> #include <stdio.h> int main (void) { KeySet * config = ksNew (0, KS_END); Key * root = keyNew ("user/test", KEY_END); printf ("Open key database\n"); KDB * handle = kdbOpen (root); printf ("Retrieve key set\n"); kdbGet (handle, config, root); printf ("Number of key-value pairs: %zu\n", ksGetSize (config)); Key * key = keyNew ("user/test/hello", KEY_VALUE, "elektra", KEY_END); printf ("Add key %s\n", keyName (key)); ksAppendKey (config, key); printf ("Number of key-value pairs: %zu\n", ksGetSize (config)); printf ("\n%s, %s\n\n", keyBaseName (key), keyString (key)); // If you want to store the key database on disk, then please uncomment the following two lines // printf ("Write key set to disk\n"); // kdbSet (handle, config, root); printf ("Delete key-value pairs inside memory\n"); ksDel (config); printf ("Close key database\n"); kdbClose (handle, 0); return 0; }
Use more common technical term
Examples: Use more common technical term
C
bsd-3-clause
e1528532/libelektra,mpranj/libelektra,mpranj/libelektra,petermax2/libelektra,BernhardDenner/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,BernhardDenner/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,ElektraInitiative/libelektra,e1528532/libelektra,e1528532/libelektra,BernhardDenner/libelektra,petermax2/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,BernhardDenner/libelektra,ElektraInitiative/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,petermax2/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,mpranj/libelektra,petermax2/libelektra,mpranj/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,e1528532/libelektra,e1528532/libelektra,mpranj/libelektra,petermax2/libelektra,mpranj/libelektra,mpranj/libelektra,e1528532/libelektra,ElektraInitiative/libelektra
c
## Code Before: /** * @file * * @brief * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include <kdb.h> #include <stdio.h> int main (void) { KeySet * config = ksNew (0, KS_END); Key * root = keyNew ("user/test", KEY_END); printf ("Open key database\n"); KDB * handle = kdbOpen (root); printf ("Retrieve key set\n"); kdbGet (handle, config, root); printf ("Number of key-value pairs: %zu\n", ksGetSize (config)); Key * key = keyNew ("user/test/hello", KEY_VALUE, "elektra", KEY_END); printf ("Add key %s\n", keyName (key)); ksAppendKey (config, key); printf ("Number of key-value pairs: %zu\n", ksGetSize (config)); printf ("\n%s, %s\n\n", keyBaseName (key), keyString (key)); // If you want to store the key database on disk, then please uncomment the following two lines // printf ("Write key set to disk\n"); // kdbSet (handle, config, root); printf ("Delete mappings inside memory\n"); ksDel (config); printf ("Close key database\n"); kdbClose (handle, 0); return 0; } ## Instruction: Examples: Use more common technical term ## Code After: /** * @file * * @brief * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include <kdb.h> #include <stdio.h> int main (void) { KeySet * config = ksNew (0, KS_END); Key * root = keyNew ("user/test", KEY_END); printf ("Open key database\n"); KDB * handle = kdbOpen (root); printf ("Retrieve key set\n"); kdbGet (handle, config, root); printf ("Number of key-value pairs: %zu\n", ksGetSize (config)); Key * key = keyNew ("user/test/hello", KEY_VALUE, "elektra", KEY_END); printf ("Add key %s\n", keyName (key)); ksAppendKey (config, key); printf ("Number of key-value pairs: %zu\n", ksGetSize (config)); printf ("\n%s, %s\n\n", keyBaseName (key), keyString (key)); // If you want to store the key database on disk, then please uncomment the following two lines // printf ("Write key set to disk\n"); // kdbSet (handle, config, root); printf ("Delete key-value pairs inside memory\n"); ksDel (config); printf ("Close key database\n"); kdbClose (handle, 0); return 0; }
# ... existing code ... // printf ("Write key set to disk\n"); // kdbSet (handle, config, root); printf ("Delete key-value pairs inside memory\n"); ksDel (config); printf ("Close key database\n"); kdbClose (handle, 0); # ... rest of the code ...
368808eee4701f78d2931970d28674c4db0428dc
integration-tests/src/test/java/arez/integration/IdentifiableIntegrationTest.java
integration-tests/src/test/java/arez/integration/IdentifiableIntegrationTest.java
package arez.integration; import arez.annotations.ArezComponent; import arez.annotations.ComponentId; import arez.component.Identifiable; import org.testng.annotations.Test; import static org.testng.Assert.*; @SuppressWarnings( "ConstantConditions" ) public final class IdentifiableIntegrationTest extends AbstractArezIntegrationTest { @Test public void arezManagedArezId() { final Model1 model = new IdentifiableIntegrationTest_Arez_Model1(); assertFalse( model instanceof Identifiable ); } @Test public void componentManagedArezId() { final Model2 model = new IdentifiableIntegrationTest_Arez_Model2( 33 ); assertTrue( model instanceof Identifiable ); assertEquals( Identifiable.getArezId( model ), (Integer) 33 ); assertEquals( Identifiable.asIdentifiable( model ), model ); } @ArezComponent( allowEmpty = true ) static abstract class Model1 { } @ArezComponent( allowEmpty = true ) static abstract class Model2 { private final int id; Model2( final int id ) { this.id = id; } @ComponentId int getId() { return id; } } }
package arez.integration; import arez.annotations.ArezComponent; import arez.annotations.ComponentId; import arez.annotations.Feature; import arez.component.Identifiable; import org.testng.annotations.Test; import static org.testng.Assert.*; @SuppressWarnings( "ConstantConditions" ) public final class IdentifiableIntegrationTest extends AbstractArezIntegrationTest { @Test public void requireId_DISABLE() { final Model1 model = new IdentifiableIntegrationTest_Arez_Model1(); assertFalse( model instanceof Identifiable ); } @Test public void requireId_ENABLE() { final Model2 model = new IdentifiableIntegrationTest_Arez_Model2( 33 ); assertTrue( model instanceof Identifiable ); assertEquals( Identifiable.getArezId( model ), (Integer) 33 ); assertEquals( Identifiable.asIdentifiable( model ), model ); } @Test public void requireId_DEFAULT() { final Model3 model = new IdentifiableIntegrationTest_Arez_Model3(); assertTrue( model instanceof Identifiable ); assertEquals( Identifiable.getArezId( model ), (Integer) 1 ); assertEquals( Identifiable.asIdentifiable( model ), model ); } @ArezComponent( allowEmpty = true, requireId = Feature.DISABLE ) static abstract class Model1 { } @ArezComponent( allowEmpty = true, requireId = Feature.ENABLE ) static abstract class Model2 { private final int id; Model2( final int id ) { this.id = id; } @ComponentId int getId() { return id; } } @ArezComponent( allowEmpty = true, requireId = Feature.AUTODETECT ) static abstract class Model3 { } }
Fix test to reflect current defaults
Fix test to reflect current defaults
Java
apache-2.0
realityforge/arez,realityforge/arez,realityforge/arez
java
## Code Before: package arez.integration; import arez.annotations.ArezComponent; import arez.annotations.ComponentId; import arez.component.Identifiable; import org.testng.annotations.Test; import static org.testng.Assert.*; @SuppressWarnings( "ConstantConditions" ) public final class IdentifiableIntegrationTest extends AbstractArezIntegrationTest { @Test public void arezManagedArezId() { final Model1 model = new IdentifiableIntegrationTest_Arez_Model1(); assertFalse( model instanceof Identifiable ); } @Test public void componentManagedArezId() { final Model2 model = new IdentifiableIntegrationTest_Arez_Model2( 33 ); assertTrue( model instanceof Identifiable ); assertEquals( Identifiable.getArezId( model ), (Integer) 33 ); assertEquals( Identifiable.asIdentifiable( model ), model ); } @ArezComponent( allowEmpty = true ) static abstract class Model1 { } @ArezComponent( allowEmpty = true ) static abstract class Model2 { private final int id; Model2( final int id ) { this.id = id; } @ComponentId int getId() { return id; } } } ## Instruction: Fix test to reflect current defaults ## Code After: package arez.integration; import arez.annotations.ArezComponent; import arez.annotations.ComponentId; import arez.annotations.Feature; import arez.component.Identifiable; import org.testng.annotations.Test; import static org.testng.Assert.*; @SuppressWarnings( "ConstantConditions" ) public final class IdentifiableIntegrationTest extends AbstractArezIntegrationTest { @Test public void requireId_DISABLE() { final Model1 model = new IdentifiableIntegrationTest_Arez_Model1(); assertFalse( model instanceof Identifiable ); } @Test public void requireId_ENABLE() { final Model2 model = new IdentifiableIntegrationTest_Arez_Model2( 33 ); assertTrue( model instanceof Identifiable ); assertEquals( Identifiable.getArezId( model ), (Integer) 33 ); assertEquals( Identifiable.asIdentifiable( model ), model ); } @Test public void requireId_DEFAULT() { final Model3 model = new IdentifiableIntegrationTest_Arez_Model3(); assertTrue( model instanceof Identifiable ); assertEquals( Identifiable.getArezId( model ), (Integer) 1 ); assertEquals( Identifiable.asIdentifiable( model ), model ); } @ArezComponent( allowEmpty = true, requireId = Feature.DISABLE ) static abstract class Model1 { } @ArezComponent( allowEmpty = true, requireId = Feature.ENABLE ) static abstract class Model2 { private final int id; Model2( final int id ) { this.id = id; } @ComponentId int getId() { return id; } } @ArezComponent( allowEmpty = true, requireId = Feature.AUTODETECT ) static abstract class Model3 { } }
# ... existing code ... import arez.annotations.ArezComponent; import arez.annotations.ComponentId; import arez.annotations.Feature; import arez.component.Identifiable; import org.testng.annotations.Test; import static org.testng.Assert.*; # ... modified code ... extends AbstractArezIntegrationTest { @Test public void requireId_DISABLE() { final Model1 model = new IdentifiableIntegrationTest_Arez_Model1(); ... } @Test public void requireId_ENABLE() { final Model2 model = new IdentifiableIntegrationTest_Arez_Model2( 33 ); ... assertEquals( Identifiable.asIdentifiable( model ), model ); } @Test public void requireId_DEFAULT() { final Model3 model = new IdentifiableIntegrationTest_Arez_Model3(); assertTrue( model instanceof Identifiable ); assertEquals( Identifiable.getArezId( model ), (Integer) 1 ); assertEquals( Identifiable.asIdentifiable( model ), model ); } @ArezComponent( allowEmpty = true, requireId = Feature.DISABLE ) static abstract class Model1 { } @ArezComponent( allowEmpty = true, requireId = Feature.ENABLE ) static abstract class Model2 { private final int id; ... return id; } } @ArezComponent( allowEmpty = true, requireId = Feature.AUTODETECT ) static abstract class Model3 { } } # ... rest of the code ...
58022a61d6882902b9dc22060638f1ac9a6b95bf
src/fs/driver/devfs/devfs_dvfs.c
src/fs/driver/devfs/devfs_dvfs.c
/** * @file devfs_dvfs.c * @brief * @author Denis Deryugin <[email protected]> * @version 0.1 * @date 2015-09-28 */ /* This is stub */
/** * @file devfs_dvfs.c * @brief * @author Denis Deryugin <[email protected]> * @version 0.1 * @date 2015-09-28 */ #include <fs/dvfs.h> #include <util/array.h> static int devfs_destroy_inode(struct inode *inode) { return 0; } static int devfs_iterate(struct inode *next, struct inode *parent, struct dir_ctx *ctx) { return 0; } static struct inode *devfs_lookup(char const *name, struct dentry const *dir) { return NULL; } static int devfs_pathname(struct inode *inode, char *buf, int flags) { return 0; } static int devfs_mount_end(struct super_block *sb) { return 0; } static int devfs_open(struct inode *node, struct file *file) { return 0; } static size_t devfs_read(struct file *desc, void *buf, size_t size) { return 0; } static int devfs_ioctl(struct file *desc, int request, ...) { return 0; } struct super_block_operations devfs_sbops = { .destroy_inode = devfs_destroy_inode, }; struct inode_operations devfs_iops = { .lookup = devfs_lookup, .iterate = devfs_iterate, .pathname = devfs_pathname, }; struct file_operations devfs_fops = { .open = devfs_open, .read = devfs_read, .ioctl = devfs_ioctl, }; static int devfs_fill_sb(struct super_block *sb, struct block_dev *dev) { sb->sb_iops = &devfs_iops; sb->sb_fops = &devfs_fops; sb->sb_ops = &devfs_sbops; return 0; } static struct dumb_fs_driver devfs_dumb_driver = { .name = "devfs", .fill_sb = devfs_fill_sb, .mount_end = devfs_mount_end, }; ARRAY_SPREAD_DECLARE(struct dumb_fs_driver *, dumb_drv_tab); ARRAY_SPREAD_ADD(dumb_drv_tab, &devfs_dumb_driver);
Add fs-related structures and stub functions
devfs: Add fs-related structures and stub functions
C
bsd-2-clause
Kakadu/embox,Kakadu/embox,mike2390/embox,embox/embox,gzoom13/embox,mike2390/embox,embox/embox,gzoom13/embox,mike2390/embox,mike2390/embox,Kakadu/embox,gzoom13/embox,Kakadu/embox,gzoom13/embox,gzoom13/embox,Kakadu/embox,Kakadu/embox,mike2390/embox,gzoom13/embox,mike2390/embox,gzoom13/embox,embox/embox,embox/embox,Kakadu/embox,mike2390/embox,embox/embox,embox/embox
c
## Code Before: /** * @file devfs_dvfs.c * @brief * @author Denis Deryugin <[email protected]> * @version 0.1 * @date 2015-09-28 */ /* This is stub */ ## Instruction: devfs: Add fs-related structures and stub functions ## Code After: /** * @file devfs_dvfs.c * @brief * @author Denis Deryugin <[email protected]> * @version 0.1 * @date 2015-09-28 */ #include <fs/dvfs.h> #include <util/array.h> static int devfs_destroy_inode(struct inode *inode) { return 0; } static int devfs_iterate(struct inode *next, struct inode *parent, struct dir_ctx *ctx) { return 0; } static struct inode *devfs_lookup(char const *name, struct dentry const *dir) { return NULL; } static int devfs_pathname(struct inode *inode, char *buf, int flags) { return 0; } static int devfs_mount_end(struct super_block *sb) { return 0; } static int devfs_open(struct inode *node, struct file *file) { return 0; } static size_t devfs_read(struct file *desc, void *buf, size_t size) { return 0; } static int devfs_ioctl(struct file *desc, int request, ...) { return 0; } struct super_block_operations devfs_sbops = { .destroy_inode = devfs_destroy_inode, }; struct inode_operations devfs_iops = { .lookup = devfs_lookup, .iterate = devfs_iterate, .pathname = devfs_pathname, }; struct file_operations devfs_fops = { .open = devfs_open, .read = devfs_read, .ioctl = devfs_ioctl, }; static int devfs_fill_sb(struct super_block *sb, struct block_dev *dev) { sb->sb_iops = &devfs_iops; sb->sb_fops = &devfs_fops; sb->sb_ops = &devfs_sbops; return 0; } static struct dumb_fs_driver devfs_dumb_driver = { .name = "devfs", .fill_sb = devfs_fill_sb, .mount_end = devfs_mount_end, }; ARRAY_SPREAD_DECLARE(struct dumb_fs_driver *, dumb_drv_tab); ARRAY_SPREAD_ADD(dumb_drv_tab, &devfs_dumb_driver);
# ... existing code ... * @date 2015-09-28 */ #include <fs/dvfs.h> #include <util/array.h> static int devfs_destroy_inode(struct inode *inode) { return 0; } static int devfs_iterate(struct inode *next, struct inode *parent, struct dir_ctx *ctx) { return 0; } static struct inode *devfs_lookup(char const *name, struct dentry const *dir) { return NULL; } static int devfs_pathname(struct inode *inode, char *buf, int flags) { return 0; } static int devfs_mount_end(struct super_block *sb) { return 0; } static int devfs_open(struct inode *node, struct file *file) { return 0; } static size_t devfs_read(struct file *desc, void *buf, size_t size) { return 0; } static int devfs_ioctl(struct file *desc, int request, ...) { return 0; } struct super_block_operations devfs_sbops = { .destroy_inode = devfs_destroy_inode, }; struct inode_operations devfs_iops = { .lookup = devfs_lookup, .iterate = devfs_iterate, .pathname = devfs_pathname, }; struct file_operations devfs_fops = { .open = devfs_open, .read = devfs_read, .ioctl = devfs_ioctl, }; static int devfs_fill_sb(struct super_block *sb, struct block_dev *dev) { sb->sb_iops = &devfs_iops; sb->sb_fops = &devfs_fops; sb->sb_ops = &devfs_sbops; return 0; } static struct dumb_fs_driver devfs_dumb_driver = { .name = "devfs", .fill_sb = devfs_fill_sb, .mount_end = devfs_mount_end, }; ARRAY_SPREAD_DECLARE(struct dumb_fs_driver *, dumb_drv_tab); ARRAY_SPREAD_ADD(dumb_drv_tab, &devfs_dumb_driver); # ... rest of the code ...
c7265b9990562df661fa7e47405f7133081945b4
src/com/woopra/WoopraEvent.java
src/com/woopra/WoopraEvent.java
package com.woopra; import java.util.Properties; /** * @author Woopra on 1/26/2013 * */ public class WoopraEvent { private String eventName = null; private Properties properties = null; public WoopraEvent(String eventName) { this.eventName = eventName; properties = new Properties(); } public WoopraEvent(String eventName, Properties properties) { this.eventName = eventName; if (properties != null) { this.properties = properties; } else { properties = new Properties(); } } public String getEventName() { return eventName; } public void setEventName(String eventName) { this.eventName = eventName; } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public void addEventProperties(Properties newProperties) { properties.putAll(newProperties); } public void addEventProperty(String key, String value) { properties.setProperty(key, value); } }
package com.woopra; import java.util.Properties; /** * @author Woopra on 1/26/2013 * */ public class WoopraEvent { private String eventName = null; private Properties properties = null; public WoopraEvent(String eventName) { super(eventName, new Properties(); } public WoopraEvent(String eventName, Properties properties) { this.properties = properties; this.properties.setProperty('name', eventName); } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public void addEventProperties(Properties newProperties) { properties.putAll(newProperties); } public void addEventProperty(String key, String value) { properties.setProperty(key, value); } }
Fix event name not being added in constructor.
Fix event name not being added in constructor.
Java
apache-2.0
Istikana/woopra-android-sdk,Woopra/woopra-android-sdk
java
## Code Before: package com.woopra; import java.util.Properties; /** * @author Woopra on 1/26/2013 * */ public class WoopraEvent { private String eventName = null; private Properties properties = null; public WoopraEvent(String eventName) { this.eventName = eventName; properties = new Properties(); } public WoopraEvent(String eventName, Properties properties) { this.eventName = eventName; if (properties != null) { this.properties = properties; } else { properties = new Properties(); } } public String getEventName() { return eventName; } public void setEventName(String eventName) { this.eventName = eventName; } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public void addEventProperties(Properties newProperties) { properties.putAll(newProperties); } public void addEventProperty(String key, String value) { properties.setProperty(key, value); } } ## Instruction: Fix event name not being added in constructor. ## Code After: package com.woopra; import java.util.Properties; /** * @author Woopra on 1/26/2013 * */ public class WoopraEvent { private String eventName = null; private Properties properties = null; public WoopraEvent(String eventName) { super(eventName, new Properties(); } public WoopraEvent(String eventName, Properties properties) { this.properties = properties; this.properties.setProperty('name', eventName); } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public void addEventProperties(Properties newProperties) { properties.putAll(newProperties); } public void addEventProperty(String key, String value) { properties.setProperty(key, value); } }
// ... existing code ... private Properties properties = null; public WoopraEvent(String eventName) { super(eventName, new Properties(); } public WoopraEvent(String eventName, Properties properties) { this.properties = properties; this.properties.setProperty('name', eventName); } public Properties getProperties() { // ... rest of the code ...
5d8dafb9bd6a6c5c5964f7076b7d398d285aaf8d
zeus/artifacts/__init__.py
zeus/artifacts/__init__.py
from __future__ import absolute_import, print_function from .manager import Manager from .checkstyle import CheckstyleHandler from .coverage import CoverageHandler from .pycodestyle import PyCodeStyleHandler from .xunit import XunitHandler manager = Manager() manager.register(CheckstyleHandler, [ 'checkstyle.xml', '*.checkstyle.xml']) manager.register(CoverageHandler, [ 'coverage.xml', '*.coverage.xml']) manager.register(XunitHandler, [ 'xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml']) manager.register(PyCodeStyleHandler, [ 'pep8.txt', '*.pep8.txt', 'pycodestyle.txt', '*.pycodestyle.txt'])
from __future__ import absolute_import, print_function from .manager import Manager from .checkstyle import CheckstyleHandler from .coverage import CoverageHandler from .pycodestyle import PyCodeStyleHandler from .pylint import PyLintHandler from .xunit import XunitHandler manager = Manager() manager.register(CheckstyleHandler, [ 'checkstyle.xml', '*.checkstyle.xml']) manager.register(CoverageHandler, [ 'coverage.xml', '*.coverage.xml']) manager.register(XunitHandler, [ 'xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml']) manager.register(PyCodeStyleHandler, [ 'pep8.txt', '*.pep8.txt', 'pycodestyle.txt', '*.pycodestyle.txt']) manager.register(PyLintHandler, [ 'pylint.txt', '*.pylint.txt'])
Add PyLintHandler to artifact manager
fix: Add PyLintHandler to artifact manager
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
python
## Code Before: from __future__ import absolute_import, print_function from .manager import Manager from .checkstyle import CheckstyleHandler from .coverage import CoverageHandler from .pycodestyle import PyCodeStyleHandler from .xunit import XunitHandler manager = Manager() manager.register(CheckstyleHandler, [ 'checkstyle.xml', '*.checkstyle.xml']) manager.register(CoverageHandler, [ 'coverage.xml', '*.coverage.xml']) manager.register(XunitHandler, [ 'xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml']) manager.register(PyCodeStyleHandler, [ 'pep8.txt', '*.pep8.txt', 'pycodestyle.txt', '*.pycodestyle.txt']) ## Instruction: fix: Add PyLintHandler to artifact manager ## Code After: from __future__ import absolute_import, print_function from .manager import Manager from .checkstyle import CheckstyleHandler from .coverage import CoverageHandler from .pycodestyle import PyCodeStyleHandler from .pylint import PyLintHandler from .xunit import XunitHandler manager = Manager() manager.register(CheckstyleHandler, [ 'checkstyle.xml', '*.checkstyle.xml']) manager.register(CoverageHandler, [ 'coverage.xml', '*.coverage.xml']) manager.register(XunitHandler, [ 'xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml']) manager.register(PyCodeStyleHandler, [ 'pep8.txt', '*.pep8.txt', 'pycodestyle.txt', '*.pycodestyle.txt']) manager.register(PyLintHandler, [ 'pylint.txt', '*.pylint.txt'])
// ... existing code ... from .checkstyle import CheckstyleHandler from .coverage import CoverageHandler from .pycodestyle import PyCodeStyleHandler from .pylint import PyLintHandler from .xunit import XunitHandler manager = Manager() // ... modified code ... 'xunit.xml', 'junit.xml', '*.xunit.xml', '*.junit.xml']) manager.register(PyCodeStyleHandler, [ 'pep8.txt', '*.pep8.txt', 'pycodestyle.txt', '*.pycodestyle.txt']) manager.register(PyLintHandler, [ 'pylint.txt', '*.pylint.txt']) // ... rest of the code ...
49263d5e43be6ab9a5c3faf2ee6478840526cccb
flatten-array/flatten_array.py
flatten-array/flatten_array.py
def flatten(lst): """Completely flatten an arbitrarily-deep list""" return [*_flatten(lst)] def _flatten(lst): """Generator for flattening arbitrarily-deep lists""" if isinstance(lst, (list, tuple)): for item in lst: if item is None: continue else: yield from _flatten(item) else: yield lst
def flatten(lst): """Completely flatten an arbitrarily-deep list""" return [*_flatten(lst)] def _flatten(lst): """Generator for flattening arbitrarily-deep lists""" for item in lst: if isinstance(item, (list, tuple)): yield from _flatten(item) elif item is not None: yield item
Tidy and simplify generator code
Tidy and simplify generator code
Python
agpl-3.0
CubicComet/exercism-python-solutions
python
## Code Before: def flatten(lst): """Completely flatten an arbitrarily-deep list""" return [*_flatten(lst)] def _flatten(lst): """Generator for flattening arbitrarily-deep lists""" if isinstance(lst, (list, tuple)): for item in lst: if item is None: continue else: yield from _flatten(item) else: yield lst ## Instruction: Tidy and simplify generator code ## Code After: def flatten(lst): """Completely flatten an arbitrarily-deep list""" return [*_flatten(lst)] def _flatten(lst): """Generator for flattening arbitrarily-deep lists""" for item in lst: if isinstance(item, (list, tuple)): yield from _flatten(item) elif item is not None: yield item
... def _flatten(lst): """Generator for flattening arbitrarily-deep lists""" for item in lst: if isinstance(item, (list, tuple)): yield from _flatten(item) elif item is not None: yield item ...
860e16f506d0a601540847fe21e617d8f7fbf882
malware/pickle_tool.py
malware/pickle_tool.py
import os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache
import os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache def pickle2json(pkl): if os.path.isfile(pkl): cache = pickle.load(open(pkl, 'rb')) with open('pkl2json.json', 'wb') as fp: json.dump(cache, fp) else: print "No such file"
Add pickle convert to json method
Add pickle convert to json method
Python
apache-2.0
John-Lin/malware,John-Lin/malware
python
## Code Before: import os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache ## Instruction: Add pickle convert to json method ## Code After: import os import cPickle as pickle import simplejson as json def update_pickle(new_cache): # print('Updated pickle') pickle.dump(new_cache, open('url_cache.pkl', 'wb'), 2) def check_pickle(): # print('Checking in pickle') if not os.path.isfile('url_cache.pkl'): malicious_url = {} pickle.dump(malicious_url, open('url_cache.pkl', 'wb'), 2) cache = pickle.load(open('url_cache.pkl', 'rb')) return cache def update_json(data): with open("url_cache.json", "wb") as fp: try: json.dump(data, fp) except: print "UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8" def check_json(): if not os.path.isfile('url_cache.json'): init = {} with open("url_cache.json", "wb") as fp: json.dump(init, fp) with open("url_cache.json", "rb") as fp: # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache def pickle2json(pkl): if os.path.isfile(pkl): cache = pickle.load(open(pkl, 'rb')) with open('pkl2json.json', 'wb') as fp: json.dump(cache, fp) else: print "No such file"
# ... existing code ... # cache = json.load(fp) cache = json.load(fp, "ISO-8859-1") return cache def pickle2json(pkl): if os.path.isfile(pkl): cache = pickle.load(open(pkl, 'rb')) with open('pkl2json.json', 'wb') as fp: json.dump(cache, fp) else: print "No such file" # ... rest of the code ...
fe6a37519ff0af26a85aeee217d498111eea5412
src/main/java/com/skcraft/plume/module/Broadcast.java
src/main/java/com/skcraft/plume/module/Broadcast.java
package com.skcraft.plume.module; import com.sk89q.intake.Command; import com.sk89q.intake.Require; import com.sk89q.intake.parametric.annotation.Switch; import com.sk89q.intake.parametric.annotation.Text; import com.skcraft.plume.command.Sender; import com.skcraft.plume.common.util.module.Module; import com.skcraft.plume.util.Messages; import net.minecraft.command.ICommandSender; import static com.skcraft.plume.common.util.SharedLocale.tr; @Module(name = "broadcast", desc = "Server wide message broadcasting for operators") public class Broadcast { @Command(aliases = {"broadcast", "bc"}, desc = "Send out a broadcast message") @Require("plume.broadcast.bc") public void broadcast(@Sender ICommandSender sender, @Text String msg, @Switch('t') String type) { if (type == null || type.equalsIgnoreCase("type")) { Messages.broadcastInfo(msg); } else if (type.equalsIgnoreCase("alert")) { Messages.broadcastAlert(msg); } else { sender.addChatMessage(Messages.error(tr("broadcast.invalidType"))); } } }
package com.skcraft.plume.module; import com.sk89q.intake.Command; import com.sk89q.intake.Require; import com.sk89q.intake.parametric.annotation.Text; import com.skcraft.plume.command.Sender; import com.skcraft.plume.common.util.module.Module; import com.skcraft.plume.util.Messages; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; @Module(name = "broadcast", desc = "Server wide message broadcasting for operators") public class Broadcast { @Command(aliases = {"broadcast", "bc"}, desc = "Send out a broadcast message") @Require("plume.broadcast.broadcast") public void broadcast(@Sender ICommandSender sender, @Text String msg) { Messages.broadcast(Messages.info("SERVER: " + msg)); } @Command(aliases = {"alert"}, desc = "Send out a broadcast message") @Require("plume.broadcast.broadcast") public void alert(@Sender ICommandSender sender, @Text String msg) { Messages.broadcast(Messages.error("SERVER: " + msg)); } @Command(aliases = {"print"}, desc = "Print an unformatted message to chat") @Require("plume.broadcast.print") public void print(@Sender ICommandSender sender, @Text String msg) { Messages.broadcast(new ChatComponentText(msg)); } }
Make the broadcast module more versatile.
Make the broadcast module more versatile.
Java
bsd-3-clause
wizjany/Plume,SKCraft/Plume,wizjany/Plume,SKCraft/Plume
java
## Code Before: package com.skcraft.plume.module; import com.sk89q.intake.Command; import com.sk89q.intake.Require; import com.sk89q.intake.parametric.annotation.Switch; import com.sk89q.intake.parametric.annotation.Text; import com.skcraft.plume.command.Sender; import com.skcraft.plume.common.util.module.Module; import com.skcraft.plume.util.Messages; import net.minecraft.command.ICommandSender; import static com.skcraft.plume.common.util.SharedLocale.tr; @Module(name = "broadcast", desc = "Server wide message broadcasting for operators") public class Broadcast { @Command(aliases = {"broadcast", "bc"}, desc = "Send out a broadcast message") @Require("plume.broadcast.bc") public void broadcast(@Sender ICommandSender sender, @Text String msg, @Switch('t') String type) { if (type == null || type.equalsIgnoreCase("type")) { Messages.broadcastInfo(msg); } else if (type.equalsIgnoreCase("alert")) { Messages.broadcastAlert(msg); } else { sender.addChatMessage(Messages.error(tr("broadcast.invalidType"))); } } } ## Instruction: Make the broadcast module more versatile. ## Code After: package com.skcraft.plume.module; import com.sk89q.intake.Command; import com.sk89q.intake.Require; import com.sk89q.intake.parametric.annotation.Text; import com.skcraft.plume.command.Sender; import com.skcraft.plume.common.util.module.Module; import com.skcraft.plume.util.Messages; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; @Module(name = "broadcast", desc = "Server wide message broadcasting for operators") public class Broadcast { @Command(aliases = {"broadcast", "bc"}, desc = "Send out a broadcast message") @Require("plume.broadcast.broadcast") public void broadcast(@Sender ICommandSender sender, @Text String msg) { Messages.broadcast(Messages.info("SERVER: " + msg)); } @Command(aliases = {"alert"}, desc = "Send out a broadcast message") @Require("plume.broadcast.broadcast") public void alert(@Sender ICommandSender sender, @Text String msg) { Messages.broadcast(Messages.error("SERVER: " + msg)); } @Command(aliases = {"print"}, desc = "Print an unformatted message to chat") @Require("plume.broadcast.print") public void print(@Sender ICommandSender sender, @Text String msg) { Messages.broadcast(new ChatComponentText(msg)); } }
# ... existing code ... import com.sk89q.intake.Command; import com.sk89q.intake.Require; import com.sk89q.intake.parametric.annotation.Text; import com.skcraft.plume.command.Sender; import com.skcraft.plume.common.util.module.Module; import com.skcraft.plume.util.Messages; import net.minecraft.command.ICommandSender; import net.minecraft.util.ChatComponentText; @Module(name = "broadcast", desc = "Server wide message broadcasting for operators") public class Broadcast { @Command(aliases = {"broadcast", "bc"}, desc = "Send out a broadcast message") @Require("plume.broadcast.broadcast") public void broadcast(@Sender ICommandSender sender, @Text String msg) { Messages.broadcast(Messages.info("SERVER: " + msg)); } @Command(aliases = {"alert"}, desc = "Send out a broadcast message") @Require("plume.broadcast.broadcast") public void alert(@Sender ICommandSender sender, @Text String msg) { Messages.broadcast(Messages.error("SERVER: " + msg)); } @Command(aliases = {"print"}, desc = "Print an unformatted message to chat") @Require("plume.broadcast.print") public void print(@Sender ICommandSender sender, @Text String msg) { Messages.broadcast(new ChatComponentText(msg)); } } # ... rest of the code ...
f3eeb19249fae51a5537735cd5966596194cdc36
pages/widgets_registry.py
pages/widgets_registry.py
__all__ = ('register_widget',) from django.utils.translation import ugettext as _ class WidgetAlreadyRegistered(Exception): """ An attempt was made to register a widget for Django page CMS more than once. """ pass class WidgetNotFound(Exception): """ The requested widget was not found """ pass registry = [] def register_widget(widget): if widget in registry: raise AlreadyRegistered( _('The widget %s has already been registered.') % widget.__name__) registry.append(widget) def get_widget(name): for widget in registry: if widget.__name__ == name: return widget raise WidgetNotFound( _('The widget %s has not been registered.') % name)
__all__ = ('register_widget',) from django.utils.translation import ugettext as _ class WidgetAlreadyRegistered(Exception): """ An attempt was made to register a widget for Django page CMS more than once. """ pass class WidgetNotFound(Exception): """ The requested widget was not found """ pass registry = [] def register_widget(widget): if widget in registry: raise WidgetAlreadyRegistered(_('The widget %s has already been registered.') % widget.__name__) registry.append(widget) def get_widget(name): for widget in registry: if widget.__name__ == name: return widget raise WidgetNotFound( _('The widget %s has not been registered.') % name)
Fix widget registry exception handling code
Fix widget registry exception handling code
Python
bsd-3-clause
batiste/django-page-cms,remik/django-page-cms,batiste/django-page-cms,oliciv/django-page-cms,oliciv/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,remik/django-page-cms,akaihola/django-page-cms,oliciv/django-page-cms,pombredanne/django-page-cms-1,batiste/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1,pombredanne/django-page-cms-1,remik/django-page-cms
python
## Code Before: __all__ = ('register_widget',) from django.utils.translation import ugettext as _ class WidgetAlreadyRegistered(Exception): """ An attempt was made to register a widget for Django page CMS more than once. """ pass class WidgetNotFound(Exception): """ The requested widget was not found """ pass registry = [] def register_widget(widget): if widget in registry: raise AlreadyRegistered( _('The widget %s has already been registered.') % widget.__name__) registry.append(widget) def get_widget(name): for widget in registry: if widget.__name__ == name: return widget raise WidgetNotFound( _('The widget %s has not been registered.') % name) ## Instruction: Fix widget registry exception handling code ## Code After: __all__ = ('register_widget',) from django.utils.translation import ugettext as _ class WidgetAlreadyRegistered(Exception): """ An attempt was made to register a widget for Django page CMS more than once. """ pass class WidgetNotFound(Exception): """ The requested widget was not found """ pass registry = [] def register_widget(widget): if widget in registry: raise WidgetAlreadyRegistered(_('The widget %s has already been registered.') % widget.__name__) registry.append(widget) def get_widget(name): for widget in registry: if widget.__name__ == name: return widget raise WidgetNotFound( _('The widget %s has not been registered.') % name)
// ... existing code ... def register_widget(widget): if widget in registry: raise WidgetAlreadyRegistered(_('The widget %s has already been registered.') % widget.__name__) registry.append(widget) def get_widget(name): // ... rest of the code ...
7500220568918ec9dd09636c9f694a2431c0d1af
src/main/java/net/bourgau/philippe/concurrency/kata/TextLineProtocol.java
src/main/java/net/bourgau/philippe/concurrency/kata/TextLineProtocol.java
package net.bourgau.philippe.concurrency.kata; import org.apache.commons.io.IOUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; public class TextLineProtocol implements AutoCloseable { private final Socket socket; private BufferedReader reader; private BufferedWriter writer; public TextLineProtocol(Socket socket) throws Exception { this.socket = socket; reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); } public void writeMessage(String message) throws Exception { writer.write(message + "\n"); writer.flush(); } public String readMessage() throws Exception { return reader.readLine(); } @Override public void close() { IOUtils.closeQuietly(socket); } }
package net.bourgau.philippe.concurrency.kata; import org.apache.commons.io.IOUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; public class TextLineProtocol implements AutoCloseable { private final Socket socket; private BufferedReader reader; private BufferedWriter writer; public TextLineProtocol(Socket socket) throws Exception { this.socket = socket; socket.setSoTimeout(250); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); } public void writeMessage(String message) throws Exception { writer.write(message + "\n"); writer.flush(); } public String readMessage() throws Exception { String message = null; while (!Thread.interrupted()) { try { message = reader.readLine(); break; } catch (SocketTimeoutException ignoreTimeoutAndRetry) { continue; } } if (message == null) { throw new SocketException("Socket was closed before a message could be read"); } return message; } @Override public void close() { IOUtils.closeQuietly(socket); } }
Make reading from sockets more robust
Make reading from sockets more robust - throw SocketException if nothing could be read from the socket - use timeout version of socket read
Java
mit
philou/concurrency-kata,philou/concurrency-kata
java
## Code Before: package net.bourgau.philippe.concurrency.kata; import org.apache.commons.io.IOUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; public class TextLineProtocol implements AutoCloseable { private final Socket socket; private BufferedReader reader; private BufferedWriter writer; public TextLineProtocol(Socket socket) throws Exception { this.socket = socket; reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); } public void writeMessage(String message) throws Exception { writer.write(message + "\n"); writer.flush(); } public String readMessage() throws Exception { return reader.readLine(); } @Override public void close() { IOUtils.closeQuietly(socket); } } ## Instruction: Make reading from sockets more robust - throw SocketException if nothing could be read from the socket - use timeout version of socket read ## Code After: package net.bourgau.philippe.concurrency.kata; import org.apache.commons.io.IOUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; public class TextLineProtocol implements AutoCloseable { private final Socket socket; private BufferedReader reader; private BufferedWriter writer; public TextLineProtocol(Socket socket) throws Exception { this.socket = socket; socket.setSoTimeout(250); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); } public void writeMessage(String message) throws Exception { writer.write(message + "\n"); writer.flush(); } public String readMessage() throws Exception { String message = null; while (!Thread.interrupted()) { try { message = reader.readLine(); break; } catch (SocketTimeoutException ignoreTimeoutAndRetry) { continue; } } if (message == null) { throw new SocketException("Socket was closed before a message could be read"); } return message; } @Override public void close() { IOUtils.closeQuietly(socket); } }
// ... existing code ... import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; public class TextLineProtocol implements AutoCloseable { private final Socket socket; // ... modified code ... public TextLineProtocol(Socket socket) throws Exception { this.socket = socket; socket.setSoTimeout(250); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); } ... } public String readMessage() throws Exception { String message = null; while (!Thread.interrupted()) { try { message = reader.readLine(); break; } catch (SocketTimeoutException ignoreTimeoutAndRetry) { continue; } } if (message == null) { throw new SocketException("Socket was closed before a message could be read"); } return message; } @Override // ... rest of the code ...
6a7a553dd51abbd6ade2e448bae0e4e2a8036f23
generate-data.py
generate-data.py
import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): data = ['0' for i in range(numx * numy)] stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) data[stimulus[1] * numx + stimulus[0]] = '1' return data, stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): data, stimulus = generate_data(gridDim[0], gridDim[1]) print_input(data, data) # duplicate for two eyes scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y))
import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): ldata = ['0' for i in range(numx * numy)] rdata = ['0' for i in range(numx * numy)] stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) ldata[stimulus[1] * numx + stimulus[0]] = '1' rdata[stimulus[1] * numx + stimulus[0]] = '1' return ldata, rdata, stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): ldata, rdata, stimulus = generate_data(gridDim[0], gridDim[1]) print_input(ldata, rdata) scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y))
Add separate left and right eye data generation
Add separate left and right eye data generation
Python
mit
jeffames-cs/nnot
python
## Code Before: import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): data = ['0' for i in range(numx * numy)] stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) data[stimulus[1] * numx + stimulus[0]] = '1' return data, stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): data, stimulus = generate_data(gridDim[0], gridDim[1]) print_input(data, data) # duplicate for two eyes scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y)) ## Instruction: Add separate left and right eye data generation ## Code After: import random from nott_params import * num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): ldata = ['0' for i in range(numx * numy)] rdata = ['0' for i in range(numx * numy)] stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) ldata[stimulus[1] * numx + stimulus[0]] = '1' rdata[stimulus[1] * numx + stimulus[0]] = '1' return ldata, rdata, stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) def print_input(left, right): data = left + right print(' '.join(data)) if __name__ == '__main__': random.seed() print_header() for i in range(num_samples): ldata, rdata, stimulus = generate_data(gridDim[0], gridDim[1]) print_input(ldata, rdata) scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, scaled_x, scaled_y))
... num_samples = int(gridDim[0] * gridDim[1] * 10) def generate_data(numx, numy): ldata = ['0' for i in range(numx * numy)] rdata = ['0' for i in range(numx * numy)] stimulus = (random.randint(0, numx - 1), random.randint(0, numy - 1)) ldata[stimulus[1] * numx + stimulus[0]] = '1' rdata[stimulus[1] * numx + stimulus[0]] = '1' return ldata, rdata, stimulus def print_header(): print("{0} {1} {2}".format(num_samples, num_inputs, num_outputs)) ... random.seed() print_header() for i in range(num_samples): ldata, rdata, stimulus = generate_data(gridDim[0], gridDim[1]) print_input(ldata, rdata) scaled_x = 2 * float(stimulus[0]) / gridDim[0] - 1 scaled_y = 2 * float(stimulus[1]) / gridDim[1] - 1 print("{0} {1} {2} {3}".format(scaled_x, scaled_y, ...
151599602b9d626ebcfe5ae6960ea216b767fec2
setuptools/distutils_patch.py
setuptools/distutils_patch.py
import sys import importlib from os.path import dirname sys.path.insert(0, dirname(dirname(__file__))) importlib.import_module('distutils') sys.path.pop(0)
import sys import importlib import contextlib from os.path import dirname @contextlib.contextmanager def patch_sys_path(): orig = sys.path[:] sys.path[:] = [dirname(dirname(__file__))] try: yield finally: sys.path[:] = orig if 'distutils' in sys.path: raise RuntimeError("Distutils must not be imported before setuptools") with patch_sys_path(): importlib.import_module('distutils')
Update distutils patch to monkeypatch all paths from sys.path to ensure that distutils is never imported except from the same path as setuptools. Assert that 'distutils' is not already in sys.modules.
Update distutils patch to monkeypatch all paths from sys.path to ensure that distutils is never imported except from the same path as setuptools. Assert that 'distutils' is not already in sys.modules.
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
python
## Code Before: import sys import importlib from os.path import dirname sys.path.insert(0, dirname(dirname(__file__))) importlib.import_module('distutils') sys.path.pop(0) ## Instruction: Update distutils patch to monkeypatch all paths from sys.path to ensure that distutils is never imported except from the same path as setuptools. Assert that 'distutils' is not already in sys.modules. ## Code After: import sys import importlib import contextlib from os.path import dirname @contextlib.contextmanager def patch_sys_path(): orig = sys.path[:] sys.path[:] = [dirname(dirname(__file__))] try: yield finally: sys.path[:] = orig if 'distutils' in sys.path: raise RuntimeError("Distutils must not be imported before setuptools") with patch_sys_path(): importlib.import_module('distutils')
... import sys import importlib import contextlib from os.path import dirname @contextlib.contextmanager def patch_sys_path(): orig = sys.path[:] sys.path[:] = [dirname(dirname(__file__))] try: yield finally: sys.path[:] = orig if 'distutils' in sys.path: raise RuntimeError("Distutils must not be imported before setuptools") with patch_sys_path(): importlib.import_module('distutils') ...
b7b41a160294edd987f73be7817c8b08aa8ed70e
herders/templatetags/utils.py
herders/templatetags/utils.py
from django import template register = template.Library() @register.filter def get_range(value): return range(value) @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_')
from django import template register = template.Library() @register.filter def get_range(value): if value: return range(value) else: return 0 @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_')
Return 0 with the get_range filter if value is invalid instead of raise exception
Return 0 with the get_range filter if value is invalid instead of raise exception
Python
apache-2.0
porksmash/swarfarm,PeteAndersen/swarfarm,PeteAndersen/swarfarm,porksmash/swarfarm,PeteAndersen/swarfarm,porksmash/swarfarm,porksmash/swarfarm,PeteAndersen/swarfarm
python
## Code Before: from django import template register = template.Library() @register.filter def get_range(value): return range(value) @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_') ## Instruction: Return 0 with the get_range filter if value is invalid instead of raise exception ## Code After: from django import template register = template.Library() @register.filter def get_range(value): if value: return range(value) else: return 0 @register.filter def absolute(value): return abs(value) @register.filter def subtract(value, arg): return value - arg @register.filter def multiply(value, arg): return value * arg @register.filter def remove_extension(string): return string.replace('.png', '').replace("'", "").replace('(', '_').replace(')', '_')
... @register.filter def get_range(value): if value: return range(value) else: return 0 @register.filter ...
09ec6e4611a763e823a5e3d15fb233a0132fd06b
imagersite/imagersite/tests.py
imagersite/imagersite/tests.py
from django.test import Client, TestCase from django.contrib.auth.models import User HOME = '/' REGISTER = '/accounts/register/' LOGIN = '/login' LOGOUT = '/logout' class UnauthenticatedUser(TestCase): """Create unauth user for testing.""" def setUp(self): """Setup unauth user.""" client = Client() self.home = client.get(HOME) self.login = client.get(LOGIN) self.logout = client.get(LOGOUT) self.register = client.get(REGISTER) def test_no_user_in_db(self): """No user i db.""" self.assertFalse(User.objects.count()) def test_homepage(self): """Test homepage can be reached.""" self.assertEqual(self.home.status_code, 200) def test_login(self): """Test login cna be reached.""" self.assertEqual(self.login.status_code, 200) def test_logout(self): """Test logout can be reached.""" self.assertEqual(self.logout.status_code, 200) def test_register(self): """Test register can be reached.""" self.assertEqual(self.register.status_code, 200)
"""Tests for project level urls and views.""" from __future__ import unicode_literals from django.contrib.staticfiles import finders from django.test import Client, TestCase from django.contrib.auth.models import User HOME = '/' REGISTER = '/accounts/register/' LOGIN = '/login' LOGOUT = '/logout' DEFAULT_IMAGE = finders.find('static/imagersite/images/default-image.jpg') class UnauthenticatedUser(TestCase): """Create unauth user for testing.""" def setUp(self): """Setup unauth user.""" client = Client() self.home = client.get(HOME) self.login = client.get(LOGIN) self.logout = client.get(LOGOUT) self.register = client.get(REGISTER) def test_no_user_in_db(self): """No user i db.""" self.assertFalse(User.objects.count()) def test_homepage(self): """Test homepage can be reached.""" self.assertEqual(self.home.status_code, 200) def test_login(self): """Test login cna be reached.""" self.assertEqual(self.login.status_code, 200) def test_logout(self): """Test logout can be reached.""" self.assertEqual(self.logout.status_code, 200) def test_register(self): """Test register can be reached.""" self.assertEqual(self.register.status_code, 200) def test_default_image(self): """Test default image shows up.""" img_path = self.home.context['image'] self.assertEqual(img_path, DEFAULT_IMAGE)
Add passing test for default image
Add passing test for default image
Python
mit
SeleniumK/django-imager,SeleniumK/django-imager,SeleniumK/django-imager
python
## Code Before: from django.test import Client, TestCase from django.contrib.auth.models import User HOME = '/' REGISTER = '/accounts/register/' LOGIN = '/login' LOGOUT = '/logout' class UnauthenticatedUser(TestCase): """Create unauth user for testing.""" def setUp(self): """Setup unauth user.""" client = Client() self.home = client.get(HOME) self.login = client.get(LOGIN) self.logout = client.get(LOGOUT) self.register = client.get(REGISTER) def test_no_user_in_db(self): """No user i db.""" self.assertFalse(User.objects.count()) def test_homepage(self): """Test homepage can be reached.""" self.assertEqual(self.home.status_code, 200) def test_login(self): """Test login cna be reached.""" self.assertEqual(self.login.status_code, 200) def test_logout(self): """Test logout can be reached.""" self.assertEqual(self.logout.status_code, 200) def test_register(self): """Test register can be reached.""" self.assertEqual(self.register.status_code, 200) ## Instruction: Add passing test for default image ## Code After: """Tests for project level urls and views.""" from __future__ import unicode_literals from django.contrib.staticfiles import finders from django.test import Client, TestCase from django.contrib.auth.models import User HOME = '/' REGISTER = '/accounts/register/' LOGIN = '/login' LOGOUT = '/logout' DEFAULT_IMAGE = finders.find('static/imagersite/images/default-image.jpg') class UnauthenticatedUser(TestCase): """Create unauth user for testing.""" def setUp(self): """Setup unauth user.""" client = Client() self.home = client.get(HOME) self.login = client.get(LOGIN) self.logout = client.get(LOGOUT) self.register = client.get(REGISTER) def test_no_user_in_db(self): """No user i db.""" self.assertFalse(User.objects.count()) def test_homepage(self): """Test homepage can be reached.""" self.assertEqual(self.home.status_code, 200) def test_login(self): """Test login cna be reached.""" self.assertEqual(self.login.status_code, 200) def test_logout(self): """Test logout can be reached.""" self.assertEqual(self.logout.status_code, 200) def test_register(self): """Test register can be reached.""" self.assertEqual(self.register.status_code, 200) def test_default_image(self): """Test default image shows up.""" img_path = self.home.context['image'] self.assertEqual(img_path, DEFAULT_IMAGE)
# ... existing code ... """Tests for project level urls and views.""" from __future__ import unicode_literals from django.contrib.staticfiles import finders from django.test import Client, TestCase from django.contrib.auth.models import User # ... modified code ... REGISTER = '/accounts/register/' LOGIN = '/login' LOGOUT = '/logout' DEFAULT_IMAGE = finders.find('static/imagersite/images/default-image.jpg') class UnauthenticatedUser(TestCase): ... def test_register(self): """Test register can be reached.""" self.assertEqual(self.register.status_code, 200) def test_default_image(self): """Test default image shows up.""" img_path = self.home.context['image'] self.assertEqual(img_path, DEFAULT_IMAGE) # ... rest of the code ...
f78e20b05a5d7ede84f80a9be16a6a40a1a7abf8
ifs/cli.py
ifs/cli.py
import click import lib @click.group() def cli(): """ Install From Source When the version in the package manager has gone stale, get a fresh, production-ready version from a source tarball or precompiled archive. Send issues or improvements to https://github.com/cbednarski/ifs """ pass @cli.command() def ls(): for app in lib.list_apps(): click.echo(app) @cli.command() @click.argument('term') def search(term): for app in lib.list_apps(): if term in app: click.echo(app) @cli.command() @click.argument('application') def install(application): click.echo(lib.install(application)) @cli.command() @click.argument('application') def info(application): """ Show information about an application from ifs ls """ info = lib.app_info(application) for k, v in info.iteritems(): if type(v) is list: v = ' '.join(v) click.echo('%s: %s' % (k, v)) if __name__ == '__main__': cli()
import click import lib @click.group() def cli(): """ Install From Source When the version in the package manager has gone stale, get a fresh, production-ready version from a source tarball or precompiled archive. Send issues or improvements to https://github.com/cbednarski/ifs """ pass @cli.command() def ls(): for app in lib.list_apps(): click.echo(app) @cli.command() @click.argument('term') def search(term): for app in lib.list_apps(): if term in app: click.echo(app) @cli.command() @click.argument('application') def install(application): cmd = lib.install(application) click.echo(cmd.output) exit(cmd.returncode) @cli.command() @click.argument('application') def info(application): """ Show information about an application from ifs ls """ info = lib.app_info(application) for k, v in info.iteritems(): if type(v) is list: v = ' '.join(v) click.echo('%s: %s' % (k, v)) if __name__ == '__main__': cli()
Exit with return code from called script
Exit with return code from called script
Python
isc
cbednarski/ifs-python,cbednarski/ifs-python
python
## Code Before: import click import lib @click.group() def cli(): """ Install From Source When the version in the package manager has gone stale, get a fresh, production-ready version from a source tarball or precompiled archive. Send issues or improvements to https://github.com/cbednarski/ifs """ pass @cli.command() def ls(): for app in lib.list_apps(): click.echo(app) @cli.command() @click.argument('term') def search(term): for app in lib.list_apps(): if term in app: click.echo(app) @cli.command() @click.argument('application') def install(application): click.echo(lib.install(application)) @cli.command() @click.argument('application') def info(application): """ Show information about an application from ifs ls """ info = lib.app_info(application) for k, v in info.iteritems(): if type(v) is list: v = ' '.join(v) click.echo('%s: %s' % (k, v)) if __name__ == '__main__': cli() ## Instruction: Exit with return code from called script ## Code After: import click import lib @click.group() def cli(): """ Install From Source When the version in the package manager has gone stale, get a fresh, production-ready version from a source tarball or precompiled archive. Send issues or improvements to https://github.com/cbednarski/ifs """ pass @cli.command() def ls(): for app in lib.list_apps(): click.echo(app) @cli.command() @click.argument('term') def search(term): for app in lib.list_apps(): if term in app: click.echo(app) @cli.command() @click.argument('application') def install(application): cmd = lib.install(application) click.echo(cmd.output) exit(cmd.returncode) @cli.command() @click.argument('application') def info(application): """ Show information about an application from ifs ls """ info = lib.app_info(application) for k, v in info.iteritems(): if type(v) is list: v = ' '.join(v) click.echo('%s: %s' % (k, v)) if __name__ == '__main__': cli()
# ... existing code ... @cli.command() @click.argument('application') def install(application): cmd = lib.install(application) click.echo(cmd.output) exit(cmd.returncode) @cli.command() # ... rest of the code ...
dcd2442442bd85cba988f69e973de304c2c5afc9
src/main/java/com/minelittlepony/client/render/MagicGlow.java
src/main/java/com/minelittlepony/client/render/MagicGlow.java
package com.minelittlepony.client.render; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.RenderPhase; import net.minecraft.client.render.VertexFormats; public class MagicGlow extends RenderPhase { public MagicGlow(String name, Runnable beginAction, Runnable endAction) { super(name, beginAction, endAction); } public static RenderLayer getRenderLayer() { return RenderLayer.method_24048("mlp_magic_glow", VertexFormats.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 256, RenderLayer.MultiPhaseData.builder() .texture(NO_TEXTURE) .transparency(TRANSLUCENT_TRANSPARENCY) .lightmap(DISABLE_LIGHTMAP) .cull(DISABLE_CULLING) .build(false)); } }
package com.minelittlepony.client.render; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.RenderPhase; import net.minecraft.client.render.VertexFormats; public class MagicGlow extends RenderPhase { private MagicGlow(String name, Runnable beginAction, Runnable endAction) { super(name, beginAction, endAction); } static final RenderLayer MAGIC = RenderLayer.method_24048("mlp_magic_glow", VertexFormats.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 256, RenderLayer.MultiPhaseData.builder() .texture(NO_TEXTURE) .transparency(TRANSLUCENT_TRANSPARENCY) .lightmap(DISABLE_LIGHTMAP) .cull(DISABLE_CULLING) .build(false)); public static RenderLayer getRenderLayer() { return MAGIC; } }
Tidy up the magic glow layer
Tidy up the magic glow layer
Java
mit
MineLittlePony/MineLittlePony,MineLittlePony/MineLittlePony
java
## Code Before: package com.minelittlepony.client.render; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.RenderPhase; import net.minecraft.client.render.VertexFormats; public class MagicGlow extends RenderPhase { public MagicGlow(String name, Runnable beginAction, Runnable endAction) { super(name, beginAction, endAction); } public static RenderLayer getRenderLayer() { return RenderLayer.method_24048("mlp_magic_glow", VertexFormats.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 256, RenderLayer.MultiPhaseData.builder() .texture(NO_TEXTURE) .transparency(TRANSLUCENT_TRANSPARENCY) .lightmap(DISABLE_LIGHTMAP) .cull(DISABLE_CULLING) .build(false)); } } ## Instruction: Tidy up the magic glow layer ## Code After: package com.minelittlepony.client.render; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.RenderPhase; import net.minecraft.client.render.VertexFormats; public class MagicGlow extends RenderPhase { private MagicGlow(String name, Runnable beginAction, Runnable endAction) { super(name, beginAction, endAction); } static final RenderLayer MAGIC = RenderLayer.method_24048("mlp_magic_glow", VertexFormats.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 256, RenderLayer.MultiPhaseData.builder() .texture(NO_TEXTURE) .transparency(TRANSLUCENT_TRANSPARENCY) .lightmap(DISABLE_LIGHTMAP) .cull(DISABLE_CULLING) .build(false)); public static RenderLayer getRenderLayer() { return MAGIC; } }
# ... existing code ... import net.minecraft.client.render.VertexFormats; public class MagicGlow extends RenderPhase { private MagicGlow(String name, Runnable beginAction, Runnable endAction) { super(name, beginAction, endAction); } static final RenderLayer MAGIC = RenderLayer.method_24048("mlp_magic_glow", VertexFormats.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 256, RenderLayer.MultiPhaseData.builder() .texture(NO_TEXTURE) .transparency(TRANSLUCENT_TRANSPARENCY) .lightmap(DISABLE_LIGHTMAP) .cull(DISABLE_CULLING) .build(false)); public static RenderLayer getRenderLayer() { return MAGIC; } } # ... rest of the code ...
b5fe71191bc7c39996d526132720a22c3967b1cf
canopus/schema/core.py
canopus/schema/core.py
from marshmallow import Schema, fields from ..models.core import Post class PostSchema(Schema): id = fields.Integer() title = fields.String() body = fields.String() is_published = fields.Boolean() def make_object(self, data): return Post(**data)
from marshmallow import Schema, fields, post_load from ..models import Post class PostSchema(Schema): __model__ = Post id = fields.Integer() title = fields.String() body = fields.String() is_published = fields.Boolean() class Meta: ordered = True @post_load def make_object(self, data): return self.__model__(**data)
Fix post schema for latest marshmallow release
Fix post schema for latest marshmallow release
Python
mit
josuemontano/pyramid-angularjs-starter,josuemontano/pyramid-angularjs-starter,josuemontano/pyramid-angularjs-starter,josuemontano/API-platform,josuemontano/api-starter,josuemontano/API-platform,josuemontano/api-starter,josuemontano/api-starter,josuemontano/API-platform,josuemontano/API-platform
python
## Code Before: from marshmallow import Schema, fields from ..models.core import Post class PostSchema(Schema): id = fields.Integer() title = fields.String() body = fields.String() is_published = fields.Boolean() def make_object(self, data): return Post(**data) ## Instruction: Fix post schema for latest marshmallow release ## Code After: from marshmallow import Schema, fields, post_load from ..models import Post class PostSchema(Schema): __model__ = Post id = fields.Integer() title = fields.String() body = fields.String() is_published = fields.Boolean() class Meta: ordered = True @post_load def make_object(self, data): return self.__model__(**data)
# ... existing code ... from marshmallow import Schema, fields, post_load from ..models import Post class PostSchema(Schema): __model__ = Post id = fields.Integer() title = fields.String() body = fields.String() is_published = fields.Boolean() class Meta: ordered = True @post_load def make_object(self, data): return self.__model__(**data) # ... rest of the code ...
67d3193683d2215fdd660bdc086801fe761c7db7
src/views.py
src/views.py
from flask import render_template from app import app @app.route('/') def index(): return render_template('index.html', active='index') @app.route('/contact/') def contact(): return render_template('contact.html', active='contact') @app.context_processor def utility_processor(): def page_title(title=None): return "{} | {}".format(title, app.config['SITE_TITLE']) if title \ else app.config['SITE_TITLE'] def post_source(path): return '{}{}{}'.format(app.config['POST_SOURCE_ROOT'], path, app.config['FLATPAGES_EXTENSION']) return dict(page_title=page_title, post_source=post_source) @app.template_filter('date') def date_filter(date): return date.strftime('%B %-d, %Y')
import os from flask import render_template from flask import send_from_directory from app import app @app.route('/') def index(): return render_template('index.html', active='index') @app.route('/contact/') def contact(): return render_template('contact.html', active='contact') @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon') @app.context_processor def utility_processor(): def page_title(title=None): return "{} | {}".format(title, app.config['SITE_TITLE']) if title \ else app.config['SITE_TITLE'] def post_source(path): return '{}{}{}'.format(app.config['POST_SOURCE_ROOT'], path, app.config['FLATPAGES_EXTENSION']) return dict(page_title=page_title, post_source=post_source) @app.template_filter('date') def date_filter(date): return date.strftime('%B %-d, %Y')
Make the favicon available at /favicon.ico
Make the favicon available at /favicon.ico
Python
mit
matachi/MaTachi.github.io,matachi/MaTachi.github.io
python
## Code Before: from flask import render_template from app import app @app.route('/') def index(): return render_template('index.html', active='index') @app.route('/contact/') def contact(): return render_template('contact.html', active='contact') @app.context_processor def utility_processor(): def page_title(title=None): return "{} | {}".format(title, app.config['SITE_TITLE']) if title \ else app.config['SITE_TITLE'] def post_source(path): return '{}{}{}'.format(app.config['POST_SOURCE_ROOT'], path, app.config['FLATPAGES_EXTENSION']) return dict(page_title=page_title, post_source=post_source) @app.template_filter('date') def date_filter(date): return date.strftime('%B %-d, %Y') ## Instruction: Make the favicon available at /favicon.ico ## Code After: import os from flask import render_template from flask import send_from_directory from app import app @app.route('/') def index(): return render_template('index.html', active='index') @app.route('/contact/') def contact(): return render_template('contact.html', active='contact') @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon') @app.context_processor def utility_processor(): def page_title(title=None): return "{} | {}".format(title, app.config['SITE_TITLE']) if title \ else app.config['SITE_TITLE'] def post_source(path): return '{}{}{}'.format(app.config['POST_SOURCE_ROOT'], path, app.config['FLATPAGES_EXTENSION']) return dict(page_title=page_title, post_source=post_source) @app.template_filter('date') def date_filter(date): return date.strftime('%B %-d, %Y')
# ... existing code ... import os from flask import render_template from flask import send_from_directory from app import app @app.route('/') # ... modified code ... @app.route('/contact/') def contact(): return render_template('contact.html', active='contact') @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon') @app.context_processor def utility_processor(): # ... rest of the code ...
e68cb906810a26d93e0d15e0357a75a2b49d8784
boundary/plugin_get_components.py
boundary/plugin_get_components.py
from boundary import ApiCli class PluginGetComponents (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path="v1/plugins" self.pluginName = None def addArguments(self): ApiCli.addArguments(self) self.parser.add_argument('-n', '--plugin-Name', dest='pluginName',action='store',required=True,help='Plugin name') def getArguments(self): ''' Extracts the specific arguments of this CLI ''' ApiCli.getArguments(self) if self.args.pluginName != None: self.pluginName = self.args.pluginName self.path = "v1/plugins/{0}/components".format(self.pluginName) def getDescription(self): return "Get the components of a plugin in a Boundary account"
from boundary import ApiCli class PluginGetComponents(ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/plugins" self.pluginName = None def addArguments(self): ApiCli.addArguments(self) self.parser.add_argument('-n', '--plugin-Name', dest='pluginName', action='store', metavar='plugin_name', required=True, help='Plugin name') def getArguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.getArguments(self) if self.args.pluginName is not None: self.pluginName = self.args.pluginName self.path = "v1/plugins/{0}/components".format(self.pluginName) def getDescription(self): return "Get the components of a plugin in a Boundary account"
Reformat code to PEP-8 standards
Reformat code to PEP-8 standards
Python
apache-2.0
jdgwartney/boundary-api-cli,boundary/pulse-api-cli,wcainboundary/boundary-api-cli,jdgwartney/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/boundary-api-cli,boundary/pulse-api-cli,boundary/boundary-api-cli,wcainboundary/boundary-api-cli,jdgwartney/pulse-api-cli
python
## Code Before: from boundary import ApiCli class PluginGetComponents (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path="v1/plugins" self.pluginName = None def addArguments(self): ApiCli.addArguments(self) self.parser.add_argument('-n', '--plugin-Name', dest='pluginName',action='store',required=True,help='Plugin name') def getArguments(self): ''' Extracts the specific arguments of this CLI ''' ApiCli.getArguments(self) if self.args.pluginName != None: self.pluginName = self.args.pluginName self.path = "v1/plugins/{0}/components".format(self.pluginName) def getDescription(self): return "Get the components of a plugin in a Boundary account" ## Instruction: Reformat code to PEP-8 standards ## Code After: from boundary import ApiCli class PluginGetComponents(ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/plugins" self.pluginName = None def addArguments(self): ApiCli.addArguments(self) self.parser.add_argument('-n', '--plugin-Name', dest='pluginName', action='store', metavar='plugin_name', required=True, help='Plugin name') def getArguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.getArguments(self) if self.args.pluginName is not None: self.pluginName = self.args.pluginName self.path = "v1/plugins/{0}/components".format(self.pluginName) def getDescription(self): return "Get the components of a plugin in a Boundary account"
# ... existing code ... from boundary import ApiCli class PluginGetComponents(ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/plugins" self.pluginName = None def addArguments(self): ApiCli.addArguments(self) self.parser.add_argument('-n', '--plugin-Name', dest='pluginName', action='store', metavar='plugin_name', required=True, help='Plugin name') def getArguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.getArguments(self) if self.args.pluginName is not None: self.pluginName = self.args.pluginName self.path = "v1/plugins/{0}/components".format(self.pluginName) def getDescription(self): return "Get the components of a plugin in a Boundary account" # ... rest of the code ...
ec1f7db3f1bd637807b4b9d69a0b702af36fbef1
morenines/ignores.py
morenines/ignores.py
import os from fnmatch import fnmatchcase import click class Ignores(object): @classmethod def read(cls, path): ignores = cls() if path: with click.open_file(path, 'r') as stream: ignores.patterns = [line.strip() for line in stream] return ignores def __init__(self): self.patterns = [] def match(self, path): filename = os.path.basename(path) if any(fnmatchcase(filename, pattern) for pattern in self.patterns): return True else: return False
import os from fnmatch import fnmatchcase import click from morenines.util import find_file class Ignores(object): @classmethod def read(cls, path): if not path: path = find_file('.mnignore') ignores = cls() if path: with click.open_file(path, 'r') as stream: ignores.patterns = [line.strip() for line in stream] return ignores def __init__(self): self.patterns = [] def match(self, path): filename = os.path.basename(path) if any(fnmatchcase(filename, pattern) for pattern in self.patterns): return True else: return False
Make Ignores try to find '.mnignore'
Make Ignores try to find '.mnignore' If it doesn't find it, that's okay, and no action is required.
Python
mit
mcgid/morenines,mcgid/morenines
python
## Code Before: import os from fnmatch import fnmatchcase import click class Ignores(object): @classmethod def read(cls, path): ignores = cls() if path: with click.open_file(path, 'r') as stream: ignores.patterns = [line.strip() for line in stream] return ignores def __init__(self): self.patterns = [] def match(self, path): filename = os.path.basename(path) if any(fnmatchcase(filename, pattern) for pattern in self.patterns): return True else: return False ## Instruction: Make Ignores try to find '.mnignore' If it doesn't find it, that's okay, and no action is required. ## Code After: import os from fnmatch import fnmatchcase import click from morenines.util import find_file class Ignores(object): @classmethod def read(cls, path): if not path: path = find_file('.mnignore') ignores = cls() if path: with click.open_file(path, 'r') as stream: ignores.patterns = [line.strip() for line in stream] return ignores def __init__(self): self.patterns = [] def match(self, path): filename = os.path.basename(path) if any(fnmatchcase(filename, pattern) for pattern in self.patterns): return True else: return False
... from fnmatch import fnmatchcase import click from morenines.util import find_file class Ignores(object): @classmethod def read(cls, path): if not path: path = find_file('.mnignore') ignores = cls() if path: ...
31bfe8fb498ea2e528da6463c9045b397992e028
python/caffe/test/test_draw.py
python/caffe/test/test_draw.py
import os import unittest from google import protobuf import caffe.draw from caffe.proto import caffe_pb2 def getFilenames(): """Yields files in the source tree which are Net prototxts.""" result = [] root_dir = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..', '..')) assert os.path.exists(root_dir) for dirname in ('models', 'examples'): dirname = os.path.join(root_dir, dirname) assert os.path.exists(dirname) for cwd, _, filenames in os.walk(dirname): for filename in filenames: filename = os.path.join(cwd, filename) if filename.endswith('.prototxt') and 'solver' not in filename: yield os.path.join(dirname, filename) class TestDraw(unittest.TestCase): def test_draw_net(self): for filename in getFilenames(): net = caffe_pb2.NetParameter() with open(filename) as infile: protobuf.text_format.Merge(infile.read(), net) caffe.draw.draw_net(net, 'LR')
import os import unittest from google.protobuf import text_format import caffe.draw from caffe.proto import caffe_pb2 def getFilenames(): """Yields files in the source tree which are Net prototxts.""" result = [] root_dir = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..', '..')) assert os.path.exists(root_dir) for dirname in ('models', 'examples'): dirname = os.path.join(root_dir, dirname) assert os.path.exists(dirname) for cwd, _, filenames in os.walk(dirname): for filename in filenames: filename = os.path.join(cwd, filename) if filename.endswith('.prototxt') and 'solver' not in filename: yield os.path.join(dirname, filename) class TestDraw(unittest.TestCase): def test_draw_net(self): for filename in getFilenames(): net = caffe_pb2.NetParameter() with open(filename) as infile: text_format.Merge(infile.read(), net) caffe.draw.draw_net(net, 'LR') if __name__ == "__main__": unittest.main()
Add main() for draw_net unittest, fix import errors
Add main() for draw_net unittest, fix import errors
Python
apache-2.0
gnina/gnina,gnina/gnina,gnina/gnina,gnina/gnina,gnina/gnina,gnina/gnina
python
## Code Before: import os import unittest from google import protobuf import caffe.draw from caffe.proto import caffe_pb2 def getFilenames(): """Yields files in the source tree which are Net prototxts.""" result = [] root_dir = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..', '..')) assert os.path.exists(root_dir) for dirname in ('models', 'examples'): dirname = os.path.join(root_dir, dirname) assert os.path.exists(dirname) for cwd, _, filenames in os.walk(dirname): for filename in filenames: filename = os.path.join(cwd, filename) if filename.endswith('.prototxt') and 'solver' not in filename: yield os.path.join(dirname, filename) class TestDraw(unittest.TestCase): def test_draw_net(self): for filename in getFilenames(): net = caffe_pb2.NetParameter() with open(filename) as infile: protobuf.text_format.Merge(infile.read(), net) caffe.draw.draw_net(net, 'LR') ## Instruction: Add main() for draw_net unittest, fix import errors ## Code After: import os import unittest from google.protobuf import text_format import caffe.draw from caffe.proto import caffe_pb2 def getFilenames(): """Yields files in the source tree which are Net prototxts.""" result = [] root_dir = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..', '..')) assert os.path.exists(root_dir) for dirname in ('models', 'examples'): dirname = os.path.join(root_dir, dirname) assert os.path.exists(dirname) for cwd, _, filenames in os.walk(dirname): for filename in filenames: filename = os.path.join(cwd, filename) if filename.endswith('.prototxt') and 'solver' not in filename: yield os.path.join(dirname, filename) class TestDraw(unittest.TestCase): def test_draw_net(self): for filename in getFilenames(): net = caffe_pb2.NetParameter() with open(filename) as infile: text_format.Merge(infile.read(), net) caffe.draw.draw_net(net, 'LR') if __name__ == "__main__": unittest.main()
// ... existing code ... import os import unittest from google.protobuf import text_format import caffe.draw from caffe.proto import caffe_pb2 // ... modified code ... for filename in getFilenames(): net = caffe_pb2.NetParameter() with open(filename) as infile: text_format.Merge(infile.read(), net) caffe.draw.draw_net(net, 'LR') if __name__ == "__main__": unittest.main() // ... rest of the code ...
d63905158f5148b07534e823d271326262369d42
pavement.py
pavement.py
import os import re from paver.easy import * from paver.setuputils import setup def get_version(): """ Grab the version from irclib.py. """ here = os.path.dirname(__file__) irclib = os.path.join(here, 'irclib.py') with open(irclib) as f: content = f.read() VERSION = eval(re.search('VERSION = (.*)', content).group(1)) VERSION = '.'.join(map(str, VERSION)) return VERSION def read_long_description(): f = open('README') try: data = f.read() finally: f.close() return data setup( name="python-irclib", description="IRC (Internet Relay Chat) protocol client library for Python", long_description=read_long_description(), version=get_version(), py_modules=["irclib", "ircbot"], author="Joel Rosdahl", author_email="[email protected]", maintainer="Jason R. Coombs", maintainer_email="[email protected]", url="http://python-irclib.sourceforge.net", classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", ], ) @task @needs('generate_setup', 'minilib', 'distutils.command.sdist') def sdist(): "Override sdist to make sure the setup.py gets generated"
import os import re from paver.easy import * from paver.setuputils import setup def get_version(): """ Grab the version from irclib.py. """ here = os.path.dirname(__file__) irclib = os.path.join(here, 'irclib.py') with open(irclib) as f: content = f.read() VERSION = eval(re.search('VERSION = (.*)', content).group(1)) VERSION = '.'.join(map(str, VERSION)) return VERSION def read_long_description(): with open('README') as f: data = f.read() return data setup( name="python-irclib", description="IRC (Internet Relay Chat) protocol client library for Python", long_description=read_long_description(), version=get_version(), py_modules=["irclib", "ircbot"], author="Joel Rosdahl", author_email="[email protected]", maintainer="Jason R. Coombs", maintainer_email="[email protected]", url="http://python-irclib.sourceforge.net", classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", ], ) @task @needs('generate_setup', 'minilib', 'distutils.command.sdist') def sdist(): "Override sdist to make sure the setup.py gets generated"
Use context manager to read README
Use context manager to read README
Python
mit
jaraco/irc
python
## Code Before: import os import re from paver.easy import * from paver.setuputils import setup def get_version(): """ Grab the version from irclib.py. """ here = os.path.dirname(__file__) irclib = os.path.join(here, 'irclib.py') with open(irclib) as f: content = f.read() VERSION = eval(re.search('VERSION = (.*)', content).group(1)) VERSION = '.'.join(map(str, VERSION)) return VERSION def read_long_description(): f = open('README') try: data = f.read() finally: f.close() return data setup( name="python-irclib", description="IRC (Internet Relay Chat) protocol client library for Python", long_description=read_long_description(), version=get_version(), py_modules=["irclib", "ircbot"], author="Joel Rosdahl", author_email="[email protected]", maintainer="Jason R. Coombs", maintainer_email="[email protected]", url="http://python-irclib.sourceforge.net", classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", ], ) @task @needs('generate_setup', 'minilib', 'distutils.command.sdist') def sdist(): "Override sdist to make sure the setup.py gets generated" ## Instruction: Use context manager to read README ## Code After: import os import re from paver.easy import * from paver.setuputils import setup def get_version(): """ Grab the version from irclib.py. """ here = os.path.dirname(__file__) irclib = os.path.join(here, 'irclib.py') with open(irclib) as f: content = f.read() VERSION = eval(re.search('VERSION = (.*)', content).group(1)) VERSION = '.'.join(map(str, VERSION)) return VERSION def read_long_description(): with open('README') as f: data = f.read() return data setup( name="python-irclib", description="IRC (Internet Relay Chat) protocol client library for Python", long_description=read_long_description(), version=get_version(), py_modules=["irclib", "ircbot"], author="Joel Rosdahl", author_email="[email protected]", maintainer="Jason R. Coombs", maintainer_email="[email protected]", url="http://python-irclib.sourceforge.net", classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", ], ) @task @needs('generate_setup', 'minilib', 'distutils.command.sdist') def sdist(): "Override sdist to make sure the setup.py gets generated"
// ... existing code ... return VERSION def read_long_description(): with open('README') as f: data = f.read() return data setup( // ... rest of the code ...
23d7418aa18f6e4ce1b97938144a8968e2b0cb9b
setup.py
setup.py
"""Setup script for the pyparsing module distribution.""" # Setuptools depends on pyparsing (via packaging) as of version 34, so allow # installing without it to avoid bootstrap problems. try: from setuptools import setup except ImportError: from distutils.core import setup import sys import os from pyparsing import __version__ as pyparsing_version modules = ["pyparsing",] setup(# Distribution meta-data name = "pyparsing", version = pyparsing_version, description = "Python parsing module", author = "Paul McGuire", author_email = "[email protected]", url = "https://github.com/pyparsing/pyparsing/", download_url = "https://pypi.org/project/pyparsing/", license = "MIT License", py_modules = modules, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ] )
"""Setup script for the pyparsing module distribution.""" # Setuptools depends on pyparsing (via packaging) as of version 34, so allow # installing without it to avoid bootstrap problems. try: from setuptools import setup except ImportError: from distutils.core import setup import sys import os from pyparsing import __version__ as pyparsing_version modules = ["pyparsing",] setup(# Distribution meta-data name = "pyparsing", version = pyparsing_version, description = "Python parsing module", author = "Paul McGuire", author_email = "[email protected]", url = "https://github.com/pyparsing/pyparsing/", download_url = "https://pypi.org/project/pyparsing/", license = "MIT License", py_modules = modules, python_requires='>=2.6, !=3.0.*, !=3.1.*, !=3.2.*', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ] )
Add python_requires to help pip
Add python_requires to help pip
Python
mit
pyparsing/pyparsing,pyparsing/pyparsing
python
## Code Before: """Setup script for the pyparsing module distribution.""" # Setuptools depends on pyparsing (via packaging) as of version 34, so allow # installing without it to avoid bootstrap problems. try: from setuptools import setup except ImportError: from distutils.core import setup import sys import os from pyparsing import __version__ as pyparsing_version modules = ["pyparsing",] setup(# Distribution meta-data name = "pyparsing", version = pyparsing_version, description = "Python parsing module", author = "Paul McGuire", author_email = "[email protected]", url = "https://github.com/pyparsing/pyparsing/", download_url = "https://pypi.org/project/pyparsing/", license = "MIT License", py_modules = modules, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ] ) ## Instruction: Add python_requires to help pip ## Code After: """Setup script for the pyparsing module distribution.""" # Setuptools depends on pyparsing (via packaging) as of version 34, so allow # installing without it to avoid bootstrap problems. try: from setuptools import setup except ImportError: from distutils.core import setup import sys import os from pyparsing import __version__ as pyparsing_version modules = ["pyparsing",] setup(# Distribution meta-data name = "pyparsing", version = pyparsing_version, description = "Python parsing module", author = "Paul McGuire", author_email = "[email protected]", url = "https://github.com/pyparsing/pyparsing/", download_url = "https://pypi.org/project/pyparsing/", license = "MIT License", py_modules = modules, python_requires='>=2.6, !=3.0.*, !=3.1.*, !=3.2.*', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Information Technology', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ] )
... download_url = "https://pypi.org/project/pyparsing/", license = "MIT License", py_modules = modules, python_requires='>=2.6, !=3.0.*, !=3.1.*, !=3.2.*', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', ...
212bf2f97a82ebe28431ff3d8f64affaf45fd55e
pyforge/celeryconfig.py
pyforge/celeryconfig.py
CELERY_BACKEND = "mongodb" AMQP_SERVER = "localhost" AMQP_PORT = 5672 AMQP_VHOST = "celeryvhost" AMQP_USER = "celeryuser" AMQP_PASSWORD = "celerypw" CELERYD_LOG_FILE = "celeryd.log" CELERYD_PID_FILE = "celeryd.pid" CELERYD_DAEMON_LOG_LEVEL = "INFO" CELERY_MONGODB_BACKEND_SETTINGS = { "host":"localhost", "port":27017, "database":"celery" } CELERY_AMQP_EXCHANGE = "tasks" CELERY_AMQP_PUBLISHER_ROUTING_KEY = "task.regular" CELERY_AMQP_EXCHANGE_TYPE = "topic" CELERY_AMQP_CONSUMER_QUEUE = "forge_tasks" CELERY_AMQP_CONSUMER_ROUTING_KEY = "forge.#" CELERY_IMPORTS = ("pyforge.tasks.MailTask")
CELERY_BACKEND = "mongodb" # We shouldn't need to supply these because we're using Mongo, # but Celery gives us errors if we don't. DATABASE_ENGINE = "sqlite3" DATABASE_NAME = "celery.db" AMQP_SERVER = "localhost" AMQP_PORT = 5672 AMQP_VHOST = "celeryvhost" AMQP_USER = "celeryuser" AMQP_PASSWORD = "celerypw" CELERYD_LOG_FILE = "celeryd.log" CELERYD_PID_FILE = "celeryd.pid" CELERYD_DAEMON_LOG_LEVEL = "INFO" CELERY_MONGODB_BACKEND_SETTINGS = { "host":"localhost", "port":27017, "database":"celery" } CELERY_AMQP_EXCHANGE = "tasks" CELERY_AMQP_PUBLISHER_ROUTING_KEY = "task.regular" CELERY_AMQP_EXCHANGE_TYPE = "topic" CELERY_AMQP_CONSUMER_QUEUE = "forge_tasks" CELERY_AMQP_CONSUMER_ROUTING_KEY = "forge.#" CELERY_IMPORTS = ("pyforge.tasks.MailTask")
Add unused DATABASE_ENGINE, DATABASE_NAME to pacify celeryinit
Add unused DATABASE_ENGINE, DATABASE_NAME to pacify celeryinit
Python
apache-2.0
Bitergia/allura,apache/incubator-allura,apache/allura,apache/incubator-allura,lym/allura-git,lym/allura-git,apache/incubator-allura,leotrubach/sourceforge-allura,lym/allura-git,heiths/allura,apache/allura,heiths/allura,apache/allura,heiths/allura,Bitergia/allura,apache/incubator-allura,leotrubach/sourceforge-allura,lym/allura-git,Bitergia/allura,Bitergia/allura,heiths/allura,leotrubach/sourceforge-allura,leotrubach/sourceforge-allura,Bitergia/allura,heiths/allura,apache/allura,lym/allura-git,apache/allura
python
## Code Before: CELERY_BACKEND = "mongodb" AMQP_SERVER = "localhost" AMQP_PORT = 5672 AMQP_VHOST = "celeryvhost" AMQP_USER = "celeryuser" AMQP_PASSWORD = "celerypw" CELERYD_LOG_FILE = "celeryd.log" CELERYD_PID_FILE = "celeryd.pid" CELERYD_DAEMON_LOG_LEVEL = "INFO" CELERY_MONGODB_BACKEND_SETTINGS = { "host":"localhost", "port":27017, "database":"celery" } CELERY_AMQP_EXCHANGE = "tasks" CELERY_AMQP_PUBLISHER_ROUTING_KEY = "task.regular" CELERY_AMQP_EXCHANGE_TYPE = "topic" CELERY_AMQP_CONSUMER_QUEUE = "forge_tasks" CELERY_AMQP_CONSUMER_ROUTING_KEY = "forge.#" CELERY_IMPORTS = ("pyforge.tasks.MailTask") ## Instruction: Add unused DATABASE_ENGINE, DATABASE_NAME to pacify celeryinit ## Code After: CELERY_BACKEND = "mongodb" # We shouldn't need to supply these because we're using Mongo, # but Celery gives us errors if we don't. DATABASE_ENGINE = "sqlite3" DATABASE_NAME = "celery.db" AMQP_SERVER = "localhost" AMQP_PORT = 5672 AMQP_VHOST = "celeryvhost" AMQP_USER = "celeryuser" AMQP_PASSWORD = "celerypw" CELERYD_LOG_FILE = "celeryd.log" CELERYD_PID_FILE = "celeryd.pid" CELERYD_DAEMON_LOG_LEVEL = "INFO" CELERY_MONGODB_BACKEND_SETTINGS = { "host":"localhost", "port":27017, "database":"celery" } CELERY_AMQP_EXCHANGE = "tasks" CELERY_AMQP_PUBLISHER_ROUTING_KEY = "task.regular" CELERY_AMQP_EXCHANGE_TYPE = "topic" CELERY_AMQP_CONSUMER_QUEUE = "forge_tasks" CELERY_AMQP_CONSUMER_ROUTING_KEY = "forge.#" CELERY_IMPORTS = ("pyforge.tasks.MailTask")
// ... existing code ... CELERY_BACKEND = "mongodb" # We shouldn't need to supply these because we're using Mongo, # but Celery gives us errors if we don't. DATABASE_ENGINE = "sqlite3" DATABASE_NAME = "celery.db" AMQP_SERVER = "localhost" AMQP_PORT = 5672 // ... rest of the code ...
4bd4499f3d2b9a026e02d0b1106e2a430359c5ad
presto-hive/src/test/java/com/facebook/presto/hive/TestHiveDistributedQueries.java
presto-hive/src/test/java/com/facebook/presto/hive/TestHiveDistributedQueries.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive; import com.facebook.presto.tests.AbstractTestDistributedQueries; import static com.facebook.presto.hive.HiveQueryRunner.createQueryRunner; import static com.facebook.presto.hive.HiveQueryRunner.createSampledSession; import static io.airlift.tpch.TpchTable.getTables; public class TestHiveDistributedQueries extends AbstractTestDistributedQueries { public TestHiveDistributedQueries() throws Exception { super(createQueryRunner(getTables()), createSampledSession()); } @Override public void testDelete() throws Exception { // Hive connector currently does not support delete } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive; import com.facebook.presto.tests.AbstractTestDistributedQueries; import static com.facebook.presto.hive.HiveQueryRunner.createQueryRunner; import static com.facebook.presto.hive.HiveQueryRunner.createSampledSession; import static io.airlift.tpch.TpchTable.getTables; public class TestHiveDistributedQueries extends AbstractTestDistributedQueries { public TestHiveDistributedQueries() throws Exception { super(createQueryRunner(getTables()), createSampledSession()); } @Override public void testDelete() throws Exception { // Hive connector currently does not support row-by-row delete } @Override public void testAddColumn() throws Exception { // Hive connector currently does not support schema change } @Override public void testRenameColumn() throws Exception { // Hive connector currently does not support schema change } @Override public void testRenameTable() throws Exception { // Hive connector currently does not support table rename } }
Disable schema change tests in Hive distributed test
Disable schema change tests in Hive distributed test
Java
apache-2.0
electrum/presto,raghavsethi/presto,cberner/presto,twitter-forks/presto,haitaoyao/presto,treasure-data/presto,zhenyuy-fb/presto,arhimondr/presto,jiangyifangh/presto,stewartpark/presto,chrisunder/presto,haitaoyao/presto,mugglmenzel/presto,propene/presto,nileema/presto,erichwang/presto,haitaoyao/presto,ocono-tech/presto,wagnermarkd/presto,albertocsm/presto,svstanev/presto,smartnews/presto,aramesh117/presto,soz-fb/presto,toyama0919/presto,cosinequanon/presto,prestodb/presto,erichwang/presto,y-lan/presto,ipros-team/presto,sumitkgec/presto,ebyhr/presto,prateek1306/presto,ebyhr/presto,wrmsr/presto,jiangyifangh/presto,prateek1306/presto,ptkool/presto,mode/presto,mugglmenzel/presto,mvp/presto,dain/presto,ocono-tech/presto,losipiuk/presto,11xor6/presto,takari/presto,facebook/presto,zzhao0/presto,toyama0919/presto,EvilMcJerkface/presto,svstanev/presto,nezihyigitbasi/presto,sumitkgec/presto,RobinUS2/presto,dabaitu/presto,RobinUS2/presto,suyucs/presto,elonazoulay/presto,aleph-zero/presto,shixuan-fan/presto,sunchao/presto,prestodb/presto,elonazoulay/presto,wrmsr/presto,losipiuk/presto,hgschmie/presto,electrum/presto,propene/presto,idemura/presto,Yaliang/presto,smartnews/presto,aramesh117/presto,wyukawa/presto,troels/nz-presto,propene/presto,raghavsethi/presto,gh351135612/presto,cawallin/presto,jf367/presto,svstanev/presto,treasure-data/presto,Zoomdata/presto,kietly/presto,smartnews/presto,hulu/presto,dain/presto,zhenyuy-fb/presto,dain/presto,ipros-team/presto,hgschmie/presto,aleph-zero/presto,wagnermarkd/presto,takari/presto,mandusm/presto,kietly/presto,suyucs/presto,y-lan/presto,damiencarol/presto,svstanev/presto,tellproject/presto,raghavsethi/presto,gh351135612/presto,bloomberg/presto,sumitkgec/presto,mpilman/presto,ptkool/presto,Nasdaq/presto,aglne/presto,youngwookim/presto,jf367/presto,treasure-data/presto,11xor6/presto,mbeitchman/presto,ArturGajowy/presto,cawallin/presto,tomz/presto,martint/presto,kietly/presto,zzhao0/presto,youngwookim/presto,hulu/presto,youngwookim/presto,Zoomdata/presto,Nasdaq/presto,ipros-team/presto,harunurhan/presto,toyama0919/presto,takari/presto,TeradataCenterForHadoop/bootcamp,cosinequanon/presto,hulu/presto,kietly/presto,aramesh117/presto,geraint0923/presto,geraint0923/presto,shixuan-fan/presto,Teradata/presto,mpilman/presto,sunchao/presto,geraint0923/presto,Yaliang/presto,idemura/presto,dabaitu/presto,Nasdaq/presto,fiedukow/presto,sopel39/presto,ArturGajowy/presto,gh351135612/presto,shixuan-fan/presto,chrisunder/presto,wyukawa/presto,troels/nz-presto,tellproject/presto,electrum/presto,haozhun/presto,miniway/presto,ipros-team/presto,mbeitchman/presto,stewartpark/presto,RobinUS2/presto,cawallin/presto,Yaliang/presto,soz-fb/presto,geraint0923/presto,arhimondr/presto,arhimondr/presto,mode/presto,aglne/presto,stewartpark/presto,ArturGajowy/presto,aleph-zero/presto,11xor6/presto,totticarter/presto,nileema/presto,nileema/presto,mandusm/presto,tomz/presto,sopel39/presto,lingochamp/presto,mbeitchman/presto,raghavsethi/presto,takari/presto,sunchao/presto,nezihyigitbasi/presto,twitter-forks/presto,totticarter/presto,lingochamp/presto,shixuan-fan/presto,jf367/presto,jiangyifangh/presto,suyucs/presto,mbeitchman/presto,hulu/presto,miniway/presto,Yaliang/presto,treasure-data/presto,aglne/presto,takari/presto,wyukawa/presto,ocono-tech/presto,prateek1306/presto,yuananf/presto,Teradata/presto,jf367/presto,sopel39/presto,ocono-tech/presto,twitter-forks/presto,miniway/presto,totticarter/presto,ipros-team/presto,wrmsr/presto,damiencarol/presto,Teradata/presto,kietly/presto,arhimondr/presto,damiencarol/presto,haitaoyao/presto,totticarter/presto,chrisunder/presto,y-lan/presto,mvp/presto,idemura/presto,erichwang/presto,dabaitu/presto,zhenyuy-fb/presto,mugglmenzel/presto,treasure-data/presto,11xor6/presto,albertocsm/presto,11xor6/presto,yuananf/presto,propene/presto,toyama0919/presto,zzhao0/presto,martint/presto,losipiuk/presto,mugglmenzel/presto,haozhun/presto,svstanev/presto,tellproject/presto,sumitkgec/presto,cosinequanon/presto,harunurhan/presto,idemura/presto,haozhun/presto,lingochamp/presto,ptkool/presto,toyama0919/presto,Jimexist/presto,Zoomdata/presto,fiedukow/presto,wrmsr/presto,dabaitu/presto,mvp/presto,EvilMcJerkface/presto,TeradataCenterForHadoop/bootcamp,smartnews/presto,joy-yao/presto,facebook/presto,jiangyifangh/presto,TeradataCenterForHadoop/bootcamp,geraint0923/presto,tomz/presto,jxiang/presto,TeradataCenterForHadoop/bootcamp,mvp/presto,harunurhan/presto,losipiuk/presto,prestodb/presto,tomz/presto,mandusm/presto,EvilMcJerkface/presto,gh351135612/presto,propene/presto,prestodb/presto,jiangyifangh/presto,tellproject/presto,joy-yao/presto,bloomberg/presto,zhenyuy-fb/presto,Praveen2112/presto,mbeitchman/presto,mode/presto,sunchao/presto,Zoomdata/presto,joy-yao/presto,Jimexist/presto,arhimondr/presto,mvp/presto,ebd2/presto,youngwookim/presto,joy-yao/presto,damiencarol/presto,Praveen2112/presto,miniway/presto,dain/presto,cawallin/presto,sunchao/presto,wyukawa/presto,aramesh117/presto,bloomberg/presto,jf367/presto,RobinUS2/presto,zzhao0/presto,ebyhr/presto,bloomberg/presto,raghavsethi/presto,zzhao0/presto,Praveen2112/presto,martint/presto,sopel39/presto,lingochamp/presto,cberner/presto,jxiang/presto,yuananf/presto,tellproject/presto,mpilman/presto,prateek1306/presto,yuananf/presto,zhenyuy-fb/presto,nileema/presto,ebd2/presto,facebook/presto,joy-yao/presto,losipiuk/presto,y-lan/presto,Nasdaq/presto,ptkool/presto,youngwookim/presto,wagnermarkd/presto,mpilman/presto,harunurhan/presto,mandusm/presto,nezihyigitbasi/presto,cberner/presto,erichwang/presto,mpilman/presto,cberner/presto,jxiang/presto,ebd2/presto,electrum/presto,hgschmie/presto,chrisunder/presto,Praveen2112/presto,ArturGajowy/presto,wagnermarkd/presto,haitaoyao/presto,shixuan-fan/presto,Teradata/presto,martint/presto,troels/nz-presto,suyucs/presto,haozhun/presto,wagnermarkd/presto,martint/presto,mpilman/presto,elonazoulay/presto,prateek1306/presto,Praveen2112/presto,cawallin/presto,elonazoulay/presto,hgschmie/presto,treasure-data/presto,damiencarol/presto,prestodb/presto,ebyhr/presto,idemura/presto,sumitkgec/presto,albertocsm/presto,hulu/presto,elonazoulay/presto,twitter-forks/presto,wrmsr/presto,yuananf/presto,cosinequanon/presto,stewartpark/presto,prestodb/presto,ebd2/presto,totticarter/presto,Teradata/presto,jxiang/presto,facebook/presto,sopel39/presto,nezihyigitbasi/presto,albertocsm/presto,mode/presto,fiedukow/presto,cosinequanon/presto,EvilMcJerkface/presto,chrisunder/presto,harunurhan/presto,suyucs/presto,soz-fb/presto,mode/presto,fiedukow/presto,Nasdaq/presto,jxiang/presto,gh351135612/presto,hgschmie/presto,EvilMcJerkface/presto,aleph-zero/presto,dabaitu/presto,ebyhr/presto,bloomberg/presto,wrmsr/presto,erichwang/presto,ArturGajowy/presto,troels/nz-presto,dain/presto,Jimexist/presto,wyukawa/presto,albertocsm/presto,electrum/presto,cberner/presto,aramesh117/presto,mugglmenzel/presto,TeradataCenterForHadoop/bootcamp,mandusm/presto,smartnews/presto,aleph-zero/presto,Yaliang/presto,miniway/presto,ptkool/presto,nezihyigitbasi/presto,soz-fb/presto,ebd2/presto,y-lan/presto,ocono-tech/presto,aglne/presto,RobinUS2/presto,tomz/presto,twitter-forks/presto,fiedukow/presto,Jimexist/presto,haozhun/presto,facebook/presto,Jimexist/presto,troels/nz-presto,nileema/presto,stewartpark/presto,Zoomdata/presto,lingochamp/presto,soz-fb/presto,tellproject/presto,aglne/presto
java
## Code Before: /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive; import com.facebook.presto.tests.AbstractTestDistributedQueries; import static com.facebook.presto.hive.HiveQueryRunner.createQueryRunner; import static com.facebook.presto.hive.HiveQueryRunner.createSampledSession; import static io.airlift.tpch.TpchTable.getTables; public class TestHiveDistributedQueries extends AbstractTestDistributedQueries { public TestHiveDistributedQueries() throws Exception { super(createQueryRunner(getTables()), createSampledSession()); } @Override public void testDelete() throws Exception { // Hive connector currently does not support delete } } ## Instruction: Disable schema change tests in Hive distributed test ## Code After: /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.hive; import com.facebook.presto.tests.AbstractTestDistributedQueries; import static com.facebook.presto.hive.HiveQueryRunner.createQueryRunner; import static com.facebook.presto.hive.HiveQueryRunner.createSampledSession; import static io.airlift.tpch.TpchTable.getTables; public class TestHiveDistributedQueries extends AbstractTestDistributedQueries { public TestHiveDistributedQueries() throws Exception { super(createQueryRunner(getTables()), createSampledSession()); } @Override public void testDelete() throws Exception { // Hive connector currently does not support row-by-row delete } @Override public void testAddColumn() throws Exception { // Hive connector currently does not support schema change } @Override public void testRenameColumn() throws Exception { // Hive connector currently does not support schema change } @Override public void testRenameTable() throws Exception { // Hive connector currently does not support table rename } }
# ... existing code ... public void testDelete() throws Exception { // Hive connector currently does not support row-by-row delete } @Override public void testAddColumn() throws Exception { // Hive connector currently does not support schema change } @Override public void testRenameColumn() throws Exception { // Hive connector currently does not support schema change } @Override public void testRenameTable() throws Exception { // Hive connector currently does not support table rename } } # ... rest of the code ...
92340a1238636d9160ce120cd9a12ed260007aca
app/__init__.py
app/__init__.py
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config app = Flask(__name__) app.config.from_object(config['development']) bootstrap = Bootstrap(app) db = SQLAlchemy(app) login_manager = LoginManager(app); login_manager.login_view = 'index' from . import views, models
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config app = Flask(__name__) app.config.from_object(config['development']) bootstrap = Bootstrap(app) db = SQLAlchemy(app) login_manager = LoginManager(app); login_manager.login_view = 'index' login_manager.login_message_category = "info" from . import views, models
Add default login manager message category
Add default login manager message category
Python
mit
timzdevz/fm-flask-app
python
## Code Before: from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config app = Flask(__name__) app.config.from_object(config['development']) bootstrap = Bootstrap(app) db = SQLAlchemy(app) login_manager = LoginManager(app); login_manager.login_view = 'index' from . import views, models ## Instruction: Add default login manager message category ## Code After: from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from config import config app = Flask(__name__) app.config.from_object(config['development']) bootstrap = Bootstrap(app) db = SQLAlchemy(app) login_manager = LoginManager(app); login_manager.login_view = 'index' login_manager.login_message_category = "info" from . import views, models
# ... existing code ... db = SQLAlchemy(app) login_manager = LoginManager(app); login_manager.login_view = 'index' login_manager.login_message_category = "info" from . import views, models # ... rest of the code ...
e9b7c19a7080bd9e9a88f0e2eb53a662ee5b154b
tests/python/verify_image.py
tests/python/verify_image.py
import unittest import os from selenium import webdriver from time import sleep class TestClaimsLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.PhantomJS() self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') def test_verify_main_screen_loaded(self): self.driver.get('http://%s/eclaim/login/' % self.ip) self.driver.find_element_by_id('id_user_name').send_keys("implementer") self.driver.find_element_by_id('id_password').send_keys("eclaim_implementer") self.driver.find_element_by_css_selector('button.btn.btn-primary').click() self.driver.implicitly_wait(30) greeting = self.driver.find_element_by_id("user-greeting") self.assertTrue(greeting.is_displayed()) self.assertIn(greeting.text, u'Hello, Implementer') # import ipdb; ipdb.set_trace() self.driver.execute_script("set_language('ms')") sleep(5) self.assertEqual(self.driver.find_element_by_id("logo").text, u'Staff Claims') def tearDown(self): self.driver.get('http://%s/eclaim/logout' % self.ip) self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2)
import unittest import os from selenium import webdriver from time import sleep class TestClaimsLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.PhantomJS() self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') def test_verify_main_screen_loaded(self): self.driver.get('http://%s/eclaim/login/' % self.ip) self.driver.find_element_by_id('id_user_name').send_keys("implementer") self.driver.find_element_by_id('id_password').send_keys("eclaim_implementer") self.driver.find_element_by_css_selector('button.btn.btn-primary').click() self.driver.implicitly_wait(30) greeting = self.driver.find_element_by_id("user-greeting") self.assertTrue(greeting.is_displayed()) self.assertTrue('Hello, Implementer' in greeting.text) # import ipdb; ipdb.set_trace() self.driver.execute_script("set_language('ms')") sleep(5) self.assertEqual(self.driver.find_element_by_id("logo").text, u'Staff Claims') def tearDown(self): self.driver.get('http://%s/eclaim/logout' % self.ip) self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2)
Change self.assertIn to self.assertTrue('Hello Implementer' in greeting.txt)
Change self.assertIn to self.assertTrue('Hello Implementer' in greeting.txt)
Python
mit
censof/ansible-deployment,censof/ansible-deployment,censof/ansible-deployment
python
## Code Before: import unittest import os from selenium import webdriver from time import sleep class TestClaimsLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.PhantomJS() self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') def test_verify_main_screen_loaded(self): self.driver.get('http://%s/eclaim/login/' % self.ip) self.driver.find_element_by_id('id_user_name').send_keys("implementer") self.driver.find_element_by_id('id_password').send_keys("eclaim_implementer") self.driver.find_element_by_css_selector('button.btn.btn-primary').click() self.driver.implicitly_wait(30) greeting = self.driver.find_element_by_id("user-greeting") self.assertTrue(greeting.is_displayed()) self.assertIn(greeting.text, u'Hello, Implementer') # import ipdb; ipdb.set_trace() self.driver.execute_script("set_language('ms')") sleep(5) self.assertEqual(self.driver.find_element_by_id("logo").text, u'Staff Claims') def tearDown(self): self.driver.get('http://%s/eclaim/logout' % self.ip) self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2) ## Instruction: Change self.assertIn to self.assertTrue('Hello Implementer' in greeting.txt) ## Code After: import unittest import os from selenium import webdriver from time import sleep class TestClaimsLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.PhantomJS() self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') def test_verify_main_screen_loaded(self): self.driver.get('http://%s/eclaim/login/' % self.ip) self.driver.find_element_by_id('id_user_name').send_keys("implementer") self.driver.find_element_by_id('id_password').send_keys("eclaim_implementer") self.driver.find_element_by_css_selector('button.btn.btn-primary').click() self.driver.implicitly_wait(30) greeting = self.driver.find_element_by_id("user-greeting") self.assertTrue(greeting.is_displayed()) self.assertTrue('Hello, Implementer' in greeting.text) # import ipdb; ipdb.set_trace() self.driver.execute_script("set_language('ms')") sleep(5) self.assertEqual(self.driver.find_element_by_id("logo").text, u'Staff Claims') def tearDown(self): self.driver.get('http://%s/eclaim/logout' % self.ip) self.driver.quit() if __name__ == '__main__': unittest.main(verbosity=2)
... self.driver.implicitly_wait(30) greeting = self.driver.find_element_by_id("user-greeting") self.assertTrue(greeting.is_displayed()) self.assertTrue('Hello, Implementer' in greeting.text) # import ipdb; ipdb.set_trace() self.driver.execute_script("set_language('ms')") sleep(5) ...
ea180a007c1a5bfaeb56e6b223610876b0619e63
webmaster_verification/views.py
webmaster_verification/views.py
import logging logger = logging.getLogger(__name__) from django.http import Http404 from django.views.generic import TemplateView import settings class VerificationView(TemplateView): """ This simply adds the verification key to the view context and makes sure we return a 404 if the key wasn't set for the provider """ def get_context_data(self, **kwargs): context = super(VerificationView, self).get_context_data(**kwargs) try: context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider] except KeyError: raise Http404 except AttributeError: logger.info("WEBMASTER_VERIFICATION not defined in settings") raise Http404 return context class GoogleVerificationView(VerificationView): template_name = 'webmaster_verification/google_verify_template.html' provider = 'google' class BingVerificationView(VerificationView): template_name = 'webmaster_verification/bing_verify_template.xml' provider = 'bing' class MajesticVerificationView(VerificationView): template_name = 'webmaster_verification/majestic_verify_template.txt' provider = 'majestic'
import logging logger = logging.getLogger(__name__) from django.http import Http404 from django.views.generic import TemplateView import settings class VerificationView(TemplateView): """ This simply adds the verification key to the view context and makes sure we return a 404 if the key wasn't set for the provider """ def get_context_data(self, **kwargs): context = super(VerificationView, self).get_context_data(**kwargs) try: context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider] except KeyError: raise Http404 except AttributeError: logger.info("WEBMASTER_VERIFICATION not defined in settings") raise Http404 return context class VerificationTextView(VerificationView): """ Return proper content type """ def render_to_response(self, context, **kwargs): return super(VerificationTextView, self).render_to_response( context, content_type='text/plain', **kwargs ) class VerificationXMLView(VerificationView): """ Return proper content type """ def render_to_response(self, context, **kwargs): return super(VerificationXMLView, self).render_to_response( context, content_type='text/xml', **kwargs ) class GoogleVerificationView(VerificationView): template_name = 'webmaster_verification/google_verify_template.html' provider = 'google' class BingVerificationView(VerificationXMLView): template_name = 'webmaster_verification/bing_verify_template.xml' provider = 'bing' class MajesticVerificationView(VerificationTextView): template_name = 'webmaster_verification/majestic_verify_template.txt' provider = 'majestic'
Use proper content-type for all files
Use proper content-type for all files
Python
bsd-3-clause
nkuttler/django-webmaster-verification,nkuttler/django-webmaster-verification
python
## Code Before: import logging logger = logging.getLogger(__name__) from django.http import Http404 from django.views.generic import TemplateView import settings class VerificationView(TemplateView): """ This simply adds the verification key to the view context and makes sure we return a 404 if the key wasn't set for the provider """ def get_context_data(self, **kwargs): context = super(VerificationView, self).get_context_data(**kwargs) try: context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider] except KeyError: raise Http404 except AttributeError: logger.info("WEBMASTER_VERIFICATION not defined in settings") raise Http404 return context class GoogleVerificationView(VerificationView): template_name = 'webmaster_verification/google_verify_template.html' provider = 'google' class BingVerificationView(VerificationView): template_name = 'webmaster_verification/bing_verify_template.xml' provider = 'bing' class MajesticVerificationView(VerificationView): template_name = 'webmaster_verification/majestic_verify_template.txt' provider = 'majestic' ## Instruction: Use proper content-type for all files ## Code After: import logging logger = logging.getLogger(__name__) from django.http import Http404 from django.views.generic import TemplateView import settings class VerificationView(TemplateView): """ This simply adds the verification key to the view context and makes sure we return a 404 if the key wasn't set for the provider """ def get_context_data(self, **kwargs): context = super(VerificationView, self).get_context_data(**kwargs) try: context['%s_verification' % self.provider] = settings.WEBMASTER_VERIFICATION[self.provider] except KeyError: raise Http404 except AttributeError: logger.info("WEBMASTER_VERIFICATION not defined in settings") raise Http404 return context class VerificationTextView(VerificationView): """ Return proper content type """ def render_to_response(self, context, **kwargs): return super(VerificationTextView, self).render_to_response( context, content_type='text/plain', **kwargs ) class VerificationXMLView(VerificationView): """ Return proper content type """ def render_to_response(self, context, **kwargs): return super(VerificationXMLView, self).render_to_response( context, content_type='text/xml', **kwargs ) class GoogleVerificationView(VerificationView): template_name = 'webmaster_verification/google_verify_template.html' provider = 'google' class BingVerificationView(VerificationXMLView): template_name = 'webmaster_verification/bing_verify_template.xml' provider = 'bing' class MajesticVerificationView(VerificationTextView): template_name = 'webmaster_verification/majestic_verify_template.txt' provider = 'majestic'
// ... existing code ... return context class VerificationTextView(VerificationView): """ Return proper content type """ def render_to_response(self, context, **kwargs): return super(VerificationTextView, self).render_to_response( context, content_type='text/plain', **kwargs ) class VerificationXMLView(VerificationView): """ Return proper content type """ def render_to_response(self, context, **kwargs): return super(VerificationXMLView, self).render_to_response( context, content_type='text/xml', **kwargs ) class GoogleVerificationView(VerificationView): template_name = 'webmaster_verification/google_verify_template.html' provider = 'google' class BingVerificationView(VerificationXMLView): template_name = 'webmaster_verification/bing_verify_template.xml' provider = 'bing' class MajesticVerificationView(VerificationTextView): template_name = 'webmaster_verification/majestic_verify_template.txt' provider = 'majestic' // ... rest of the code ...
5120bffc257989af56a7f2282bc0a5c505aca833
src/main/java/org/mcphoton/impl/network/PacketSending.java
src/main/java/org/mcphoton/impl/network/PacketSending.java
package org.mcphoton.impl.network; import java.util.Collection; import org.mcphoton.network.Packet; public final class PacketSending { public final Packet packet; public final Collection<PhotonClient> clients; public PacketSending(Packet packet, Collection<PhotonClient> clients) { this.packet = packet; this.clients = clients; } }
package org.mcphoton.impl.network; import java.util.Collection; import java.util.Collections; import org.mcphoton.network.Packet; public final class PacketSending { public final Packet packet; public final Collection<PhotonClient> clients; public PacketSending(Packet packet, PhotonClient client) { this.packet = packet; this.clients = Collections.singletonList(client); } public PacketSending(Packet packet, Collection<PhotonClient> clients) { this.packet = packet; this.clients = clients; } }
Add a constructor for a single PhotonClient
Add a constructor for a single PhotonClient
Java
agpl-3.0
DJmaxZPL4Y/Photon-Server
java
## Code Before: package org.mcphoton.impl.network; import java.util.Collection; import org.mcphoton.network.Packet; public final class PacketSending { public final Packet packet; public final Collection<PhotonClient> clients; public PacketSending(Packet packet, Collection<PhotonClient> clients) { this.packet = packet; this.clients = clients; } } ## Instruction: Add a constructor for a single PhotonClient ## Code After: package org.mcphoton.impl.network; import java.util.Collection; import java.util.Collections; import org.mcphoton.network.Packet; public final class PacketSending { public final Packet packet; public final Collection<PhotonClient> clients; public PacketSending(Packet packet, PhotonClient client) { this.packet = packet; this.clients = Collections.singletonList(client); } public PacketSending(Packet packet, Collection<PhotonClient> clients) { this.packet = packet; this.clients = clients; } }
# ... existing code ... package org.mcphoton.impl.network; import java.util.Collection; import java.util.Collections; import org.mcphoton.network.Packet; public final class PacketSending { public final Packet packet; public final Collection<PhotonClient> clients; public PacketSending(Packet packet, PhotonClient client) { this.packet = packet; this.clients = Collections.singletonList(client); } public PacketSending(Packet packet, Collection<PhotonClient> clients) { this.packet = packet; this.clients = clients; } } # ... rest of the code ...
aa4243e3866f53fa78a122b35319623c51196787
panifex-platform-module-dashboard-impl/src/main/java/org/panifex/platform/module/dashboard/impl/DashboardSidebar.java
panifex-platform-module-dashboard-impl/src/main/java/org/panifex/platform/module/dashboard/impl/DashboardSidebar.java
package org.panifex.platform.module.dashboard.impl; import java.util.ArrayList; import java.util.Collection; import org.apache.aries.blueprint.annotation.Bean; import org.apache.aries.blueprint.annotation.Service; import org.panifex.platform.module.api.sidebar.Sidebar; import org.panifex.platform.module.api.sidebar.DefaultSidebarCommand; import org.panifex.platform.module.api.sidebar.SidebarItem; @Bean(id = DashboardSidebar.ID) @Service(interfaces = Sidebar.class) public class DashboardSidebar implements Sidebar { public final static String ID = "org.panifex.platform.module.dashboard.impl.DashboardSidebar"; private Collection<SidebarItem> sidebarItems = new ArrayList<>(); /** * Initializes Dashboard sidebar items; */ public DashboardSidebar() { // create dashboard sidebar item DefaultSidebarCommand dashboardItem = new DefaultSidebarCommand( "Dashboard", DashboardContent.ID, 0); // add item to list sidebarItems.add(dashboardItem); } @Override public Collection<SidebarItem> getSidebarItems() { return sidebarItems; } }
package org.panifex.platform.module.dashboard.impl; import java.util.ArrayList; import java.util.Collection; import org.apache.aries.blueprint.annotation.Bean; import org.apache.aries.blueprint.annotation.Service; import org.panifex.platform.module.api.sidebar.Sidebar; import org.panifex.platform.module.api.sidebar.DefaultSidebarCommand; import org.panifex.platform.module.api.sidebar.SidebarItem; @Bean(id = DashboardSidebar.ID) @Service(interfaces = Sidebar.class) public class DashboardSidebar implements Sidebar { public final static String ID = "org.panifex.platform.module.dashboard.impl.DashboardSidebar"; private Collection<SidebarItem> sidebarItems = new ArrayList<>(); /** * Initializes Dashboard sidebar items; */ public DashboardSidebar() { // create dashboard sidebar item DefaultSidebarCommand dashboardItem = new DefaultSidebarCommand( "Dashboard", DashboardContent.ID, 0); dashboardItem.setIconSclass("glyphicon glyphicon-home"); // add item to list sidebarItems.add(dashboardItem); } @Override public Collection<SidebarItem> getSidebarItems() { return sidebarItems; } }
Add css style to Dashboard sidebar item
Add css style to Dashboard sidebar item
Java
lgpl-2.1
panifex/panifex-platform,panifex/panifex-platform
java
## Code Before: package org.panifex.platform.module.dashboard.impl; import java.util.ArrayList; import java.util.Collection; import org.apache.aries.blueprint.annotation.Bean; import org.apache.aries.blueprint.annotation.Service; import org.panifex.platform.module.api.sidebar.Sidebar; import org.panifex.platform.module.api.sidebar.DefaultSidebarCommand; import org.panifex.platform.module.api.sidebar.SidebarItem; @Bean(id = DashboardSidebar.ID) @Service(interfaces = Sidebar.class) public class DashboardSidebar implements Sidebar { public final static String ID = "org.panifex.platform.module.dashboard.impl.DashboardSidebar"; private Collection<SidebarItem> sidebarItems = new ArrayList<>(); /** * Initializes Dashboard sidebar items; */ public DashboardSidebar() { // create dashboard sidebar item DefaultSidebarCommand dashboardItem = new DefaultSidebarCommand( "Dashboard", DashboardContent.ID, 0); // add item to list sidebarItems.add(dashboardItem); } @Override public Collection<SidebarItem> getSidebarItems() { return sidebarItems; } } ## Instruction: Add css style to Dashboard sidebar item ## Code After: package org.panifex.platform.module.dashboard.impl; import java.util.ArrayList; import java.util.Collection; import org.apache.aries.blueprint.annotation.Bean; import org.apache.aries.blueprint.annotation.Service; import org.panifex.platform.module.api.sidebar.Sidebar; import org.panifex.platform.module.api.sidebar.DefaultSidebarCommand; import org.panifex.platform.module.api.sidebar.SidebarItem; @Bean(id = DashboardSidebar.ID) @Service(interfaces = Sidebar.class) public class DashboardSidebar implements Sidebar { public final static String ID = "org.panifex.platform.module.dashboard.impl.DashboardSidebar"; private Collection<SidebarItem> sidebarItems = new ArrayList<>(); /** * Initializes Dashboard sidebar items; */ public DashboardSidebar() { // create dashboard sidebar item DefaultSidebarCommand dashboardItem = new DefaultSidebarCommand( "Dashboard", DashboardContent.ID, 0); dashboardItem.setIconSclass("glyphicon glyphicon-home"); // add item to list sidebarItems.add(dashboardItem); } @Override public Collection<SidebarItem> getSidebarItems() { return sidebarItems; } }
... DashboardContent.ID, 0); dashboardItem.setIconSclass("glyphicon glyphicon-home"); // add item to list sidebarItems.add(dashboardItem); } ...
9926270a8a8394e1e48b3a46bf7b115dd7b0e009
archetype-gae/src/main/resources/archetype-resources/src/main/java/model/MyEntity.java
archetype-gae/src/main/resources/archetype-resources/src/main/java/model/MyEntity.java
package ${package}.model; import org.compass.annotations.Searchable; import org.compass.annotations.SearchableId; import org.compass.annotations.SearchableProperty; import org.hibernate.validator.NotNull; import javax.persistence.Entity; import javax.persistence.Id; @Entity @Searchable public class MyEntity { @Id @SearchableId private Long id; @NotNull @SearchableProperty private String myProp; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getMyProp() { return myProp; } public void setMyProp(String myProp) { this.myProp = myProp; } }
package ${package}.model; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class MyEntity { @Id private Long id; private String myProp; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getMyProp() { return myProp; } public void setMyProp(String myProp) { this.myProp = myProp; } }
Remove Compass and Hibernate dependencies
Remove Compass and Hibernate dependencies
Java
apache-2.0
pojosontheweb/woko,pojosontheweb/woko,pojosontheweb/woko,pojosontheweb/woko
java
## Code Before: package ${package}.model; import org.compass.annotations.Searchable; import org.compass.annotations.SearchableId; import org.compass.annotations.SearchableProperty; import org.hibernate.validator.NotNull; import javax.persistence.Entity; import javax.persistence.Id; @Entity @Searchable public class MyEntity { @Id @SearchableId private Long id; @NotNull @SearchableProperty private String myProp; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getMyProp() { return myProp; } public void setMyProp(String myProp) { this.myProp = myProp; } } ## Instruction: Remove Compass and Hibernate dependencies ## Code After: package ${package}.model; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class MyEntity { @Id private Long id; private String myProp; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getMyProp() { return myProp; } public void setMyProp(String myProp) { this.myProp = myProp; } }
// ... existing code ... package ${package}.model; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class MyEntity { @Id private Long id; private String myProp; public Long getId() { // ... rest of the code ...
8b78f3e84c688b0e45ecfa0dda827870eced4c4e
sdi/corestick.py
sdi/corestick.py
def read(filename): """ Reads in a corestick file and returns a dictionary keyed by core_id. Layer interface depths are positive and are relative to the lake bottom. depths are returned in meters. Northing and Easting are typically in the coordinate system used in the rest of the lake survey. We ignore the width fields in the file. """ cores = {} with open(filename) as f: units = f.readline().strip('\r\n').lower() if units not in ['feet', 'meters', 'meter']: raise NotImplementedError('Only units of FEET and METERS/METER are supported ') conv_factor = 1.0 if units == 'feet': conv_factor = 0.3048 f.readline() for line in f.readlines(): fields = line.split() core_id = fields[2] data = {} data['easting'] = float(fields[0]) data['northing'] = float(fields[1]) data['layer_interface_depths'] = [ float(fields[i]) * conv_factor for i in range(5, len(fields), 4) ] data['layer_colors'] = [i for i in range(6, len(fields), 4)] cores[core_id] = data return cores
def read(filename): """ Reads in a corestick file and returns a dictionary keyed by core_id. Layer interface depths are positive and are relative to the lake bottom. depths are returned in meters. Northing and Easting are typically in the coordinate system used in the rest of the lake survey. We ignore the width fields in the file. """ cores = {} with open(filename) as f: units = f.readline().strip('\r\n').lower() if units not in ['feet', 'meters', 'meter']: raise NotImplementedError('Only units of FEET and METERS/METER are supported ') conv_factor = 1.0 if units == 'feet': conv_factor = 0.3048 f.readline() for line in f.readlines(): fields = line.split() core_id = fields[2] data = {} data['easting'] = float(fields[0]) data['northing'] = float(fields[1]) data['layer_interface_depths'] = [ float(fields[i]) * conv_factor for i in range(5, len(fields), 4) ] data['layer_colors'] = [ int(fields[i]) for i in range(6, len(fields), 4)] cores[core_id] = data return cores
Fix reading in for layer_colors.
Fix reading in for layer_colors.
Python
bsd-3-clause
twdb/sdi
python
## Code Before: def read(filename): """ Reads in a corestick file and returns a dictionary keyed by core_id. Layer interface depths are positive and are relative to the lake bottom. depths are returned in meters. Northing and Easting are typically in the coordinate system used in the rest of the lake survey. We ignore the width fields in the file. """ cores = {} with open(filename) as f: units = f.readline().strip('\r\n').lower() if units not in ['feet', 'meters', 'meter']: raise NotImplementedError('Only units of FEET and METERS/METER are supported ') conv_factor = 1.0 if units == 'feet': conv_factor = 0.3048 f.readline() for line in f.readlines(): fields = line.split() core_id = fields[2] data = {} data['easting'] = float(fields[0]) data['northing'] = float(fields[1]) data['layer_interface_depths'] = [ float(fields[i]) * conv_factor for i in range(5, len(fields), 4) ] data['layer_colors'] = [i for i in range(6, len(fields), 4)] cores[core_id] = data return cores ## Instruction: Fix reading in for layer_colors. ## Code After: def read(filename): """ Reads in a corestick file and returns a dictionary keyed by core_id. Layer interface depths are positive and are relative to the lake bottom. depths are returned in meters. Northing and Easting are typically in the coordinate system used in the rest of the lake survey. We ignore the width fields in the file. """ cores = {} with open(filename) as f: units = f.readline().strip('\r\n').lower() if units not in ['feet', 'meters', 'meter']: raise NotImplementedError('Only units of FEET and METERS/METER are supported ') conv_factor = 1.0 if units == 'feet': conv_factor = 0.3048 f.readline() for line in f.readlines(): fields = line.split() core_id = fields[2] data = {} data['easting'] = float(fields[0]) data['northing'] = float(fields[1]) data['layer_interface_depths'] = [ float(fields[i]) * conv_factor for i in range(5, len(fields), 4) ] data['layer_colors'] = [ int(fields[i]) for i in range(6, len(fields), 4)] cores[core_id] = data return cores
... float(fields[i]) * conv_factor for i in range(5, len(fields), 4) ] data['layer_colors'] = [ int(fields[i]) for i in range(6, len(fields), 4)] cores[core_id] = data return cores ...
24cbbd24e6398aa11956ac48282bd907806284c3
genderbot.py
genderbot.py
import re from twitterbot import TwitterBot import wikipedia class Genderbot(TwitterBot): boring_article_regex = (r"municipality|village|town|football|genus|family|" "administrative|district|community|region|hamlet|" "school|actor|mountain|basketball|city|species|film|" "county|located|politician|professional|settlement") def tweet(self): article = self.__random_wikipedia_article() match = re.search(r"\bis [^.?]+", article.content, re.UNICODE) if match: status = self.__format_status(match.group(0), article.url) if self.__is_interesting(status): self.post_tweet(status) def __format_status(self, is_phrase, url): status = 'gender %s' % (is_phrase) if len(status) > 114: status = status[0:113] + '...' return status + ' %s' % (url) def __is_interesting(self, status): boring_match = re.search(Genderbot.boring_article_regex, status, re.UNICODE) return boring_match is None def __random_wikipedia_article(self): random_title = wikipedia.random(pages=1) return wikipedia.page(title=random_title) if __name__ == "__main__": try: Genderbot("CustomGender").tweet() except: pass
import re from twitterbot import TwitterBot import wikipedia class Genderbot(TwitterBot): boring_regex = (r"municipality|village|town|football|genus|family|" "administrative|district|community|region|hamlet|" "school|actor|mountain|basketball|city|species|film|" "county|located|politician|professional|settlement|" "river|lake|province|replaced|origin|band|park|song" "approximately|north|south|east|west|business") def tweet(self): article = self.__random_wikipedia_article() match = re.search(r"\bis [^.?]+", article.content, re.UNICODE) if match: status = self.__format_status(match.group(0), article.url) if self.__is_interesting(status): self.post_tweet(status) def __format_status(self, is_phrase, url): status = 'gender %s' % (is_phrase) if len(status) > 114: status = status[0:113] + '...' return status + ' %s' % (url) def __is_interesting(self, status): flags = re.UNICODE | re.IGNORECASE boring = re.search(Genderbot.boring_regex, status, flags) return boring is None def __random_wikipedia_article(self): random_title = wikipedia.random(pages=1) return wikipedia.page(title=random_title) if __name__ == "__main__": try: Genderbot("CustomGender").tweet() except: pass
Tweak boring regex to exclude more terms
Tweak boring regex to exclude more terms
Python
mit
DanielleSucher/genderbot
python
## Code Before: import re from twitterbot import TwitterBot import wikipedia class Genderbot(TwitterBot): boring_article_regex = (r"municipality|village|town|football|genus|family|" "administrative|district|community|region|hamlet|" "school|actor|mountain|basketball|city|species|film|" "county|located|politician|professional|settlement") def tweet(self): article = self.__random_wikipedia_article() match = re.search(r"\bis [^.?]+", article.content, re.UNICODE) if match: status = self.__format_status(match.group(0), article.url) if self.__is_interesting(status): self.post_tweet(status) def __format_status(self, is_phrase, url): status = 'gender %s' % (is_phrase) if len(status) > 114: status = status[0:113] + '...' return status + ' %s' % (url) def __is_interesting(self, status): boring_match = re.search(Genderbot.boring_article_regex, status, re.UNICODE) return boring_match is None def __random_wikipedia_article(self): random_title = wikipedia.random(pages=1) return wikipedia.page(title=random_title) if __name__ == "__main__": try: Genderbot("CustomGender").tweet() except: pass ## Instruction: Tweak boring regex to exclude more terms ## Code After: import re from twitterbot import TwitterBot import wikipedia class Genderbot(TwitterBot): boring_regex = (r"municipality|village|town|football|genus|family|" "administrative|district|community|region|hamlet|" "school|actor|mountain|basketball|city|species|film|" "county|located|politician|professional|settlement|" "river|lake|province|replaced|origin|band|park|song" "approximately|north|south|east|west|business") def tweet(self): article = self.__random_wikipedia_article() match = re.search(r"\bis [^.?]+", article.content, re.UNICODE) if match: status = self.__format_status(match.group(0), article.url) if self.__is_interesting(status): self.post_tweet(status) def __format_status(self, is_phrase, url): status = 'gender %s' % (is_phrase) if len(status) > 114: status = status[0:113] + '...' return status + ' %s' % (url) def __is_interesting(self, status): flags = re.UNICODE | re.IGNORECASE boring = re.search(Genderbot.boring_regex, status, flags) return boring is None def __random_wikipedia_article(self): random_title = wikipedia.random(pages=1) return wikipedia.page(title=random_title) if __name__ == "__main__": try: Genderbot("CustomGender").tweet() except: pass
// ... existing code ... class Genderbot(TwitterBot): boring_regex = (r"municipality|village|town|football|genus|family|" "administrative|district|community|region|hamlet|" "school|actor|mountain|basketball|city|species|film|" "county|located|politician|professional|settlement|" "river|lake|province|replaced|origin|band|park|song" "approximately|north|south|east|west|business") def tweet(self): article = self.__random_wikipedia_article() // ... modified code ... return status + ' %s' % (url) def __is_interesting(self, status): flags = re.UNICODE | re.IGNORECASE boring = re.search(Genderbot.boring_regex, status, flags) return boring is None def __random_wikipedia_article(self): random_title = wikipedia.random(pages=1) // ... rest of the code ...
65b3a7fa7ae7ee467d3e8ef32b9a00b99b095c3e
humblemedia/processing_spooler.py
humblemedia/processing_spooler.py
import uwsgi import django django.setup() from resources.processing import BaseProcessor from resources.models import Attachment def content_processing(env): print (env) resource_id = int(env.get(b"id")) processor_name = env.get(b"processor").decode() att = Attachment.objects.get(id=resource_id) for cls in BaseProcessor.__subclasses__(): if cls.__name__ == processor_name: instance = cls(att) instance.process() break return uwsgi.SPOOL_OK uwsgi.spooler = content_processing
import uwsgi import django django.setup() from resources.processing import BaseProcessor from resources.models import Attachment def content_processing(env): print (env) resource_id = int(env.get(b"id")) processor_name = env.get(b"processor").decode() try: att = Attachment.objects.get(id=resource_id) except Attachment.DoesNotExist: return uwsgi.SPOOL_OK for cls in BaseProcessor.__subclasses__(): if cls.__name__ == processor_name: instance = cls(att) instance.process() break return uwsgi.SPOOL_OK uwsgi.spooler = content_processing
Return ok if db object does not exist in spooler
Return ok if db object does not exist in spooler
Python
mit
vladimiroff/humble-media,vladimiroff/humble-media
python
## Code Before: import uwsgi import django django.setup() from resources.processing import BaseProcessor from resources.models import Attachment def content_processing(env): print (env) resource_id = int(env.get(b"id")) processor_name = env.get(b"processor").decode() att = Attachment.objects.get(id=resource_id) for cls in BaseProcessor.__subclasses__(): if cls.__name__ == processor_name: instance = cls(att) instance.process() break return uwsgi.SPOOL_OK uwsgi.spooler = content_processing ## Instruction: Return ok if db object does not exist in spooler ## Code After: import uwsgi import django django.setup() from resources.processing import BaseProcessor from resources.models import Attachment def content_processing(env): print (env) resource_id = int(env.get(b"id")) processor_name = env.get(b"processor").decode() try: att = Attachment.objects.get(id=resource_id) except Attachment.DoesNotExist: return uwsgi.SPOOL_OK for cls in BaseProcessor.__subclasses__(): if cls.__name__ == processor_name: instance = cls(att) instance.process() break return uwsgi.SPOOL_OK uwsgi.spooler = content_processing
... print (env) resource_id = int(env.get(b"id")) processor_name = env.get(b"processor").decode() try: att = Attachment.objects.get(id=resource_id) except Attachment.DoesNotExist: return uwsgi.SPOOL_OK for cls in BaseProcessor.__subclasses__(): if cls.__name__ == processor_name: ...
9feb84c39c6988ff31f3d7cb38852a457870111b
bin/readability_to_dr.py
bin/readability_to_dr.py
import hashlib import json import os import sys print(sys.path) from gigacluster import Doc, dr, Tokenizer tok = Tokenizer() for root, dirs, files in os.walk(sys.argv[1]): dirs.sort() files = set(files) cluster_dr = os.path.join(root, 'cluster.dr') with open(cluster_dr, 'wb') as f_dr: writer = dr.Writer(f_dr, Doc) for filename in sorted(f for f in files if f.endswith('.readability')): dr_filename = filename.replace('.readability', '.dr') if not dr_filename in files: path = os.path.join(root, filename) with open(path) as f: try: data = json.load(f) except Exception: pass else: if not ('url' in data and 'title' in data and 'content' in data): continue id = hashlib.md5(data['url'].encode('utf8')).hexdigest() title = data.get('title', '') text = data.get('content', '') doc = Doc(id=id) title = title.encode('utf8') tok.tokenize(title, doc, 0, is_headline=True) tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) print(doc) writer.write(doc)
from collections import defaultdict import hashlib import json import os import sys from gigacluster import Doc, dr, Tokenizer tok = Tokenizer() stats = defaultdict(int) for root, dirs, files in os.walk(sys.argv[1]): dirs.sort() files = set(files) cluster_dr = os.path.join(root, 'cluster.dr') with open(cluster_dr, 'wb') as f_dr: writer = dr.Writer(f_dr, Doc) written = 0 for filename in sorted(f for f in files if f.endswith('.readability')): path = os.path.join(root, filename) with open(path) as f: try: data = json.load(f) except Exception: stats['bad json'] += 1 pass else: if not ('url' in data and 'title' in data and 'content' in data): stats['no url/title/content'] += 1 continue id = hashlib.md5(data['url'].encode('utf8')).hexdigest() title = data.get('title', '') text = data.get('content', '') doc = Doc(id=id) title = title.encode('utf8') tok.tokenize(title, doc, 0, is_headline=True) tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) writer.write(doc) stats['ok'] += 1 written += 1 if not written: print('No docs written for {}'.format(cluster_dr)) os.remove(cluster_dr) print('Stats\t{}'.format(dict(stats)))
Check for empty cluster dr files.
Check for empty cluster dr files.
Python
mit
schwa-lab/gigacluster,schwa-lab/gigacluster
python
## Code Before: import hashlib import json import os import sys print(sys.path) from gigacluster import Doc, dr, Tokenizer tok = Tokenizer() for root, dirs, files in os.walk(sys.argv[1]): dirs.sort() files = set(files) cluster_dr = os.path.join(root, 'cluster.dr') with open(cluster_dr, 'wb') as f_dr: writer = dr.Writer(f_dr, Doc) for filename in sorted(f for f in files if f.endswith('.readability')): dr_filename = filename.replace('.readability', '.dr') if not dr_filename in files: path = os.path.join(root, filename) with open(path) as f: try: data = json.load(f) except Exception: pass else: if not ('url' in data and 'title' in data and 'content' in data): continue id = hashlib.md5(data['url'].encode('utf8')).hexdigest() title = data.get('title', '') text = data.get('content', '') doc = Doc(id=id) title = title.encode('utf8') tok.tokenize(title, doc, 0, is_headline=True) tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) print(doc) writer.write(doc) ## Instruction: Check for empty cluster dr files. ## Code After: from collections import defaultdict import hashlib import json import os import sys from gigacluster import Doc, dr, Tokenizer tok = Tokenizer() stats = defaultdict(int) for root, dirs, files in os.walk(sys.argv[1]): dirs.sort() files = set(files) cluster_dr = os.path.join(root, 'cluster.dr') with open(cluster_dr, 'wb') as f_dr: writer = dr.Writer(f_dr, Doc) written = 0 for filename in sorted(f for f in files if f.endswith('.readability')): path = os.path.join(root, filename) with open(path) as f: try: data = json.load(f) except Exception: stats['bad json'] += 1 pass else: if not ('url' in data and 'title' in data and 'content' in data): stats['no url/title/content'] += 1 continue id = hashlib.md5(data['url'].encode('utf8')).hexdigest() title = data.get('title', '') text = data.get('content', '') doc = Doc(id=id) title = title.encode('utf8') tok.tokenize(title, doc, 0, is_headline=True) tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) writer.write(doc) stats['ok'] += 1 written += 1 if not written: print('No docs written for {}'.format(cluster_dr)) os.remove(cluster_dr) print('Stats\t{}'.format(dict(stats)))
# ... existing code ... from collections import defaultdict import hashlib import json import os import sys from gigacluster import Doc, dr, Tokenizer tok = Tokenizer() stats = defaultdict(int) for root, dirs, files in os.walk(sys.argv[1]): dirs.sort() files = set(files) # ... modified code ... cluster_dr = os.path.join(root, 'cluster.dr') with open(cluster_dr, 'wb') as f_dr: writer = dr.Writer(f_dr, Doc) written = 0 for filename in sorted(f for f in files if f.endswith('.readability')): path = os.path.join(root, filename) with open(path) as f: try: data = json.load(f) except Exception: stats['bad json'] += 1 pass else: if not ('url' in data and 'title' in data and 'content' in data): stats['no url/title/content'] += 1 continue id = hashlib.md5(data['url'].encode('utf8')).hexdigest() title = data.get('title', '') text = data.get('content', '') doc = Doc(id=id) title = title.encode('utf8') tok.tokenize(title, doc, 0, is_headline=True) tok.tokenize(text.encode('utf8'), doc, len(title) + 1, is_headline=False) writer.write(doc) stats['ok'] += 1 written += 1 if not written: print('No docs written for {}'.format(cluster_dr)) os.remove(cluster_dr) print('Stats\t{}'.format(dict(stats))) # ... rest of the code ...
13d83578629d933cc33daf5c869be7e6bd74be86
src/main/java/uk/org/sappho/jira/workflow/approvals/SetSummaryFromParentAction.java
src/main/java/uk/org/sappho/jira/workflow/approvals/SetSummaryFromParentAction.java
package uk.org.sappho.jira.workflow.approvals; import java.util.Map; import com.atlassian.jira.issue.MutableIssue; import com.atlassian.jira.workflow.function.issue.AbstractJiraFunctionProvider; import com.opensymphony.module.propertyset.PropertySet; import com.opensymphony.workflow.WorkflowException; public class SetSummaryFromParentAction extends AbstractJiraFunctionProvider { @SuppressWarnings("unchecked") public void execute(Map transientVars, Map args, PropertySet ps) throws WorkflowException { MutableIssue issue = (MutableIssue) transientVars.get("issue"); String issueType = issue.getIssueTypeObject().getName(); String summary = issue.getSummary().trim(); String parentSummary = issue.getParentObject().getSummary().trim(); if (!summary.equals(parentSummary)) summary = parentSummary + " / " + (summary.length() > 1 ? summary : "additional"); issue.setSummary(issueType + " / " + summary); issue.store(); } }
package uk.org.sappho.jira.workflow.approvals; import java.util.Map; import com.atlassian.jira.issue.MutableIssue; import com.atlassian.jira.workflow.function.issue.AbstractJiraFunctionProvider; import com.opensymphony.module.propertyset.PropertySet; import com.opensymphony.workflow.WorkflowException; public class SetSummaryFromParentAction extends AbstractJiraFunctionProvider { @SuppressWarnings("unchecked") public void execute(Map transientVars, Map args, PropertySet ps) throws WorkflowException { MutableIssue issue = (MutableIssue) transientVars.get("issue"); String issueType = issue.getIssueTypeObject().getName(); String summary = issue.getSummary().trim(); String parentSummary = issue.getParentObject().getSummary().trim(); issue.setSummary(issueType + " / " + parentSummary + (summary.length() > 1 ? summary : "additional")); issue.store(); } }
Add post-function to set summary on approvals subtasks.
SAPPHO-1: Add post-function to set summary on approvals subtasks.
Java
agpl-3.0
sappho/sappho-jira-workflow-approvals
java
## Code Before: package uk.org.sappho.jira.workflow.approvals; import java.util.Map; import com.atlassian.jira.issue.MutableIssue; import com.atlassian.jira.workflow.function.issue.AbstractJiraFunctionProvider; import com.opensymphony.module.propertyset.PropertySet; import com.opensymphony.workflow.WorkflowException; public class SetSummaryFromParentAction extends AbstractJiraFunctionProvider { @SuppressWarnings("unchecked") public void execute(Map transientVars, Map args, PropertySet ps) throws WorkflowException { MutableIssue issue = (MutableIssue) transientVars.get("issue"); String issueType = issue.getIssueTypeObject().getName(); String summary = issue.getSummary().trim(); String parentSummary = issue.getParentObject().getSummary().trim(); if (!summary.equals(parentSummary)) summary = parentSummary + " / " + (summary.length() > 1 ? summary : "additional"); issue.setSummary(issueType + " / " + summary); issue.store(); } } ## Instruction: SAPPHO-1: Add post-function to set summary on approvals subtasks. ## Code After: package uk.org.sappho.jira.workflow.approvals; import java.util.Map; import com.atlassian.jira.issue.MutableIssue; import com.atlassian.jira.workflow.function.issue.AbstractJiraFunctionProvider; import com.opensymphony.module.propertyset.PropertySet; import com.opensymphony.workflow.WorkflowException; public class SetSummaryFromParentAction extends AbstractJiraFunctionProvider { @SuppressWarnings("unchecked") public void execute(Map transientVars, Map args, PropertySet ps) throws WorkflowException { MutableIssue issue = (MutableIssue) transientVars.get("issue"); String issueType = issue.getIssueTypeObject().getName(); String summary = issue.getSummary().trim(); String parentSummary = issue.getParentObject().getSummary().trim(); issue.setSummary(issueType + " / " + parentSummary + (summary.length() > 1 ? summary : "additional")); issue.store(); } }
// ... existing code ... String issueType = issue.getIssueTypeObject().getName(); String summary = issue.getSummary().trim(); String parentSummary = issue.getParentObject().getSummary().trim(); issue.setSummary(issueType + " / " + parentSummary + (summary.length() > 1 ? summary : "additional")); issue.store(); } } // ... rest of the code ...
fbc42057c647e4e42825b0b4e33d69e5967901f0
cid/locals/thread_local.py
cid/locals/thread_local.py
from threading import local from django.conf import settings from .base import build_cid _thread_locals = local() def set_cid(cid): """Set the correlation id for the current request.""" setattr(_thread_locals, 'CID', cid) def get_cid(): """Return the currently set correlation id (if any). If no correlation id has been set and ``CID_GENERATE`` is enabled in the settings, a new correlation id is set and returned. FIXME (dbaty): in version 2, just `return getattr(_thread_locals, 'CID', None)` We want the simplest thing here and let `generate_new_cid` do the job. """ cid = getattr(_thread_locals, 'CID', None) if cid is None and getattr(settings, 'CID_GENERATE', False): cid = build_cid() set_cid(cid) return cid
from threading import local from django.conf import settings from .base import build_cid _thread_locals = local() def set_cid(cid): """Set the correlation id for the current request.""" setattr(_thread_locals, 'CID', cid) def get_cid(): """Return the currently set correlation id (if any). If no correlation id has been set and ``CID_GENERATE`` is enabled in the settings, a new correlation id is set and returned. """ cid = getattr(_thread_locals, 'CID', None) if cid is None and getattr(settings, 'CID_GENERATE', False): cid = build_cid() set_cid(cid) return cid
Remove ancient FIXME in `get_cid()`
Remove ancient FIXME in `get_cid()` Maybe I had a great idea in mind when I wrote the comment. Or maybe it was just a vague thought. I guess we'll never know.
Python
bsd-3-clause
snowball-one/cid
python
## Code Before: from threading import local from django.conf import settings from .base import build_cid _thread_locals = local() def set_cid(cid): """Set the correlation id for the current request.""" setattr(_thread_locals, 'CID', cid) def get_cid(): """Return the currently set correlation id (if any). If no correlation id has been set and ``CID_GENERATE`` is enabled in the settings, a new correlation id is set and returned. FIXME (dbaty): in version 2, just `return getattr(_thread_locals, 'CID', None)` We want the simplest thing here and let `generate_new_cid` do the job. """ cid = getattr(_thread_locals, 'CID', None) if cid is None and getattr(settings, 'CID_GENERATE', False): cid = build_cid() set_cid(cid) return cid ## Instruction: Remove ancient FIXME in `get_cid()` Maybe I had a great idea in mind when I wrote the comment. Or maybe it was just a vague thought. I guess we'll never know. ## Code After: from threading import local from django.conf import settings from .base import build_cid _thread_locals = local() def set_cid(cid): """Set the correlation id for the current request.""" setattr(_thread_locals, 'CID', cid) def get_cid(): """Return the currently set correlation id (if any). If no correlation id has been set and ``CID_GENERATE`` is enabled in the settings, a new correlation id is set and returned. """ cid = getattr(_thread_locals, 'CID', None) if cid is None and getattr(settings, 'CID_GENERATE', False): cid = build_cid() set_cid(cid) return cid
# ... existing code ... If no correlation id has been set and ``CID_GENERATE`` is enabled in the settings, a new correlation id is set and returned. """ cid = getattr(_thread_locals, 'CID', None) if cid is None and getattr(settings, 'CID_GENERATE', False): # ... rest of the code ...
0d1300165b2d33802124917d477047f7b414a69c
plugins/Tools/ScaleTool/ScaleToolHandle.py
plugins/Tools/ScaleTool/ScaleToolHandle.py
from UM.Scene.ToolHandle import ToolHandle class ScaleToolHandle(ToolHandle): def __init__(self, parent = None): super().__init__(parent) md = self.getMeshData() md.addVertex(0, 0, 0) md.addVertex(0, 20, 0) md.addVertex(0, 0, 0) md.addVertex(20, 0, 0) md.addVertex(0, 0, 0) md.addVertex(0, 0, 20)
from UM.Scene.ToolHandle import ToolHandle from UM.Mesh.MeshData import MeshData from UM.Mesh.MeshBuilder import MeshBuilder from UM.Math.Vector import Vector class ScaleToolHandle(ToolHandle): def __init__(self, parent = None): super().__init__(parent) lines = MeshData() lines.addVertex(0, 0, 0) lines.addVertex(0, 20, 0) lines.addVertex(0, 0, 0) lines.addVertex(20, 0, 0) lines.addVertex(0, 0, 0) lines.addVertex(0, 0, 20) lines.setVertexColor(0, ToolHandle.YAxisColor) lines.setVertexColor(1, ToolHandle.YAxisColor) lines.setVertexColor(2, ToolHandle.XAxisColor) lines.setVertexColor(3, ToolHandle.XAxisColor) lines.setVertexColor(4, ToolHandle.ZAxisColor) lines.setVertexColor(5, ToolHandle.ZAxisColor) self.setLineMesh(lines) mb = MeshBuilder() mb.addCube( width = 2, height = 2, depth = 2, center = Vector(0, 0, 0), color = ToolHandle.AllAxisColor ) mb.addCube( width = 2, height = 2, depth = 2, center = Vector(0, 20, 0), color = ToolHandle.YAxisColor ) mb.addCube( width = 2, height = 2, depth = 2, center = Vector(20, 0, 0), color = ToolHandle.XAxisColor ) mb.addCube( width = 2, height = 2, depth = 2, center = Vector(0, 0, 20), color = ToolHandle.ZAxisColor ) self.setSolidMesh(mb.getData())
Implement proper scale tool handles
Implement proper scale tool handles
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
python
## Code Before: from UM.Scene.ToolHandle import ToolHandle class ScaleToolHandle(ToolHandle): def __init__(self, parent = None): super().__init__(parent) md = self.getMeshData() md.addVertex(0, 0, 0) md.addVertex(0, 20, 0) md.addVertex(0, 0, 0) md.addVertex(20, 0, 0) md.addVertex(0, 0, 0) md.addVertex(0, 0, 20) ## Instruction: Implement proper scale tool handles ## Code After: from UM.Scene.ToolHandle import ToolHandle from UM.Mesh.MeshData import MeshData from UM.Mesh.MeshBuilder import MeshBuilder from UM.Math.Vector import Vector class ScaleToolHandle(ToolHandle): def __init__(self, parent = None): super().__init__(parent) lines = MeshData() lines.addVertex(0, 0, 0) lines.addVertex(0, 20, 0) lines.addVertex(0, 0, 0) lines.addVertex(20, 0, 0) lines.addVertex(0, 0, 0) lines.addVertex(0, 0, 20) lines.setVertexColor(0, ToolHandle.YAxisColor) lines.setVertexColor(1, ToolHandle.YAxisColor) lines.setVertexColor(2, ToolHandle.XAxisColor) lines.setVertexColor(3, ToolHandle.XAxisColor) lines.setVertexColor(4, ToolHandle.ZAxisColor) lines.setVertexColor(5, ToolHandle.ZAxisColor) self.setLineMesh(lines) mb = MeshBuilder() mb.addCube( width = 2, height = 2, depth = 2, center = Vector(0, 0, 0), color = ToolHandle.AllAxisColor ) mb.addCube( width = 2, height = 2, depth = 2, center = Vector(0, 20, 0), color = ToolHandle.YAxisColor ) mb.addCube( width = 2, height = 2, depth = 2, center = Vector(20, 0, 0), color = ToolHandle.XAxisColor ) mb.addCube( width = 2, height = 2, depth = 2, center = Vector(0, 0, 20), color = ToolHandle.ZAxisColor ) self.setSolidMesh(mb.getData())
// ... existing code ... from UM.Scene.ToolHandle import ToolHandle from UM.Mesh.MeshData import MeshData from UM.Mesh.MeshBuilder import MeshBuilder from UM.Math.Vector import Vector class ScaleToolHandle(ToolHandle): def __init__(self, parent = None): super().__init__(parent) lines = MeshData() lines.addVertex(0, 0, 0) lines.addVertex(0, 20, 0) lines.addVertex(0, 0, 0) lines.addVertex(20, 0, 0) lines.addVertex(0, 0, 0) lines.addVertex(0, 0, 20) lines.setVertexColor(0, ToolHandle.YAxisColor) lines.setVertexColor(1, ToolHandle.YAxisColor) lines.setVertexColor(2, ToolHandle.XAxisColor) lines.setVertexColor(3, ToolHandle.XAxisColor) lines.setVertexColor(4, ToolHandle.ZAxisColor) lines.setVertexColor(5, ToolHandle.ZAxisColor) self.setLineMesh(lines) mb = MeshBuilder() mb.addCube( width = 2, height = 2, depth = 2, center = Vector(0, 0, 0), color = ToolHandle.AllAxisColor ) mb.addCube( width = 2, height = 2, depth = 2, center = Vector(0, 20, 0), color = ToolHandle.YAxisColor ) mb.addCube( width = 2, height = 2, depth = 2, center = Vector(20, 0, 0), color = ToolHandle.XAxisColor ) mb.addCube( width = 2, height = 2, depth = 2, center = Vector(0, 0, 20), color = ToolHandle.ZAxisColor ) self.setSolidMesh(mb.getData()) // ... rest of the code ...
7ed3a8452de8d75a09d2ee2265d7fa32b4a25c7c
pelicanconf.py
pelicanconf.py
from __future__ import unicode_literals AUTHOR = 'Joao Moreira' SITENAME = 'Joao Moreira' SITEURL = '' BIO = 'lorem ipsum doler umpalum paluuu' PROFILE_IMAGE = "avatar.jpg" PATH = 'content' TIMEZONE = 'America/Chicago' DEFAULT_LANG = 'en' DEFAULT_DATE_FORMAT = '%B %-d, %Y' THEME = "pelican-hyde" DISPLAY_PAGES_ON_MENU = True LOAD_CONTENT_CACHE = False # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None # Social widget SOCIAL = (('github-square', 'https://github.com/jagmoreira'), ('linkedin', 'https://www.linkedin.com/in/joao-moreira'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True YEAR_ARCHIVE_SAVE_AS = 'posts/{date:%Y}/index.html'
from __future__ import unicode_literals AUTHOR = 'Joao Moreira' SITENAME = 'Joao Moreira' SITEURL = '' BIO = 'PhD student. Data scientist. Iron Man fan.' PROFILE_IMAGE = "avatar.jpg" PATH = 'content' STATIC_PATHS = ['images', 'extra/CNAME'] EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},} TIMEZONE = 'America/Chicago' DEFAULT_LANG = 'en' DEFAULT_DATE_FORMAT = '%B %-d, %Y' THEME = "pelican-hyde" DISPLAY_PAGES_ON_MENU = True LOAD_CONTENT_CACHE = False # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None # Social widget SOCIAL = (('github-square', 'https://github.com/jagmoreira'), ('linkedin', 'https://www.linkedin.com/in/joao-moreira'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True YEAR_ARCHIVE_SAVE_AS = 'posts/{date:%Y}/index.html'
Add publication date on github publish
Add publication date on github publish
Python
mit
jagmoreira/jagmoreira.github.io,jagmoreira/jagmoreira.github.io
python
## Code Before: from __future__ import unicode_literals AUTHOR = 'Joao Moreira' SITENAME = 'Joao Moreira' SITEURL = '' BIO = 'lorem ipsum doler umpalum paluuu' PROFILE_IMAGE = "avatar.jpg" PATH = 'content' TIMEZONE = 'America/Chicago' DEFAULT_LANG = 'en' DEFAULT_DATE_FORMAT = '%B %-d, %Y' THEME = "pelican-hyde" DISPLAY_PAGES_ON_MENU = True LOAD_CONTENT_CACHE = False # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None # Social widget SOCIAL = (('github-square', 'https://github.com/jagmoreira'), ('linkedin', 'https://www.linkedin.com/in/joao-moreira'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True YEAR_ARCHIVE_SAVE_AS = 'posts/{date:%Y}/index.html' ## Instruction: Add publication date on github publish ## Code After: from __future__ import unicode_literals AUTHOR = 'Joao Moreira' SITENAME = 'Joao Moreira' SITEURL = '' BIO = 'PhD student. Data scientist. Iron Man fan.' PROFILE_IMAGE = "avatar.jpg" PATH = 'content' STATIC_PATHS = ['images', 'extra/CNAME'] EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},} TIMEZONE = 'America/Chicago' DEFAULT_LANG = 'en' DEFAULT_DATE_FORMAT = '%B %-d, %Y' THEME = "pelican-hyde" DISPLAY_PAGES_ON_MENU = True LOAD_CONTENT_CACHE = False # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None # Social widget SOCIAL = (('github-square', 'https://github.com/jagmoreira'), ('linkedin', 'https://www.linkedin.com/in/joao-moreira'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True YEAR_ARCHIVE_SAVE_AS = 'posts/{date:%Y}/index.html'
... AUTHOR = 'Joao Moreira' SITENAME = 'Joao Moreira' SITEURL = '' BIO = 'PhD student. Data scientist. Iron Man fan.' PROFILE_IMAGE = "avatar.jpg" PATH = 'content' STATIC_PATHS = ['images', 'extra/CNAME'] EXTRA_PATH_METADATA = {'extra/CNAME': {'path': 'CNAME'},} TIMEZONE = 'America/Chicago' ...
395a09a57b1bf98b554126be3119ea52228624ae
jslack-api-client/src/main/java/com/github/seratch/jslack/api/methods/response/oauth/OAuthAccessResponse.java
jslack-api-client/src/main/java/com/github/seratch/jslack/api/methods/response/oauth/OAuthAccessResponse.java
package com.github.seratch.jslack.api.methods.response.oauth; import com.github.seratch.jslack.api.methods.SlackApiResponse; import lombok.Data; import java.util.List; @Data public class OAuthAccessResponse implements SlackApiResponse { private boolean ok; private String warning; private String error; private String needed; private String provided; private String tokenType; private String accessToken; private String scope; private String enterpriseId; private String teamName; private String teamId; private String userId; private IncomingWebhook incomingWebhook; private Bot bot; private AuthorizingUser authorizingUser; private InstallerUser installerUser; @Deprecated // for workspace apps private Scopes scopes; @Data public static class IncomingWebhook { private String url; private String channel; private String channelId; private String configurationUrl; } @Data public static class Bot { private String botUserId; private String botAccessToken; } @Data public static class AuthorizingUser { private String userId; private String appHome; } @Data public static class InstallerUser { private String userId; private String appHome; } @Data public static class Scopes { private List<String> appHome; private List<String> team; private List<String> channel; private List<String> group; private List<String> mpim; private List<String> im; private List<String> user; } }
package com.github.seratch.jslack.api.methods.response.oauth; import com.github.seratch.jslack.api.methods.SlackApiResponse; import lombok.Data; import java.util.List; @Data public class OAuthAccessResponse implements SlackApiResponse { private boolean ok; private String warning; private String error; private String needed; private String provided; private String tokenType; private String accessToken; private String scope; private String enterpriseId; private String teamName; private String teamId; private String userId; private IncomingWebhook incomingWebhook; private Bot bot; @Data public static class IncomingWebhook { private String url; private String channel; private String channelId; private String configurationUrl; } @Data public static class Bot { private String botUserId; private String botAccessToken; } @Deprecated // for workspace apps private AuthorizingUser authorizingUser; @Deprecated // for workspace apps private InstallerUser installerUser; @Deprecated // for workspace apps private Scopes scopes; @Deprecated @Data public static class AuthorizingUser { private String userId; private String appHome; } @Deprecated @Data public static class InstallerUser { private String userId; private String appHome; } @Deprecated @Data public static class Scopes { private List<String> appHome; private List<String> team; private List<String> channel; private List<String> group; private List<String> mpim; private List<String> im; private List<String> user; } }
Mark workspace app related properties as deprecated
Mark workspace app related properties as deprecated
Java
mit
seratch/jslack,seratch/jslack,seratch/jslack,seratch/jslack
java
## Code Before: package com.github.seratch.jslack.api.methods.response.oauth; import com.github.seratch.jslack.api.methods.SlackApiResponse; import lombok.Data; import java.util.List; @Data public class OAuthAccessResponse implements SlackApiResponse { private boolean ok; private String warning; private String error; private String needed; private String provided; private String tokenType; private String accessToken; private String scope; private String enterpriseId; private String teamName; private String teamId; private String userId; private IncomingWebhook incomingWebhook; private Bot bot; private AuthorizingUser authorizingUser; private InstallerUser installerUser; @Deprecated // for workspace apps private Scopes scopes; @Data public static class IncomingWebhook { private String url; private String channel; private String channelId; private String configurationUrl; } @Data public static class Bot { private String botUserId; private String botAccessToken; } @Data public static class AuthorizingUser { private String userId; private String appHome; } @Data public static class InstallerUser { private String userId; private String appHome; } @Data public static class Scopes { private List<String> appHome; private List<String> team; private List<String> channel; private List<String> group; private List<String> mpim; private List<String> im; private List<String> user; } } ## Instruction: Mark workspace app related properties as deprecated ## Code After: package com.github.seratch.jslack.api.methods.response.oauth; import com.github.seratch.jslack.api.methods.SlackApiResponse; import lombok.Data; import java.util.List; @Data public class OAuthAccessResponse implements SlackApiResponse { private boolean ok; private String warning; private String error; private String needed; private String provided; private String tokenType; private String accessToken; private String scope; private String enterpriseId; private String teamName; private String teamId; private String userId; private IncomingWebhook incomingWebhook; private Bot bot; @Data public static class IncomingWebhook { private String url; private String channel; private String channelId; private String configurationUrl; } @Data public static class Bot { private String botUserId; private String botAccessToken; } @Deprecated // for workspace apps private AuthorizingUser authorizingUser; @Deprecated // for workspace apps private InstallerUser installerUser; @Deprecated // for workspace apps private Scopes scopes; @Deprecated @Data public static class AuthorizingUser { private String userId; private String appHome; } @Deprecated @Data public static class InstallerUser { private String userId; private String appHome; } @Deprecated @Data public static class Scopes { private List<String> appHome; private List<String> team; private List<String> channel; private List<String> group; private List<String> mpim; private List<String> im; private List<String> user; } }
// ... existing code ... private IncomingWebhook incomingWebhook; private Bot bot; @Data public static class IncomingWebhook { private String url; // ... modified code ... private String botAccessToken; } @Deprecated // for workspace apps private AuthorizingUser authorizingUser; @Deprecated // for workspace apps private InstallerUser installerUser; @Deprecated // for workspace apps private Scopes scopes; @Deprecated @Data public static class AuthorizingUser { private String userId; ... private String appHome; } @Deprecated @Data public static class InstallerUser { private String userId; ... private String appHome; } @Deprecated @Data public static class Scopes { private List<String> appHome; // ... rest of the code ...
82b3f8023289175cf756187ab35318066715f430
src/modules/conf_theme/e_int_config_theme.h
src/modules/conf_theme/e_int_config_theme.h
/* * vim:ts=8:sw=3:sts=8:noexpandtab:cino=>5n-3f0^-2{2 */ #ifdef E_TYPEDEFS #else #ifndef E_INT_CONFIG_THEME_H #define E_INT_CONFIG_THEME_H EAPI E_Config_Dialog *e_int_config_theme(E_Container *con, const char *params __UNUSED__); EAPI void e_int_config_theme_import_done(E_Config_Dialog *dia); EAPI void e_int_config_theme_update(E_Config_Dialog *dia, char *file); #endif #endif
/* * vim:ts=8:sw=3:sts=8:noexpandtab:cino=>5n-3f0^-2{2 */ #ifdef E_TYPEDEFS #else #ifndef E_INT_CONFIG_THEME_H #define E_INT_CONFIG_THEME_H EAPI E_Config_Dialog *e_int_config_theme(E_Container *con, const char *params __UNUSED__); EAPI void e_int_config_theme_import_done(E_Config_Dialog *dia); EAPI void e_int_config_theme_update(E_Config_Dialog *dia, char *file); EAPI void e_int_config_theme_web_done(E_Config_Dialog *dia); #endif #endif
Declare public function in header.
Declare public function in header. git-svn-id: 0f3f1c46c6da7ffd142db61e503a7ff63af3a195@35475 7cbeb6ba-43b4-40fd-8cce-4c39aea84d33
C
bsd-2-clause
jordemort/e17,jordemort/e17,jordemort/e17
c
## Code Before: /* * vim:ts=8:sw=3:sts=8:noexpandtab:cino=>5n-3f0^-2{2 */ #ifdef E_TYPEDEFS #else #ifndef E_INT_CONFIG_THEME_H #define E_INT_CONFIG_THEME_H EAPI E_Config_Dialog *e_int_config_theme(E_Container *con, const char *params __UNUSED__); EAPI void e_int_config_theme_import_done(E_Config_Dialog *dia); EAPI void e_int_config_theme_update(E_Config_Dialog *dia, char *file); #endif #endif ## Instruction: Declare public function in header. git-svn-id: 0f3f1c46c6da7ffd142db61e503a7ff63af3a195@35475 7cbeb6ba-43b4-40fd-8cce-4c39aea84d33 ## Code After: /* * vim:ts=8:sw=3:sts=8:noexpandtab:cino=>5n-3f0^-2{2 */ #ifdef E_TYPEDEFS #else #ifndef E_INT_CONFIG_THEME_H #define E_INT_CONFIG_THEME_H EAPI E_Config_Dialog *e_int_config_theme(E_Container *con, const char *params __UNUSED__); EAPI void e_int_config_theme_import_done(E_Config_Dialog *dia); EAPI void e_int_config_theme_update(E_Config_Dialog *dia, char *file); EAPI void e_int_config_theme_web_done(E_Config_Dialog *dia); #endif #endif
... EAPI void e_int_config_theme_import_done(E_Config_Dialog *dia); EAPI void e_int_config_theme_update(E_Config_Dialog *dia, char *file); EAPI void e_int_config_theme_web_done(E_Config_Dialog *dia); #endif #endif ...
c9abba3a9ca6ccf1a9bed5fad5cda12557b3266c
tests/chainer_tests/training_tests/extensions_tests/test_plot_report.py
tests/chainer_tests/training_tests/extensions_tests/test_plot_report.py
import unittest import warnings from chainer import testing from chainer.training import extensions class TestPlotReport(unittest.TestCase): def test_available(self): try: import matplotlib # NOQA available = True except ImportError: available = False with warnings.catch_warnings(record=True) as w: self.assertEqual(extensions.PlotReport.available(), available) # It shows warning only when matplotlib.pyplot is not available if available: self.assertEqual(len(w), 0) else: self.assertEqual(len(w), 1) @unittest.skipUnless( extensions.PlotReport.available(), 'matplotlib is not installed') def test_lazy_import(self): # To support python2, we do not use self.assertWarns() with warnings.catch_warnings(record=True) as w: import matplotlib matplotlib.use('Agg') self.assertEqual(len(w), 0) testing.run_module(__name__, __file__)
import unittest import warnings from chainer import testing from chainer.training import extensions class TestPlotReport(unittest.TestCase): def test_available(self): try: import matplotlib # NOQA available = True except ImportError: available = False with warnings.catch_warnings(record=True) as w: self.assertEqual(extensions.PlotReport.available(), available) # It shows warning only when matplotlib is not available if available: self.assertEqual(len(w), 0) else: self.assertEqual(len(w), 1) # In Python 2 the above test does not raise UserWarning, # so we use plot_report._available instead of PlotReport.available() @unittest.skipUnless( extensions.plot_report._available, 'matplotlib is not installed') def test_lazy_import(self): # To support python2, we do not use self.assertWarns() with warnings.catch_warnings(record=True) as w: import matplotlib matplotlib.use('Agg') self.assertEqual(len(w), 0) testing.run_module(__name__, __file__)
Use plot_report._available instead of available()
Use plot_report._available instead of available()
Python
mit
hvy/chainer,jnishi/chainer,niboshi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,hvy/chainer,chainer/chainer,jnishi/chainer,niboshi/chainer,okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,hvy/chainer,okuta/chainer,okuta/chainer,chainer/chainer,hvy/chainer,ktnyt/chainer,ktnyt/chainer,wkentaro/chainer,jnishi/chainer,keisuke-umezawa/chainer,tkerola/chainer,wkentaro/chainer,ktnyt/chainer,ronekko/chainer,keisuke-umezawa/chainer,ktnyt/chainer,aonotas/chainer,rezoo/chainer,kashif/chainer,anaruse/chainer,jnishi/chainer,chainer/chainer,okuta/chainer,niboshi/chainer,niboshi/chainer,pfnet/chainer,chainer/chainer
python
## Code Before: import unittest import warnings from chainer import testing from chainer.training import extensions class TestPlotReport(unittest.TestCase): def test_available(self): try: import matplotlib # NOQA available = True except ImportError: available = False with warnings.catch_warnings(record=True) as w: self.assertEqual(extensions.PlotReport.available(), available) # It shows warning only when matplotlib.pyplot is not available if available: self.assertEqual(len(w), 0) else: self.assertEqual(len(w), 1) @unittest.skipUnless( extensions.PlotReport.available(), 'matplotlib is not installed') def test_lazy_import(self): # To support python2, we do not use self.assertWarns() with warnings.catch_warnings(record=True) as w: import matplotlib matplotlib.use('Agg') self.assertEqual(len(w), 0) testing.run_module(__name__, __file__) ## Instruction: Use plot_report._available instead of available() ## Code After: import unittest import warnings from chainer import testing from chainer.training import extensions class TestPlotReport(unittest.TestCase): def test_available(self): try: import matplotlib # NOQA available = True except ImportError: available = False with warnings.catch_warnings(record=True) as w: self.assertEqual(extensions.PlotReport.available(), available) # It shows warning only when matplotlib is not available if available: self.assertEqual(len(w), 0) else: self.assertEqual(len(w), 1) # In Python 2 the above test does not raise UserWarning, # so we use plot_report._available instead of PlotReport.available() @unittest.skipUnless( extensions.plot_report._available, 'matplotlib is not installed') def test_lazy_import(self): # To support python2, we do not use self.assertWarns() with warnings.catch_warnings(record=True) as w: import matplotlib matplotlib.use('Agg') self.assertEqual(len(w), 0) testing.run_module(__name__, __file__)
// ... existing code ... with warnings.catch_warnings(record=True) as w: self.assertEqual(extensions.PlotReport.available(), available) # It shows warning only when matplotlib is not available if available: self.assertEqual(len(w), 0) else: self.assertEqual(len(w), 1) # In Python 2 the above test does not raise UserWarning, # so we use plot_report._available instead of PlotReport.available() @unittest.skipUnless( extensions.plot_report._available, 'matplotlib is not installed') def test_lazy_import(self): # To support python2, we do not use self.assertWarns() with warnings.catch_warnings(record=True) as w: // ... rest of the code ...
30ea5b30746f12feb7b5915bce180ff4934ae204
problem67.py
problem67.py
import math def blad(): ins = open( "triangles_18.txt", "r" ) arr = [] idx = 0 for line in ins: try: l = [int(x) for x in line.split()] if ( l[idx] < l[idx+1] ): idx += 1 except IndexError: pass arr.append(l[idx]) ins.close() print arr print sum(arr) #6580 # 3 # 7 4 # 2 4 6 # 8 5 9 3 def all(n): arr = [] for s in format(n, '100b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] #print idx try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**99 for i in xrange(n): print i, n sums.append(all(i)) print max(sums)
def generic(): data = [] ins = open( "triangles.txt", "r" ) for i,line in enumerate(ins): data.insert(0, [int(x) for x in line.split()] ) ins.close() for n,d in enumerate(data): if n == 0: pass else: data[n] = [ max(i+data[n-1][nn], i+data[n-1][nn+1]) for nn,i in enumerate(d) ] return data[n][0] def perm(n): arr = [] for s in format(n, '015b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**14 for i in xrange(n): sums.append(perm(i)) print "Problem 18:" ,max(sums) print "Problem 67:", generic()
Add proper solution for projects 18 and 67
Add proper solution for projects 18 and 67
Python
mit
jakubczaplicki/projecteuler,jakubczaplicki/projecteuler
python
## Code Before: import math def blad(): ins = open( "triangles_18.txt", "r" ) arr = [] idx = 0 for line in ins: try: l = [int(x) for x in line.split()] if ( l[idx] < l[idx+1] ): idx += 1 except IndexError: pass arr.append(l[idx]) ins.close() print arr print sum(arr) #6580 # 3 # 7 4 # 2 4 6 # 8 5 9 3 def all(n): arr = [] for s in format(n, '100b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] #print idx try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**99 for i in xrange(n): print i, n sums.append(all(i)) print max(sums) ## Instruction: Add proper solution for projects 18 and 67 ## Code After: def generic(): data = [] ins = open( "triangles.txt", "r" ) for i,line in enumerate(ins): data.insert(0, [int(x) for x in line.split()] ) ins.close() for n,d in enumerate(data): if n == 0: pass else: data[n] = [ max(i+data[n-1][nn], i+data[n-1][nn+1]) for nn,i in enumerate(d) ] return data[n][0] def perm(n): arr = [] for s in format(n, '015b'): arr.append(int(s)) #print arr idx = 0 items = [] sum = 0 ins = open( "triangles_18.txt", "r" ) for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] try: sum += l[idx] except IndexError: print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**14 for i in xrange(n): sums.append(perm(i)) print "Problem 18:" ,max(sums) print "Problem 67:", generic()
# ... existing code ... def generic(): data = [] ins = open( "triangles.txt", "r" ) for i,line in enumerate(ins): data.insert(0, [int(x) for x in line.split()] ) ins.close() for n,d in enumerate(data): if n == 0: pass else: data[n] = [ max(i+data[n-1][nn], i+data[n-1][nn+1]) for nn,i in enumerate(d) ] return data[n][0] def perm(n): arr = [] for s in format(n, '015b'): arr.append(int(s)) #print arr idx = 0 # ... modified code ... for i,line in enumerate(ins): l = [int(x) for x in line.split()] idx += arr[i] try: sum += l[idx] except IndexError: ... print "Out of range: ", idx, "arr:", l ins.close() return sum sums = [] n = 2**14 for i in xrange(n): sums.append(perm(i)) print "Problem 18:" ,max(sums) print "Problem 67:", generic() # ... rest of the code ...
7a0ed88e1775429ce283cc315cc05ea3dbde229f
tests/response_construction_tests.py
tests/response_construction_tests.py
from django.test.client import RequestFactory from mock import Mock from unittest2 import TestCase from .helpers import RequestPatchMixin from .test_views import TestProxy class ResponseConstructionTest(TestCase, RequestPatchMixin): def setUp(self): self.proxy = TestProxy.as_view() self.browser_request = RequestFactory().get('/') self.proxy_stub = Mock( content='upstream content', headers={ 'Fake-Header': '123', 'Transfer-Encoding': 'foo' }, status_code=201) self.patch_request(self.proxy_stub) self.response = self.proxy(self.browser_request) class HttpProxyContentPassThrough(ResponseConstructionTest): def test_creates_response_object_with_proxied_content(self): self.assertEqual( self.response.content.decode('utf-8'), 'upstream content') def test_creates_response_object_with_proxied_status(self): self.assertEqual(self.response.status_code, 201) class HttpProxyHeaderPassThrough(ResponseConstructionTest): def test_sets_upstream_headers_on_response_object(self): self.assertEqual(self.response['Fake-Header'], '123') def test_doesnt_set_ignored_upstream_headers_on_response_obj(self): self.assertFalse(self.response.has_header('Transfer-Encoding'))
from django.test.client import RequestFactory from mock import Mock from unittest2 import TestCase from .helpers import RequestPatchMixin from .test_views import TestProxy class ResponseConstructionTest(TestCase, RequestPatchMixin): def get_request(self): return RequestFactory().get('/') def setUp(self): self.proxy = TestProxy.as_view() self.browser_request = self.get_request() self.proxy_stub = Mock( content='upstream content', headers={ 'Fake-Header': '123', 'Transfer-Encoding': 'foo' }, status_code=201) self.patch_request(self.proxy_stub) self.response = self.proxy(self.browser_request) class HttpProxyContentPassThrough(ResponseConstructionTest): def test_creates_response_object_with_proxied_content(self): self.assertEqual( self.response.content.decode('utf-8'), 'upstream content') def test_creates_response_object_with_proxied_status(self): self.assertEqual(self.response.status_code, 201) class HttpProxyHeaderPassThrough(ResponseConstructionTest): def test_sets_upstream_headers_on_response_object(self): self.assertEqual(self.response['Fake-Header'], '123') def test_doesnt_set_ignored_upstream_headers_on_response_obj(self): self.assertFalse(self.response.has_header('Transfer-Encoding')) class HttpProxyEmptyContentLengthHandling(ResponseConstructionTest): def get_request(self): request = RequestFactory().get('/') request.META['CONTENT_LENGTH'] = '' return request def test_succeeds(self): self.assertEqual(self.response.status_code, 201)
Add test coverage for 1.10 CONTENT_LENGTH hack
Add test coverage for 1.10 CONTENT_LENGTH hack
Python
mit
thomasw/djproxy
python
## Code Before: from django.test.client import RequestFactory from mock import Mock from unittest2 import TestCase from .helpers import RequestPatchMixin from .test_views import TestProxy class ResponseConstructionTest(TestCase, RequestPatchMixin): def setUp(self): self.proxy = TestProxy.as_view() self.browser_request = RequestFactory().get('/') self.proxy_stub = Mock( content='upstream content', headers={ 'Fake-Header': '123', 'Transfer-Encoding': 'foo' }, status_code=201) self.patch_request(self.proxy_stub) self.response = self.proxy(self.browser_request) class HttpProxyContentPassThrough(ResponseConstructionTest): def test_creates_response_object_with_proxied_content(self): self.assertEqual( self.response.content.decode('utf-8'), 'upstream content') def test_creates_response_object_with_proxied_status(self): self.assertEqual(self.response.status_code, 201) class HttpProxyHeaderPassThrough(ResponseConstructionTest): def test_sets_upstream_headers_on_response_object(self): self.assertEqual(self.response['Fake-Header'], '123') def test_doesnt_set_ignored_upstream_headers_on_response_obj(self): self.assertFalse(self.response.has_header('Transfer-Encoding')) ## Instruction: Add test coverage for 1.10 CONTENT_LENGTH hack ## Code After: from django.test.client import RequestFactory from mock import Mock from unittest2 import TestCase from .helpers import RequestPatchMixin from .test_views import TestProxy class ResponseConstructionTest(TestCase, RequestPatchMixin): def get_request(self): return RequestFactory().get('/') def setUp(self): self.proxy = TestProxy.as_view() self.browser_request = self.get_request() self.proxy_stub = Mock( content='upstream content', headers={ 'Fake-Header': '123', 'Transfer-Encoding': 'foo' }, status_code=201) self.patch_request(self.proxy_stub) self.response = self.proxy(self.browser_request) class HttpProxyContentPassThrough(ResponseConstructionTest): def test_creates_response_object_with_proxied_content(self): self.assertEqual( self.response.content.decode('utf-8'), 'upstream content') def test_creates_response_object_with_proxied_status(self): self.assertEqual(self.response.status_code, 201) class HttpProxyHeaderPassThrough(ResponseConstructionTest): def test_sets_upstream_headers_on_response_object(self): self.assertEqual(self.response['Fake-Header'], '123') def test_doesnt_set_ignored_upstream_headers_on_response_obj(self): self.assertFalse(self.response.has_header('Transfer-Encoding')) class HttpProxyEmptyContentLengthHandling(ResponseConstructionTest): def get_request(self): request = RequestFactory().get('/') request.META['CONTENT_LENGTH'] = '' return request def test_succeeds(self): self.assertEqual(self.response.status_code, 201)
# ... existing code ... class ResponseConstructionTest(TestCase, RequestPatchMixin): def get_request(self): return RequestFactory().get('/') def setUp(self): self.proxy = TestProxy.as_view() self.browser_request = self.get_request() self.proxy_stub = Mock( content='upstream content', headers={ # ... modified code ... def test_doesnt_set_ignored_upstream_headers_on_response_obj(self): self.assertFalse(self.response.has_header('Transfer-Encoding')) class HttpProxyEmptyContentLengthHandling(ResponseConstructionTest): def get_request(self): request = RequestFactory().get('/') request.META['CONTENT_LENGTH'] = '' return request def test_succeeds(self): self.assertEqual(self.response.status_code, 201) # ... rest of the code ...
601fb4918265ace2b6d9cc3c820b94093360c81e
src/main/java/com/uwetrottmann/trakt/v2/entities/Username.java
src/main/java/com/uwetrottmann/trakt/v2/entities/Username.java
package com.uwetrottmann.trakt.v2.entities; public class Username { /** * Special user name for the current user (determined by auth data). */ public static final Username ME = new Username("me"); private String encodedUsername; /** * Encodes the username returned from trakt so it is API compatible (currently replaces "." with "-"). * * @param username A username as returned by the trakt API. * @see #ME */ public Username(String username) { if (username == null || username.length() == 0) { throw new IllegalArgumentException("trakt username can not be empty."); } this.encodedUsername = username.replace(".", "-"); } @Override public String toString() { return encodedUsername; } }
package com.uwetrottmann.trakt.v2.entities; public class Username { /** * Special user name for the current user (determined by auth data). */ public static final Username ME = new Username("me"); private String encodedUsername; /** * Encodes the username returned from trakt so it is API compatible (currently replaces "." with "-"). * * @param username A username as returned by the trakt API. * @see #ME */ public Username(String username) { if (username == null || username.length() == 0) { throw new IllegalArgumentException("trakt username can not be empty."); } // trakt encodes some special chars in usernames // - points "." as a dash "-" // - spaces " " as a dash "-" // - multiple dashes are reduced to one this.encodedUsername = username.replace(".", "-").replace(" ", "-").replaceAll("(-)+", "-"); } @Override public String toString() { return encodedUsername; } }
Remove spaces in user names.
Remove spaces in user names. - Also ensure multiple consecutive dashes are replaced by just one.
Java
apache-2.0
UweTrottmann/trakt-java
java
## Code Before: package com.uwetrottmann.trakt.v2.entities; public class Username { /** * Special user name for the current user (determined by auth data). */ public static final Username ME = new Username("me"); private String encodedUsername; /** * Encodes the username returned from trakt so it is API compatible (currently replaces "." with "-"). * * @param username A username as returned by the trakt API. * @see #ME */ public Username(String username) { if (username == null || username.length() == 0) { throw new IllegalArgumentException("trakt username can not be empty."); } this.encodedUsername = username.replace(".", "-"); } @Override public String toString() { return encodedUsername; } } ## Instruction: Remove spaces in user names. - Also ensure multiple consecutive dashes are replaced by just one. ## Code After: package com.uwetrottmann.trakt.v2.entities; public class Username { /** * Special user name for the current user (determined by auth data). */ public static final Username ME = new Username("me"); private String encodedUsername; /** * Encodes the username returned from trakt so it is API compatible (currently replaces "." with "-"). * * @param username A username as returned by the trakt API. * @see #ME */ public Username(String username) { if (username == null || username.length() == 0) { throw new IllegalArgumentException("trakt username can not be empty."); } // trakt encodes some special chars in usernames // - points "." as a dash "-" // - spaces " " as a dash "-" // - multiple dashes are reduced to one this.encodedUsername = username.replace(".", "-").replace(" ", "-").replaceAll("(-)+", "-"); } @Override public String toString() { return encodedUsername; } }
... if (username == null || username.length() == 0) { throw new IllegalArgumentException("trakt username can not be empty."); } // trakt encodes some special chars in usernames // - points "." as a dash "-" // - spaces " " as a dash "-" // - multiple dashes are reduced to one this.encodedUsername = username.replace(".", "-").replace(" ", "-").replaceAll("(-)+", "-"); } @Override ...
2352f18400d5b4b36052e04804bd04e32b000cc4
streak-podium/render.py
streak-podium/render.py
import pygal def horizontal_bar(sorted_streaks, sort_attrib): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort_attrib. """ users = [user for user, _ in sorted_streaks][::-1] streaks = [getattr(streak, sort_attrib) for _, streak in sorted_streaks][::-1] chart = pygal.HorizontalStackedBar(show_legend=False, print_values=True, print_zeroes=False, print_labels=True) chart.title = 'Top contributors by {} streak'.format(sort_attrib) chart.x_labels = users values = [] for value, user in zip(streaks, users): if value > 0: values.append({'value': value, 'label': user}) else: values.append(0) chart.add('Streaks', values) chart.render_to_file('top.svg')
import pygal def horizontal_bar(sorted_streaks, sort_attrib): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort_attrib. """ users = [user for user, _ in sorted_streaks][::-1] streaks = [getattr(streak, sort_attrib) for _, streak in sorted_streaks][::-1] chart = pygal.HorizontalStackedBar(show_y_labels=False, show_x_labels=False, show_legend=False, print_values=True, print_zeroes=False, print_labels=True) chart.title = 'Top contributors by {} streak'.format(sort_attrib) chart.x_labels = users values = [] for value, user in zip(streaks, users): if value > 0: values.append({ 'value': value, 'label': user, 'xlink': 'https://github.com/{}'.format(user) }) else: values.append(0) # Let zeroes be boring chart.add('Streaks', values) chart.render_to_file('top.svg')
Add links to profiles and clean up chart options
Add links to profiles and clean up chart options
Python
mit
jollyra/hubot-commit-streak,supermitch/streak-podium,supermitch/streak-podium,jollyra/hubot-commit-streak,jollyra/hubot-streak-podium,jollyra/hubot-streak-podium
python
## Code Before: import pygal def horizontal_bar(sorted_streaks, sort_attrib): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort_attrib. """ users = [user for user, _ in sorted_streaks][::-1] streaks = [getattr(streak, sort_attrib) for _, streak in sorted_streaks][::-1] chart = pygal.HorizontalStackedBar(show_legend=False, print_values=True, print_zeroes=False, print_labels=True) chart.title = 'Top contributors by {} streak'.format(sort_attrib) chart.x_labels = users values = [] for value, user in zip(streaks, users): if value > 0: values.append({'value': value, 'label': user}) else: values.append(0) chart.add('Streaks', values) chart.render_to_file('top.svg') ## Instruction: Add links to profiles and clean up chart options ## Code After: import pygal def horizontal_bar(sorted_streaks, sort_attrib): """ Render a horizontal bar chart of streaks. Values have already been sorted by sort_attrib. """ users = [user for user, _ in sorted_streaks][::-1] streaks = [getattr(streak, sort_attrib) for _, streak in sorted_streaks][::-1] chart = pygal.HorizontalStackedBar(show_y_labels=False, show_x_labels=False, show_legend=False, print_values=True, print_zeroes=False, print_labels=True) chart.title = 'Top contributors by {} streak'.format(sort_attrib) chart.x_labels = users values = [] for value, user in zip(streaks, users): if value > 0: values.append({ 'value': value, 'label': user, 'xlink': 'https://github.com/{}'.format(user) }) else: values.append(0) # Let zeroes be boring chart.add('Streaks', values) chart.render_to_file('top.svg')
// ... existing code ... users = [user for user, _ in sorted_streaks][::-1] streaks = [getattr(streak, sort_attrib) for _, streak in sorted_streaks][::-1] chart = pygal.HorizontalStackedBar(show_y_labels=False, show_x_labels=False, show_legend=False, print_values=True, print_zeroes=False, print_labels=True) chart.title = 'Top contributors by {} streak'.format(sort_attrib) chart.x_labels = users // ... modified code ... values = [] for value, user in zip(streaks, users): if value > 0: values.append({ 'value': value, 'label': user, 'xlink': 'https://github.com/{}'.format(user) }) else: values.append(0) # Let zeroes be boring chart.add('Streaks', values) chart.render_to_file('top.svg') // ... rest of the code ...
7cb65a86a1b0fe8a739fb81fb8a66f3d205142cb
setup.py
setup.py
from chandra_aca import __version__ from setuptools import setup try: from testr.setup_helper import cmdclass except ImportError: cmdclass = {} setup(name='chandra_aca', author='Jean Connelly, Tom Aldcroft', description='Chandra Aspect Camera Tools', author_email='[email protected]', version=__version__, zip_safe=False, packages=['chandra_aca', 'chandra_aca.tests'], package_data={'chandra_aca.tests': ['data/*.txt', 'data/*.dat'], 'chandra_aca': ['data/*.dat', 'data/star_probs/*.fits.gz']}, tests_require=['pytest'], cmdclass=cmdclass, )
from chandra_aca import __version__ from setuptools import setup try: from testr.setup_helper import cmdclass except ImportError: cmdclass = {} setup(name='chandra_aca', author='Jean Connelly, Tom Aldcroft', description='Chandra Aspect Camera Tools', author_email='[email protected]', version=__version__, zip_safe=False, packages=['chandra_aca', 'chandra_aca.tests'], package_data={'chandra_aca.tests': ['data/*.txt', 'data/*.dat'], 'chandra_aca': ['data/*.dat', 'data/*.fits.gz', 'data/star_probs/*.fits.gz']}, tests_require=['pytest'], cmdclass=cmdclass, )
Add missing package data for flickering
Add missing package data for flickering
Python
bsd-2-clause
sot/chandra_aca,sot/chandra_aca
python
## Code Before: from chandra_aca import __version__ from setuptools import setup try: from testr.setup_helper import cmdclass except ImportError: cmdclass = {} setup(name='chandra_aca', author='Jean Connelly, Tom Aldcroft', description='Chandra Aspect Camera Tools', author_email='[email protected]', version=__version__, zip_safe=False, packages=['chandra_aca', 'chandra_aca.tests'], package_data={'chandra_aca.tests': ['data/*.txt', 'data/*.dat'], 'chandra_aca': ['data/*.dat', 'data/star_probs/*.fits.gz']}, tests_require=['pytest'], cmdclass=cmdclass, ) ## Instruction: Add missing package data for flickering ## Code After: from chandra_aca import __version__ from setuptools import setup try: from testr.setup_helper import cmdclass except ImportError: cmdclass = {} setup(name='chandra_aca', author='Jean Connelly, Tom Aldcroft', description='Chandra Aspect Camera Tools', author_email='[email protected]', version=__version__, zip_safe=False, packages=['chandra_aca', 'chandra_aca.tests'], package_data={'chandra_aca.tests': ['data/*.txt', 'data/*.dat'], 'chandra_aca': ['data/*.dat', 'data/*.fits.gz', 'data/star_probs/*.fits.gz']}, tests_require=['pytest'], cmdclass=cmdclass, )
# ... existing code ... zip_safe=False, packages=['chandra_aca', 'chandra_aca.tests'], package_data={'chandra_aca.tests': ['data/*.txt', 'data/*.dat'], 'chandra_aca': ['data/*.dat', 'data/*.fits.gz', 'data/star_probs/*.fits.gz']}, tests_require=['pytest'], cmdclass=cmdclass, ) # ... rest of the code ...
7fc0758f7db4b636c50aa2e70ec27626c94f3681
src/test/java/org/sagebionetworks/bridge/sdk/ConfigTest.java
src/test/java/org/sagebionetworks/bridge/sdk/ConfigTest.java
package org.sagebionetworks.bridge.sdk; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.sagebionetworks.bridge.sdk.Config; public class ConfigTest { @Test public void createConfig() { Config conf = new Config(); assertNotNull(conf); assertEquals("conf returns values", "/researchers/v1/surveys/asdf/published", conf.getSurveyMostRecentlyPublishedVersionApi("asdf")); } @Test(expected=IllegalArgumentException.class) public void configChecksArguments() { Config conf = new Config(); conf.getSurveyMostRecentlyPublishedVersionApi(null); } @Test public void configPicksUpSystemProperty() { System.setProperty("ENV", "staging"); Config conf = new Config(); assertTrue(Environment.STAGING == conf.getEnvironment()); } }
package org.sagebionetworks.bridge.sdk; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Ignore; import org.junit.Test; import org.sagebionetworks.bridge.sdk.Config; public class ConfigTest { @Test public void createConfig() { Config conf = new Config(); assertNotNull(conf); assertEquals("conf returns values", "/researchers/v1/surveys/asdf/published", conf.getSurveyMostRecentlyPublishedVersionApi("asdf")); } @Test(expected=IllegalArgumentException.class) public void configChecksArguments() { Config conf = new Config(); conf.getSurveyMostRecentlyPublishedVersionApi(null); } // Doesn't work on Travis, does work locally. @Test @Ignore public void configPicksUpSystemProperty() { System.setProperty("ENV", "staging"); Config conf = new Config(); assertTrue(Environment.STAGING == conf.getEnvironment()); } }
Disable this test which doesn't work probably for environmental reasons
Disable this test which doesn't work probably for environmental reasons
Java
apache-2.0
Sage-Bionetworks/BridgeJavaSDK,DwayneJengSage/BridgeJavaSDK,alxdarksage/BridgeJavaSDK,DwayneJengSage/BridgeJavaSDK,alxdarksage/BridgeJavaSDK,Sage-Bionetworks/BridgeJavaSDK
java
## Code Before: package org.sagebionetworks.bridge.sdk; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.sagebionetworks.bridge.sdk.Config; public class ConfigTest { @Test public void createConfig() { Config conf = new Config(); assertNotNull(conf); assertEquals("conf returns values", "/researchers/v1/surveys/asdf/published", conf.getSurveyMostRecentlyPublishedVersionApi("asdf")); } @Test(expected=IllegalArgumentException.class) public void configChecksArguments() { Config conf = new Config(); conf.getSurveyMostRecentlyPublishedVersionApi(null); } @Test public void configPicksUpSystemProperty() { System.setProperty("ENV", "staging"); Config conf = new Config(); assertTrue(Environment.STAGING == conf.getEnvironment()); } } ## Instruction: Disable this test which doesn't work probably for environmental reasons ## Code After: package org.sagebionetworks.bridge.sdk; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Ignore; import org.junit.Test; import org.sagebionetworks.bridge.sdk.Config; public class ConfigTest { @Test public void createConfig() { Config conf = new Config(); assertNotNull(conf); assertEquals("conf returns values", "/researchers/v1/surveys/asdf/published", conf.getSurveyMostRecentlyPublishedVersionApi("asdf")); } @Test(expected=IllegalArgumentException.class) public void configChecksArguments() { Config conf = new Config(); conf.getSurveyMostRecentlyPublishedVersionApi(null); } // Doesn't work on Travis, does work locally. @Test @Ignore public void configPicksUpSystemProperty() { System.setProperty("ENV", "staging"); Config conf = new Config(); assertTrue(Environment.STAGING == conf.getEnvironment()); } }
// ... existing code ... import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Ignore; import org.junit.Test; import org.sagebionetworks.bridge.sdk.Config; // ... modified code ... conf.getSurveyMostRecentlyPublishedVersionApi(null); } // Doesn't work on Travis, does work locally. @Test @Ignore public void configPicksUpSystemProperty() { System.setProperty("ENV", "staging"); Config conf = new Config(); // ... rest of the code ...
5d91948e11400253f161be489bb8c9bf13b7ee35
source/main.py
source/main.py
"""updates subreddit css with compiled sass""" import subprocess import praw def css() -> str: """compiles sass and returns css""" res: subprocess.CompletedProcess = subprocess.run( "sass index.scss --style compressed --quiet", stdout=subprocess.PIPE ) return res.stdout def update(reddit: praw.Reddit, style: str) -> None: """update subreddit stylesheet""" sub: praw.models.Subreddit = reddit.subreddit("neoliberal") sub.wiki("config/stylesheet").update(style) return def main() -> None: """main function""" reddit: praw.Reddit = praw.Reddit() style: str = css() update(reddit, style) return if __name__ == '__main__': main()
"""updates subreddit css with compiled sass""" import subprocess import time import praw def css() -> str: """compiles sass and returns css""" res: subprocess.CompletedProcess = subprocess.run( "sass index.scss --style compressed --quiet", stdout=subprocess.PIPE ) return res.stdout def uid() -> str: """return date and time""" return "Subreddit upload on {}".format(time.strftime("%c")) def update(reddit: praw.Reddit, style: str) -> None: """update subreddit stylesheet""" reddit.subreddit("neoliberal").stylesheet.update(style, reason=uid()) return def main() -> None: """main function""" reddit: praw.Reddit = praw.Reddit() style: str = css() update(reddit, style) return if __name__ == '__main__': main()
Use direct subreddit stylesheet update function
Use direct subreddit stylesheet update function Instead of updating the wiki, uses the praw-defined function. Also adds an UID function for subreddit reason
Python
mit
neoliberal/css-updater
python
## Code Before: """updates subreddit css with compiled sass""" import subprocess import praw def css() -> str: """compiles sass and returns css""" res: subprocess.CompletedProcess = subprocess.run( "sass index.scss --style compressed --quiet", stdout=subprocess.PIPE ) return res.stdout def update(reddit: praw.Reddit, style: str) -> None: """update subreddit stylesheet""" sub: praw.models.Subreddit = reddit.subreddit("neoliberal") sub.wiki("config/stylesheet").update(style) return def main() -> None: """main function""" reddit: praw.Reddit = praw.Reddit() style: str = css() update(reddit, style) return if __name__ == '__main__': main() ## Instruction: Use direct subreddit stylesheet update function Instead of updating the wiki, uses the praw-defined function. Also adds an UID function for subreddit reason ## Code After: """updates subreddit css with compiled sass""" import subprocess import time import praw def css() -> str: """compiles sass and returns css""" res: subprocess.CompletedProcess = subprocess.run( "sass index.scss --style compressed --quiet", stdout=subprocess.PIPE ) return res.stdout def uid() -> str: """return date and time""" return "Subreddit upload on {}".format(time.strftime("%c")) def update(reddit: praw.Reddit, style: str) -> None: """update subreddit stylesheet""" reddit.subreddit("neoliberal").stylesheet.update(style, reason=uid()) return def main() -> None: """main function""" reddit: praw.Reddit = praw.Reddit() style: str = css() update(reddit, style) return if __name__ == '__main__': main()
// ... existing code ... """updates subreddit css with compiled sass""" import subprocess import time import praw def css() -> str: // ... modified code ... ) return res.stdout def uid() -> str: """return date and time""" return "Subreddit upload on {}".format(time.strftime("%c")) def update(reddit: praw.Reddit, style: str) -> None: """update subreddit stylesheet""" reddit.subreddit("neoliberal").stylesheet.update(style, reason=uid()) return def main() -> None: // ... rest of the code ...
2b1cc5b2426994953e8f8b937364d91f4e7aadf2
MyHub/MyHub/urls.py
MyHub/MyHub/urls.py
from django.conf.urls import patterns, include, url from MyHub.home.views import home_page from MyHub.resume.views import resume_page from MyHub.projects.views import projects_page from MyHub.contact.views import contact_page from MyHub.views import loader_page from django.contrib import admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'MyHub.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', loader_page, name='loader'), url(r'^home/$', home_page, name='index'), url(r'^resume/$', resume_page, name='resume'), url(r'^projects/$', projects_page, name='projects'), url(r'^contact/$', contact_page, name='contact'), url(r'^admin/', include(admin.site.urls)), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
from django.conf.urls import patterns, include, url from MyHub.home.views import home_page from MyHub.resume.views import resume_page from MyHub.projects.views import projects_page from MyHub.contact.views import contact_page from MyHub.views import loader_page from django.contrib import admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'MyHub.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', home_page, name='loader'), # url(r'^home/$', home_page, name='index'), # url(r'^resume/$', resume_page, name='resume'), # url(r'^projects/$', projects_page, name='projects'), # url(r'^contact/$', contact_page, name='contact'), # url(r'^admin/', include(admin.site.urls)), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Change default URL to display home content. Temporary fix.
Change default URL to display home content. Temporary fix.
Python
mit
sebastienbarbier/sebastienbarbier.com,sebastienbarbier/sebastienbarbier.com,sebastienbarbier/sebastienbarbier.com,sebastienbarbier/sebastienbarbier.com
python
## Code Before: from django.conf.urls import patterns, include, url from MyHub.home.views import home_page from MyHub.resume.views import resume_page from MyHub.projects.views import projects_page from MyHub.contact.views import contact_page from MyHub.views import loader_page from django.contrib import admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'MyHub.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', loader_page, name='loader'), url(r'^home/$', home_page, name='index'), url(r'^resume/$', resume_page, name='resume'), url(r'^projects/$', projects_page, name='projects'), url(r'^contact/$', contact_page, name='contact'), url(r'^admin/', include(admin.site.urls)), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ## Instruction: Change default URL to display home content. Temporary fix. ## Code After: from django.conf.urls import patterns, include, url from MyHub.home.views import home_page from MyHub.resume.views import resume_page from MyHub.projects.views import projects_page from MyHub.contact.views import contact_page from MyHub.views import loader_page from django.contrib import admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'MyHub.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', home_page, name='loader'), # url(r'^home/$', home_page, name='index'), # url(r'^resume/$', resume_page, name='resume'), # url(r'^projects/$', projects_page, name='projects'), # url(r'^contact/$', contact_page, name='contact'), # url(r'^admin/', include(admin.site.urls)), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
// ... existing code ... # url(r'^$', 'MyHub.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', home_page, name='loader'), # url(r'^home/$', home_page, name='index'), # url(r'^resume/$', resume_page, name='resume'), # url(r'^projects/$', projects_page, name='projects'), # url(r'^contact/$', contact_page, name='contact'), # url(r'^admin/', include(admin.site.urls)), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) // ... rest of the code ...
fb08c6cfe6b6295a9aca9e579a067f34ee1c69c2
test/get-gh-comment-info.py
test/get-gh-comment-info.py
import argparse parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases parser.add_argument('--focus', type=str, default="") parser.add_argument('--kernel_version', type=str, default="") parser.add_argument('--k8s_version', type=str, default="") parser.add_argument('--retrieve', type=str, default="focus") args = parser.parse_args() print(args.__dict__[args.retrieve])
import argparse parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases parser.add_argument('--focus', type=str, default="") parser.add_argument('--kernel_version', type=str, default="") parser.add_argument('--k8s_version', type=str, default="") parser.add_argument('--retrieve', type=str, default="focus") args = parser.parse_args() # Update kernel_version to expected format args.kernel_version = args.kernel_version.replace('.', '') if args.kernel_version == "netnext": args.kernel_version = "net-next" print(args.__dict__[args.retrieve])
Format test-only's kernel_version to avoid mistakes
test: Format test-only's kernel_version to avoid mistakes I often try to start test-only builds with e.g.: test-only --kernel_version=4.19 --focus="..." That fails because our tests expect "419". We can extend the Python script used to parse argument to recognize that and update kernel_version to the expected format. Signed-off-by: Paul Chaignon <[email protected]>
Python
apache-2.0
cilium/cilium,tklauser/cilium,tgraf/cilium,tklauser/cilium,michi-covalent/cilium,tklauser/cilium,cilium/cilium,tgraf/cilium,cilium/cilium,michi-covalent/cilium,tgraf/cilium,tgraf/cilium,michi-covalent/cilium,michi-covalent/cilium,tgraf/cilium,cilium/cilium,tklauser/cilium,michi-covalent/cilium,tklauser/cilium,cilium/cilium,tgraf/cilium
python
## Code Before: import argparse parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases parser.add_argument('--focus', type=str, default="") parser.add_argument('--kernel_version', type=str, default="") parser.add_argument('--k8s_version', type=str, default="") parser.add_argument('--retrieve', type=str, default="focus") args = parser.parse_args() print(args.__dict__[args.retrieve]) ## Instruction: test: Format test-only's kernel_version to avoid mistakes I often try to start test-only builds with e.g.: test-only --kernel_version=4.19 --focus="..." That fails because our tests expect "419". We can extend the Python script used to parse argument to recognize that and update kernel_version to the expected format. Signed-off-by: Paul Chaignon <[email protected]> ## Code After: import argparse parser = argparse.ArgumentParser() parser.add_argument('ghcomment', type=str) # this is for test-me-please phrases parser.add_argument('--focus', type=str, default="") parser.add_argument('--kernel_version', type=str, default="") parser.add_argument('--k8s_version', type=str, default="") parser.add_argument('--retrieve', type=str, default="focus") args = parser.parse_args() # Update kernel_version to expected format args.kernel_version = args.kernel_version.replace('.', '') if args.kernel_version == "netnext": args.kernel_version = "net-next" print(args.__dict__[args.retrieve])
# ... existing code ... args = parser.parse_args() # Update kernel_version to expected format args.kernel_version = args.kernel_version.replace('.', '') if args.kernel_version == "netnext": args.kernel_version = "net-next" print(args.__dict__[args.retrieve]) # ... rest of the code ...
3351da194e68efb663008664f5687078d9299984
app/src/main/java/es/craftmanship/toledo/katangapp/utils/GPSTracker.java
app/src/main/java/es/craftmanship/toledo/katangapp/utils/GPSTracker.java
package es.craftmanship.toledo.katangapp.utils; /** * Created by cristobal on 3/2/16. */ public class GPSTracker { }
package es.craftmanship.toledo.katangapp.utils; import android.app.Service; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.Nullable; /** * Created by cristobal on 3/2/16. */ public class GPSTracker extends Service implements LocationListener { @Override public void onLocationChanged(Location location) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }
Add methods extended from android.app.Service and LocationListener
Add methods extended from android.app.Service and LocationListener
Java
apache-2.0
craftsmanship-toledo/katangapp-android
java
## Code Before: package es.craftmanship.toledo.katangapp.utils; /** * Created by cristobal on 3/2/16. */ public class GPSTracker { } ## Instruction: Add methods extended from android.app.Service and LocationListener ## Code After: package es.craftmanship.toledo.katangapp.utils; import android.app.Service; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.Nullable; /** * Created by cristobal on 3/2/16. */ public class GPSTracker extends Service implements LocationListener { @Override public void onLocationChanged(Location location) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }
# ... existing code ... package es.craftmanship.toledo.katangapp.utils; import android.app.Service; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.Nullable; /** * Created by cristobal on 3/2/16. */ public class GPSTracker extends Service implements LocationListener { @Override public void onLocationChanged(Location location) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Nullable @Override public IBinder onBind(Intent intent) { return null; } } # ... rest of the code ...
00712888b761bce556b73e36c9c7270829d3a1d4
tests/test_entity.py
tests/test_entity.py
from test_provider_gtfs import provider from busbus.entity import BaseEntityJSONEncoder import json import pytest @pytest.fixture(scope='module') def agency(provider): return next(provider.agencies) def test_entity_repr(agency): assert 'DTA' in repr(agency) def test_entity_failed_getattr(agency): with pytest.raises(AttributeError): agency.the_weather_in_london def test_entity_failed_getitem(agency): with pytest.raises(KeyError): agency['the_weather_in_london'] def test_entity_to_dict(agency): assert dict(agency)['id'] == 'DTA' def test_entity_to_json(provider): json_str = BaseEntityJSONEncoder().encode(next(provider.arrivals)) json.loads(json_str)
from test_provider_gtfs import provider from busbus.entity import BaseEntityJSONEncoder import json import pytest @pytest.fixture(scope='module') def agency(provider): return next(provider.agencies) def test_entity_repr(agency): assert 'DTA' in repr(agency) def test_entity_failed_getattr(agency): with pytest.raises(AttributeError): agency.the_weather_in_london def test_entity_failed_getitem(agency): with pytest.raises(KeyError): agency['the_weather_in_london'] def test_entity_to_dict(agency): assert dict(agency)['id'] == 'DTA' def test_entity_to_json(provider): json_str = BaseEntityJSONEncoder().encode(next(provider.arrivals)) json.loads(json_str) def test_bad_json(): with pytest.raises(TypeError): BaseEntityJSONEncoder().encode(set())
Test the failure branch in BaseEntityJSONDecoder
Test the failure branch in BaseEntityJSONDecoder
Python
mit
spaceboats/busbus
python
## Code Before: from test_provider_gtfs import provider from busbus.entity import BaseEntityJSONEncoder import json import pytest @pytest.fixture(scope='module') def agency(provider): return next(provider.agencies) def test_entity_repr(agency): assert 'DTA' in repr(agency) def test_entity_failed_getattr(agency): with pytest.raises(AttributeError): agency.the_weather_in_london def test_entity_failed_getitem(agency): with pytest.raises(KeyError): agency['the_weather_in_london'] def test_entity_to_dict(agency): assert dict(agency)['id'] == 'DTA' def test_entity_to_json(provider): json_str = BaseEntityJSONEncoder().encode(next(provider.arrivals)) json.loads(json_str) ## Instruction: Test the failure branch in BaseEntityJSONDecoder ## Code After: from test_provider_gtfs import provider from busbus.entity import BaseEntityJSONEncoder import json import pytest @pytest.fixture(scope='module') def agency(provider): return next(provider.agencies) def test_entity_repr(agency): assert 'DTA' in repr(agency) def test_entity_failed_getattr(agency): with pytest.raises(AttributeError): agency.the_weather_in_london def test_entity_failed_getitem(agency): with pytest.raises(KeyError): agency['the_weather_in_london'] def test_entity_to_dict(agency): assert dict(agency)['id'] == 'DTA' def test_entity_to_json(provider): json_str = BaseEntityJSONEncoder().encode(next(provider.arrivals)) json.loads(json_str) def test_bad_json(): with pytest.raises(TypeError): BaseEntityJSONEncoder().encode(set())
// ... existing code ... def test_entity_to_json(provider): json_str = BaseEntityJSONEncoder().encode(next(provider.arrivals)) json.loads(json_str) def test_bad_json(): with pytest.raises(TypeError): BaseEntityJSONEncoder().encode(set()) // ... rest of the code ...
0e6bcc34c6601b2ed2336d54e49bf23c12e30c60
Settings/Controls/Dialog.h
Settings/Controls/Dialog.h
// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #pragma once #include <Windows.h> #include <unordered_map> class Control; class Dialog { public: Dialog(); Dialog(HWND parent, LPCWSTR dlgTemplate); void AddControl(Control *control); HWND DialogHandle(); HWND ParentHandle(); void Show(); protected: HWND _dlgHwnd; HWND _parent; /// <summary>Maps control IDs to their respective instances.</summary> std::unordered_map<int, Control *> _controlMap; static INT_PTR CALLBACK StaticDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); virtual INT_PTR CALLBACK DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); };
// Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #pragma once #include <Windows.h> #include <unordered_map> class Control; class Dialog { public: Dialog(); Dialog(HWND parent, LPCWSTR dlgTemplate); void AddControl(Control *control); HWND DialogHandle(); HWND ParentHandle(); void Show(); protected: HWND _dlgHwnd; HWND _parent; LPCWSTR _template; /// <summary>Maps control IDs to their respective instances.</summary> std::unordered_map<int, Control *> _controlMap; static INT_PTR CALLBACK StaticDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); virtual INT_PTR CALLBACK DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); };
Maintain the template string as an instance variable
Maintain the template string as an instance variable
C
bsd-2-clause
malensek/3RVX,malensek/3RVX,malensek/3RVX
c
## Code Before: // Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #pragma once #include <Windows.h> #include <unordered_map> class Control; class Dialog { public: Dialog(); Dialog(HWND parent, LPCWSTR dlgTemplate); void AddControl(Control *control); HWND DialogHandle(); HWND ParentHandle(); void Show(); protected: HWND _dlgHwnd; HWND _parent; /// <summary>Maps control IDs to their respective instances.</summary> std::unordered_map<int, Control *> _controlMap; static INT_PTR CALLBACK StaticDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); virtual INT_PTR CALLBACK DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); }; ## Instruction: Maintain the template string as an instance variable ## Code After: // Copyright (c) 2015, Matthew Malensek. // Distributed under the BSD 2-Clause License (see LICENSE.txt for details) #pragma once #include <Windows.h> #include <unordered_map> class Control; class Dialog { public: Dialog(); Dialog(HWND parent, LPCWSTR dlgTemplate); void AddControl(Control *control); HWND DialogHandle(); HWND ParentHandle(); void Show(); protected: HWND _dlgHwnd; HWND _parent; LPCWSTR _template; /// <summary>Maps control IDs to their respective instances.</summary> std::unordered_map<int, Control *> _controlMap; static INT_PTR CALLBACK StaticDialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); virtual INT_PTR CALLBACK DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); };
... protected: HWND _dlgHwnd; HWND _parent; LPCWSTR _template; /// <summary>Maps control IDs to their respective instances.</summary> std::unordered_map<int, Control *> _controlMap; ...
843dd99fdd5dcc1154d5693d0058e54b809da60c
vespajlib/src/main/java/com/yahoo/concurrent/classlock/ClassLocking.java
vespajlib/src/main/java/com/yahoo/concurrent/classlock/ClassLocking.java
package com.yahoo.concurrent.classlock; import java.util.HashMap; import java.util.Map; import java.util.function.BooleanSupplier; /** * @author valerijf */ public class ClassLocking { private final Map<Class<?>, ClassLock> classLocks = new HashMap<>(); private final Object monitor = new Object(); public ClassLock lock(Class<?> clazz) { return lockWhile(clazz, () -> true); } public ClassLock lockWhile(Class<?> clazz, BooleanSupplier interruptCondition) { synchronized (monitor) { while (classLocks.containsKey(clazz)) { try { monitor.wait(); } catch (InterruptedException ignored) { } if (!interruptCondition.getAsBoolean()) { throw new LockInterruptException(); } } ClassLock classLock = new ClassLock(this, clazz); classLocks.put(clazz, classLock); return classLock; } } void unlock(Class<?> clazz, ClassLock classLock) { synchronized (monitor) { if (classLock.equals(classLocks.get(clazz))) { classLocks.remove(clazz); monitor.notifyAll(); } else { throw new IllegalArgumentException("Lock has already been released"); } } } public void interrupt() { synchronized (monitor) { monitor.notifyAll(); } } }
package com.yahoo.concurrent.classlock; import java.util.HashMap; import java.util.Map; import java.util.function.BooleanSupplier; /** * @author valerijf */ public class ClassLocking { private final Map<String, ClassLock> classLocks = new HashMap<>(); private final Object monitor = new Object(); public ClassLock lock(Class<?> clazz) { return lockWhile(clazz, () -> true); } public ClassLock lockWhile(Class<?> clazz, BooleanSupplier interruptCondition) { synchronized (monitor) { while (classLocks.containsKey(clazz.getName())) { try { monitor.wait(); } catch (InterruptedException ignored) { } if (!interruptCondition.getAsBoolean()) { throw new LockInterruptException(); } } ClassLock classLock = new ClassLock(this, clazz); classLocks.put(clazz.getName(), classLock); return classLock; } } void unlock(Class<?> clazz, ClassLock classLock) { synchronized (monitor) { if (classLock.equals(classLocks.get(clazz.getName()))) { classLocks.remove(clazz.getName()); monitor.notifyAll(); } else { throw new IllegalArgumentException("Lock has already been released"); } } } public void interrupt() { synchronized (monitor) { monitor.notifyAll(); } } }
Use String as lock key
Use String as lock key
Java
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
java
## Code Before: package com.yahoo.concurrent.classlock; import java.util.HashMap; import java.util.Map; import java.util.function.BooleanSupplier; /** * @author valerijf */ public class ClassLocking { private final Map<Class<?>, ClassLock> classLocks = new HashMap<>(); private final Object monitor = new Object(); public ClassLock lock(Class<?> clazz) { return lockWhile(clazz, () -> true); } public ClassLock lockWhile(Class<?> clazz, BooleanSupplier interruptCondition) { synchronized (monitor) { while (classLocks.containsKey(clazz)) { try { monitor.wait(); } catch (InterruptedException ignored) { } if (!interruptCondition.getAsBoolean()) { throw new LockInterruptException(); } } ClassLock classLock = new ClassLock(this, clazz); classLocks.put(clazz, classLock); return classLock; } } void unlock(Class<?> clazz, ClassLock classLock) { synchronized (monitor) { if (classLock.equals(classLocks.get(clazz))) { classLocks.remove(clazz); monitor.notifyAll(); } else { throw new IllegalArgumentException("Lock has already been released"); } } } public void interrupt() { synchronized (monitor) { monitor.notifyAll(); } } } ## Instruction: Use String as lock key ## Code After: package com.yahoo.concurrent.classlock; import java.util.HashMap; import java.util.Map; import java.util.function.BooleanSupplier; /** * @author valerijf */ public class ClassLocking { private final Map<String, ClassLock> classLocks = new HashMap<>(); private final Object monitor = new Object(); public ClassLock lock(Class<?> clazz) { return lockWhile(clazz, () -> true); } public ClassLock lockWhile(Class<?> clazz, BooleanSupplier interruptCondition) { synchronized (monitor) { while (classLocks.containsKey(clazz.getName())) { try { monitor.wait(); } catch (InterruptedException ignored) { } if (!interruptCondition.getAsBoolean()) { throw new LockInterruptException(); } } ClassLock classLock = new ClassLock(this, clazz); classLocks.put(clazz.getName(), classLock); return classLock; } } void unlock(Class<?> clazz, ClassLock classLock) { synchronized (monitor) { if (classLock.equals(classLocks.get(clazz.getName()))) { classLocks.remove(clazz.getName()); monitor.notifyAll(); } else { throw new IllegalArgumentException("Lock has already been released"); } } } public void interrupt() { synchronized (monitor) { monitor.notifyAll(); } } }
# ... existing code ... * @author valerijf */ public class ClassLocking { private final Map<String, ClassLock> classLocks = new HashMap<>(); private final Object monitor = new Object(); public ClassLock lock(Class<?> clazz) { # ... modified code ... public ClassLock lockWhile(Class<?> clazz, BooleanSupplier interruptCondition) { synchronized (monitor) { while (classLocks.containsKey(clazz.getName())) { try { monitor.wait(); } catch (InterruptedException ignored) { ... } ClassLock classLock = new ClassLock(this, clazz); classLocks.put(clazz.getName(), classLock); return classLock; } } ... void unlock(Class<?> clazz, ClassLock classLock) { synchronized (monitor) { if (classLock.equals(classLocks.get(clazz.getName()))) { classLocks.remove(clazz.getName()); monitor.notifyAll(); } else { throw new IllegalArgumentException("Lock has already been released"); # ... rest of the code ...
df55e36869789e3b4b94114a339dd2390156fc0b
account/urls.py
account/urls.py
from django.conf.urls import url from django.contrib.auth.views import ( password_change, password_change_done, password_reset, password_reset_done, password_reset_confirm, password_reset_complete, LoginView, LogoutView, ) from .views import AccountView urlpatterns = [ url(r'^$', AccountView.as_view(), name='view'), url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'), url(r'^login/$', LoginView.as_view(), name='login'), url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}), url(r'^password/change/$', password_change, name='password-change', kwargs={'post_change_redirect': 'account:password-change-done'}), url(r'^password/change/done/$', password_change_done, name='password-change-done'), url(r'^password/reset/$', password_reset, name='password-reset', kwargs={'post_reset_redirect': 'account:password-reset-done'}), url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'), url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm', kwargs={'post_reset_redirect': 'account:password-reset-complete'}), url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'), ]
from django.conf.urls import url from django.contrib.auth.views import ( password_change, password_change_done, password_reset, password_reset_done, password_reset_confirm, password_reset_complete, LoginView, LogoutView, ) from .views import AccountView urlpatterns = [ url(r'^$', AccountView.as_view(), name='view'), url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'), url(r'^profile/$', AccountView.as_view(), name='profile'), url(r'^login/$', LoginView.as_view(), name='login'), url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}), url(r'^password/change/$', password_change, name='password-change', kwargs={'post_change_redirect': 'account:password-change-done'}), url(r'^password/change/done/$', password_change_done, name='password-change-done'), url(r'^password/reset/$', password_reset, name='password-reset', kwargs={'post_reset_redirect': 'account:password-reset-done'}), url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'), url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm', kwargs={'post_reset_redirect': 'account:password-reset-complete'}), url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'), ]
Add profile view - default login redirect
Add profile view - default login redirect
Python
mit
uda/djaccount,uda/djaccount
python
## Code Before: from django.conf.urls import url from django.contrib.auth.views import ( password_change, password_change_done, password_reset, password_reset_done, password_reset_confirm, password_reset_complete, LoginView, LogoutView, ) from .views import AccountView urlpatterns = [ url(r'^$', AccountView.as_view(), name='view'), url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'), url(r'^login/$', LoginView.as_view(), name='login'), url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}), url(r'^password/change/$', password_change, name='password-change', kwargs={'post_change_redirect': 'account:password-change-done'}), url(r'^password/change/done/$', password_change_done, name='password-change-done'), url(r'^password/reset/$', password_reset, name='password-reset', kwargs={'post_reset_redirect': 'account:password-reset-done'}), url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'), url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm', kwargs={'post_reset_redirect': 'account:password-reset-complete'}), url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'), ] ## Instruction: Add profile view - default login redirect ## Code After: from django.conf.urls import url from django.contrib.auth.views import ( password_change, password_change_done, password_reset, password_reset_done, password_reset_confirm, password_reset_complete, LoginView, LogoutView, ) from .views import AccountView urlpatterns = [ url(r'^$', AccountView.as_view(), name='view'), url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'), url(r'^profile/$', AccountView.as_view(), name='profile'), url(r'^login/$', LoginView.as_view(), name='login'), url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}), url(r'^password/change/$', password_change, name='password-change', kwargs={'post_change_redirect': 'account:password-change-done'}), url(r'^password/change/done/$', password_change_done, name='password-change-done'), url(r'^password/reset/$', password_reset, name='password-reset', kwargs={'post_reset_redirect': 'account:password-reset-done'}), url(r'^password/reset/done/$', password_reset_done, name='password-reset-done'), url(r'^password/reset/confirm/$', password_reset_confirm, name='password-reset-confirm', kwargs={'post_reset_redirect': 'account:password-reset-complete'}), url(r'^password/reset/complete/$', password_reset_complete, name='password-reset-complete'), ]
... urlpatterns = [ url(r'^$', AccountView.as_view(), name='view'), url(r'^(?P<pk>\d+)/$', AccountView.as_view(), name='view-one'), url(r'^profile/$', AccountView.as_view(), name='profile'), url(r'^login/$', LoginView.as_view(), name='login'), url(r'^logout/$', LogoutView.as_view(), name='logout', kwargs={'next_page': '/'}), ...
09d9b0e677a1b035a6c921b1dfb06789ced5afd4
mobile/src/test/java/com/alexstyl/specialdates/events/DateDisplayStringCreatorTest.java
mobile/src/test/java/com/alexstyl/specialdates/events/DateDisplayStringCreatorTest.java
package com.alexstyl.specialdates.events; import com.alexstyl.specialdates.date.DateDisplayStringCreator; import com.alexstyl.specialdates.date.Date; import org.junit.BeforeClass; import org.junit.Test; import static org.fest.assertions.api.Assertions.assertThat; public class DateDisplayStringCreatorTest { private static final String EXPECTED_STRING = "1995-05-05"; private static final String EXPECTED_STRING_NO_YEAR = "--05-05"; private static DateDisplayStringCreator creator; @BeforeClass public static void init() { creator = DateDisplayStringCreator.INSTANCE; } @Test public void givenDateWithYear_thenReturningStringIsCorrect() { Date date = Date.on(5, 5, 1995); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo(EXPECTED_STRING); } @Test public void givenDateWithNoYear_thenReturningStringIsCorrect() { Date date = Date.on(5, 5); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo(EXPECTED_STRING_NO_YEAR); } }
package com.alexstyl.specialdates.events; import com.alexstyl.specialdates.date.DateDisplayStringCreator; import com.alexstyl.specialdates.date.Date; import org.junit.BeforeClass; import org.junit.Test; import static com.alexstyl.specialdates.date.DateConstants.MAY; import static org.fest.assertions.api.Assertions.assertThat; public class DateDisplayStringCreatorTest { private static DateDisplayStringCreator creator; @BeforeClass public static void init() { creator = DateDisplayStringCreator.INSTANCE; } @Test public void givenDateWithYear_thenReturningStringIsCorrect() { Date date = Date.on(5, MAY, 1995); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo("1995-05-05"); } @Test public void givenDateWithNoYear_thenReturningStringIsCorrect() { Date date = Date.on(5, MAY); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo("--05-05"); } }
Replace magic numbers with constants
Replace magic numbers with constants
Java
mit
pchrysa/Memento-Calendar,pchrysa/Memento-Calendar,pchrysa/Memento-Calendar
java
## Code Before: package com.alexstyl.specialdates.events; import com.alexstyl.specialdates.date.DateDisplayStringCreator; import com.alexstyl.specialdates.date.Date; import org.junit.BeforeClass; import org.junit.Test; import static org.fest.assertions.api.Assertions.assertThat; public class DateDisplayStringCreatorTest { private static final String EXPECTED_STRING = "1995-05-05"; private static final String EXPECTED_STRING_NO_YEAR = "--05-05"; private static DateDisplayStringCreator creator; @BeforeClass public static void init() { creator = DateDisplayStringCreator.INSTANCE; } @Test public void givenDateWithYear_thenReturningStringIsCorrect() { Date date = Date.on(5, 5, 1995); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo(EXPECTED_STRING); } @Test public void givenDateWithNoYear_thenReturningStringIsCorrect() { Date date = Date.on(5, 5); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo(EXPECTED_STRING_NO_YEAR); } } ## Instruction: Replace magic numbers with constants ## Code After: package com.alexstyl.specialdates.events; import com.alexstyl.specialdates.date.DateDisplayStringCreator; import com.alexstyl.specialdates.date.Date; import org.junit.BeforeClass; import org.junit.Test; import static com.alexstyl.specialdates.date.DateConstants.MAY; import static org.fest.assertions.api.Assertions.assertThat; public class DateDisplayStringCreatorTest { private static DateDisplayStringCreator creator; @BeforeClass public static void init() { creator = DateDisplayStringCreator.INSTANCE; } @Test public void givenDateWithYear_thenReturningStringIsCorrect() { Date date = Date.on(5, MAY, 1995); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo("1995-05-05"); } @Test public void givenDateWithNoYear_thenReturningStringIsCorrect() { Date date = Date.on(5, MAY); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo("--05-05"); } }
// ... existing code ... import org.junit.BeforeClass; import org.junit.Test; import static com.alexstyl.specialdates.date.DateConstants.MAY; import static org.fest.assertions.api.Assertions.assertThat; public class DateDisplayStringCreatorTest { private static DateDisplayStringCreator creator; // ... modified code ... @Test public void givenDateWithYear_thenReturningStringIsCorrect() { Date date = Date.on(5, MAY, 1995); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo("1995-05-05"); } @Test public void givenDateWithNoYear_thenReturningStringIsCorrect() { Date date = Date.on(5, MAY); String dateToString = creator.stringOf(date); assertThat(dateToString).isEqualTo("--05-05"); } } // ... rest of the code ...
3310d8a83871fc0644045295db60cb3bbfe7f141
tests/_support/empty_subcollection.py
tests/_support/empty_subcollection.py
from invoke import task, Collection @task def dummy(c): pass ns = Collection(dummy, subcollection=Collection())
from invoke import task, Collection @task def dummy(c): pass ns = Collection(dummy, Collection('subcollection'))
Fix a dumb test fixture mistake
Fix a dumb test fixture mistake
Python
bsd-2-clause
pyinvoke/invoke,pyinvoke/invoke
python
## Code Before: from invoke import task, Collection @task def dummy(c): pass ns = Collection(dummy, subcollection=Collection()) ## Instruction: Fix a dumb test fixture mistake ## Code After: from invoke import task, Collection @task def dummy(c): pass ns = Collection(dummy, Collection('subcollection'))
# ... existing code ... def dummy(c): pass ns = Collection(dummy, Collection('subcollection')) # ... rest of the code ...
bf0b3cb27fa2b518fcc3f5116da0e4dbde25aae8
src/django_richenum/__init__.py
src/django_richenum/__init__.py
import forms # noqa import models # noqa __all__ = ( 'forms', 'models', ) __version__ = 'unknown' try: __version__ = __import__('pkg_resources').get_distribution('django_richenum').version except Exception as e: pass
__version__ = 'unknown' try: __version__ = __import__('pkg_resources').get_distribution('django_richenum').version except Exception as e: pass
Remove unnecessary import of form submodule
Remove unnecessary import of form submodule
Python
mit
hearsaycorp/django-richenum,dhui/django-richenum,hearsaycorp/django-richenum,asherf/django-richenum,adepue/django-richenum
python
## Code Before: import forms # noqa import models # noqa __all__ = ( 'forms', 'models', ) __version__ = 'unknown' try: __version__ = __import__('pkg_resources').get_distribution('django_richenum').version except Exception as e: pass ## Instruction: Remove unnecessary import of form submodule ## Code After: __version__ = 'unknown' try: __version__ = __import__('pkg_resources').get_distribution('django_richenum').version except Exception as e: pass
// ... existing code ... __version__ = 'unknown' try: __version__ = __import__('pkg_resources').get_distribution('django_richenum').version // ... rest of the code ...
84c477792c752c71a1760193a706698d45c2c70a
app/src/main/java/com/example/android/miwok/Word.java
app/src/main/java/com/example/android/miwok/Word.java
package com.example.android.miwok; /** * {@link Word} represents a vocabulary word that the user wants to learn. * It contains a default translation and a Miwok translation for that word. */ public class Word { //Default translation for the word private String mDeafaultTranslation; //Miwok translation for the word private String mMiwokTranslation; //Store image resource id to associate icon with word private int mImageResourceId; //Constructor which takes in two string parameters public Word(String defaultTranslation, String miwokTranslation) { mDeafaultTranslation = defaultTranslation; mMiwokTranslation = miwokTranslation; } /** * Get the default translation of the word */ public String getDefaultTranslation() { return mDeafaultTranslation; } /** * Get the Miwok translation of the word */ public String getMiwokTranslation() { return mMiwokTranslation; } /** * Get the image resource id of the word */ public int getImageResourceID() { return mImageResourceId; } }
package com.example.android.miwok; import java.lang.reflect.Constructor; /** * {@link Word} represents a vocabulary word that the user wants to learn. * It contains a default translation and a Miwok translation for that word. */ public class Word { //Default translation for the word private String mDeafaultTranslation; //Miwok translation for the word private String mMiwokTranslation; //Store image resource id to associate icon with word private int mImageResourceId; /** * Constructor which takes in two string parameters * @param defaultTranslation is the word in a English language * @param miwokTranslation is the word in Miwok language */ public Word(String defaultTranslation, String miwokTranslation) { mDeafaultTranslation = defaultTranslation; mMiwokTranslation = miwokTranslation; } /** * Constructor which takes in two string parameters and one image resource id * @param defaultTranslation is the word in a English language * @param miwokTranslation is the word in Miwok language * @param imageResourceID is the drawable resource id of the image associated with the word */ public Word(String defaultTranslation, String miwokTranslation, int imageResourceID) { mDeafaultTranslation = defaultTranslation; mMiwokTranslation = miwokTranslation; mImageResourceId = imageResourceID; } /** * Get the default translation of the word */ public String getDefaultTranslation() { return mDeafaultTranslation; } /** * Get the Miwok translation of the word */ public String getMiwokTranslation() { return mMiwokTranslation; } /** * Get the image resource id of the word */ public int getImageResourceID() { return mImageResourceId; } }
Add a second constructor which will have 3 input parameters
Add a second constructor which will have 3 input parameters
Java
apache-2.0
kboul/MiwokApp
java
## Code Before: package com.example.android.miwok; /** * {@link Word} represents a vocabulary word that the user wants to learn. * It contains a default translation and a Miwok translation for that word. */ public class Word { //Default translation for the word private String mDeafaultTranslation; //Miwok translation for the word private String mMiwokTranslation; //Store image resource id to associate icon with word private int mImageResourceId; //Constructor which takes in two string parameters public Word(String defaultTranslation, String miwokTranslation) { mDeafaultTranslation = defaultTranslation; mMiwokTranslation = miwokTranslation; } /** * Get the default translation of the word */ public String getDefaultTranslation() { return mDeafaultTranslation; } /** * Get the Miwok translation of the word */ public String getMiwokTranslation() { return mMiwokTranslation; } /** * Get the image resource id of the word */ public int getImageResourceID() { return mImageResourceId; } } ## Instruction: Add a second constructor which will have 3 input parameters ## Code After: package com.example.android.miwok; import java.lang.reflect.Constructor; /** * {@link Word} represents a vocabulary word that the user wants to learn. * It contains a default translation and a Miwok translation for that word. */ public class Word { //Default translation for the word private String mDeafaultTranslation; //Miwok translation for the word private String mMiwokTranslation; //Store image resource id to associate icon with word private int mImageResourceId; /** * Constructor which takes in two string parameters * @param defaultTranslation is the word in a English language * @param miwokTranslation is the word in Miwok language */ public Word(String defaultTranslation, String miwokTranslation) { mDeafaultTranslation = defaultTranslation; mMiwokTranslation = miwokTranslation; } /** * Constructor which takes in two string parameters and one image resource id * @param defaultTranslation is the word in a English language * @param miwokTranslation is the word in Miwok language * @param imageResourceID is the drawable resource id of the image associated with the word */ public Word(String defaultTranslation, String miwokTranslation, int imageResourceID) { mDeafaultTranslation = defaultTranslation; mMiwokTranslation = miwokTranslation; mImageResourceId = imageResourceID; } /** * Get the default translation of the word */ public String getDefaultTranslation() { return mDeafaultTranslation; } /** * Get the Miwok translation of the word */ public String getMiwokTranslation() { return mMiwokTranslation; } /** * Get the image resource id of the word */ public int getImageResourceID() { return mImageResourceId; } }
// ... existing code ... package com.example.android.miwok; import java.lang.reflect.Constructor; /** * {@link Word} represents a vocabulary word that the user wants to learn. // ... modified code ... //Store image resource id to associate icon with word private int mImageResourceId; /** * Constructor which takes in two string parameters * @param defaultTranslation is the word in a English language * @param miwokTranslation is the word in Miwok language */ public Word(String defaultTranslation, String miwokTranslation) { mDeafaultTranslation = defaultTranslation; mMiwokTranslation = miwokTranslation; } /** * Constructor which takes in two string parameters and one image resource id * @param defaultTranslation is the word in a English language * @param miwokTranslation is the word in Miwok language * @param imageResourceID is the drawable resource id of the image associated with the word */ public Word(String defaultTranslation, String miwokTranslation, int imageResourceID) { mDeafaultTranslation = defaultTranslation; mMiwokTranslation = miwokTranslation; mImageResourceId = imageResourceID; } /** // ... rest of the code ...
1ec0f5267119874244474072dfb32f952ae4a8f1
setup.py
setup.py
from distutils.core import setup setup( name='cardscript', version='0.6', description="A scriptable card game processing engine.", author="Charles Nelson", author_email="[email protected]", url="https://github.com/cnelsonsic/cardscript", packages=['cardscript', 'cardscript.cards'], license='AGPLv3+', long_description=open('README.md').read(), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Games/Entertainment :: Board Games', ], )
from distutils.core import setup from sh import pandoc setup( name='cardscript', version='0.6', description="A scriptable card game processing engine.", author="Charles Nelson", author_email="[email protected]", url="https://github.com/cnelsonsic/cardscript", packages=['cardscript', 'cardscript.cards'], license='AGPLv3+', long_description='\n'.join(pandoc('README.md', t='rst')), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Games/Entertainment :: Board Games', ], )
Use pandoc to convert the markdown readme to rst.
Use pandoc to convert the markdown readme to rst.
Python
agpl-3.0
cnelsonsic/cardscript
python
## Code Before: from distutils.core import setup setup( name='cardscript', version='0.6', description="A scriptable card game processing engine.", author="Charles Nelson", author_email="[email protected]", url="https://github.com/cnelsonsic/cardscript", packages=['cardscript', 'cardscript.cards'], license='AGPLv3+', long_description=open('README.md').read(), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Games/Entertainment :: Board Games', ], ) ## Instruction: Use pandoc to convert the markdown readme to rst. ## Code After: from distutils.core import setup from sh import pandoc setup( name='cardscript', version='0.6', description="A scriptable card game processing engine.", author="Charles Nelson", author_email="[email protected]", url="https://github.com/cnelsonsic/cardscript", packages=['cardscript', 'cardscript.cards'], license='AGPLv3+', long_description='\n'.join(pandoc('README.md', t='rst')), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Intended Audience :: End Users/Desktop', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Games/Entertainment :: Board Games', ], )
// ... existing code ... from distutils.core import setup from sh import pandoc setup( name='cardscript', // ... modified code ... url="https://github.com/cnelsonsic/cardscript", packages=['cardscript', 'cardscript.cards'], license='AGPLv3+', long_description='\n'.join(pandoc('README.md', t='rst')), classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', // ... rest of the code ...
0f4208dd6088a6a96a0145045b11cf2d152db30d
src/samples/pillow.py
src/samples/pillow.py
from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.org/index.html) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.jpg") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv())
from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.io) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.png") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv())
Update link in the comment and change saved image format to .png
Update link in the comment and change saved image format to .png
Python
lgpl-2.1
libavg/libavg,libavg/libavg,libavg/libavg,libavg/libavg
python
## Code Before: from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.org/index.html) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.jpg") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv()) ## Instruction: Update link in the comment and change saved image format to .png ## Code After: from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.io) class MyMainDiv(app.MainDiv): def onInit(self): self.toggleTouchVisualization() srcbmp = avg.Bitmap("rgb24-64x64.png") pixels = srcbmp.getPixels(False) image = Image.frombytes("RGBA", (64,64), pixels) # Need to swap red and blue. b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.png") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) node = avg.ImageNode(parent=self) node.setBitmap(destbmp) def onExit(self): pass def onFrame(self): pass app.App().run(MyMainDiv())
# ... existing code ... from libavg import app, avg from PIL import Image # Demonstrates interoperability with pillow (https://pillow.readthedocs.io) class MyMainDiv(app.MainDiv): def onInit(self): # ... modified code ... b,g,r,a = image.split() image = Image.merge("RGBA", (r,g,b,a)) image.save("foo.png") destbmp = avg.Bitmap((64,64), avg.B8G8R8A8, "") destbmp.setPixels(image.tobytes()) # ... rest of the code ...
2c74cc83f2060cf0ea6198a955fbbe2f07e2dd05
apps/chats/models.py
apps/chats/models.py
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Chat relationships are nullable; most Quotes likely don't have a related # Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the text found inside this quote. """ return u"{name}: {text_excerpt}".format( name=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) )
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Most Quotes likely don't have a related Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the name of the quote's authoor and text found inside this quote. """ return u"{author}: {text_excerpt}".format( author=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) )
Clean up Quote model code
Clean up Quote model code
Python
mit
tofumatt/quotes,tofumatt/quotes
python
## Code Before: from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Chat relationships are nullable; most Quotes likely don't have a related # Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the text found inside this quote. """ return u"{name}: {text_excerpt}".format( name=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) ) ## Instruction: Clean up Quote model code ## Code After: from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Most Quotes likely don't have a related Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the name of the quote's authoor and text found inside this quote. """ return u"{author}: {text_excerpt}".format( author=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) )
... specific groups. """ # Most Quotes likely don't have a related Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! ... def __unicode__(self): """ Return the name of the quote's authoor and text found inside this quote. """ return u"{author}: {text_excerpt}".format( author=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) ) ...
e4350e625129472d7dbc6b77637bc08c00917670
app/src/main/java/com/permutassep/presentation/utils/ParseUtils.java
app/src/main/java/com/permutassep/presentation/utils/ParseUtils.java
package com.permutassep.presentation.utils; import com.parse.ParseInstallation; /** * By Jorge E. Hernandez (@lalongooo) 2015 */ public class ParseUtils { private static final String PARSE_INSTALLATION_COLUMN_PS_USER = "PSUser"; public static void setUpParseInstallationUser(int userId) { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); if (installation.get(PARSE_INSTALLATION_COLUMN_PS_USER) == null || Integer.valueOf(installation.get(PARSE_INSTALLATION_COLUMN_PS_USER).toString()) != userId) { installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, userId); installation.saveInBackground(); } } public static void clearParseInstallationUser() { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, -1); installation.saveInBackground(); } }
package com.permutassep.presentation.utils; import com.parse.ParseInstallation; /** * By Jorge E. Hernandez (@lalongooo) 2015 */ public class ParseUtils { private static final String PARSE_INSTALLATION_COLUMN_PS_USER = "PSUser"; public static void setUpParseInstallationUser(int userId) { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, userId); installation.saveEventually(); // if (installation.get(PARSE_INSTALLATION_COLUMN_PS_USER) == null // || // Integer.valueOf(installation.get(PARSE_INSTALLATION_COLUMN_PS_USER).toString()) != userId) { // installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, userId); // installation.saveInBackground(); // } } public static void clearParseInstallationUser() { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, -1); installation.saveEventually(); } }
Use saveEventually() instead of saveInBackground()
Use saveEventually() instead of saveInBackground()
Java
mit
lalongooo/permutas-sep-android,lalongooo/permutas-sep
java
## Code Before: package com.permutassep.presentation.utils; import com.parse.ParseInstallation; /** * By Jorge E. Hernandez (@lalongooo) 2015 */ public class ParseUtils { private static final String PARSE_INSTALLATION_COLUMN_PS_USER = "PSUser"; public static void setUpParseInstallationUser(int userId) { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); if (installation.get(PARSE_INSTALLATION_COLUMN_PS_USER) == null || Integer.valueOf(installation.get(PARSE_INSTALLATION_COLUMN_PS_USER).toString()) != userId) { installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, userId); installation.saveInBackground(); } } public static void clearParseInstallationUser() { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, -1); installation.saveInBackground(); } } ## Instruction: Use saveEventually() instead of saveInBackground() ## Code After: package com.permutassep.presentation.utils; import com.parse.ParseInstallation; /** * By Jorge E. Hernandez (@lalongooo) 2015 */ public class ParseUtils { private static final String PARSE_INSTALLATION_COLUMN_PS_USER = "PSUser"; public static void setUpParseInstallationUser(int userId) { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, userId); installation.saveEventually(); // if (installation.get(PARSE_INSTALLATION_COLUMN_PS_USER) == null // || // Integer.valueOf(installation.get(PARSE_INSTALLATION_COLUMN_PS_USER).toString()) != userId) { // installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, userId); // installation.saveInBackground(); // } } public static void clearParseInstallationUser() { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, -1); installation.saveEventually(); } }
... public static void setUpParseInstallationUser(int userId) { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, userId); installation.saveEventually(); // if (installation.get(PARSE_INSTALLATION_COLUMN_PS_USER) == null // || // Integer.valueOf(installation.get(PARSE_INSTALLATION_COLUMN_PS_USER).toString()) != userId) { // installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, userId); // installation.saveInBackground(); // } } public static void clearParseInstallationUser() { ParseInstallation installation = ParseInstallation.getCurrentInstallation(); installation.put(PARSE_INSTALLATION_COLUMN_PS_USER, -1); installation.saveEventually(); } } ...
a3158fdee28b8c869fb24dafc9f953b0c25abc97
src/main/java/Client.java
src/main/java/Client.java
import dto.LiveNode; import java.util.List; public class Client { public static void main(String[] args) { String ips = "109.231.122.0-100";//"109.231.122.54"; CommandExecutor commandExecutor = new CommandExecutor(); String nmapOutput = commandExecutor.execute("nmap --open " + ips + " -p 50070 -oX -"); XmlToJsonConverter converter = new XmlToJsonConverter(); PotentialNameNodeDiscoverer pnd = new PotentialNameNodeDiscoverer(); String jsonString = converter.process(nmapOutput); List<String> potentialNameNodes = pnd.getPotentialNameNodes(jsonString); for (String ip : potentialNameNodes) { String url = "http://" + ip + ":50070/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo"; HdfsNodeExtractor hdfsNodeExtractor = new HdfsNodeExtractor(url); List<LiveNode> liveDataNodes = hdfsNodeExtractor.getLiveDataNodes(); //hdfsNodeExtractor.prettyPrint(); System.out.print(liveDataNodes); } //"nmap --open 109.231.122.240 109.231.122.54 -p 50070" } }
import dto.LiveNode; import java.util.List; public class Client { public static void main(String[] args) { StringBuilder ipList = new StringBuilder(); for (String arg : args) { ipList.append(arg + " "); } String ips = ipList.toString().trim(); CommandExecutor commandExecutor = new CommandExecutor(); String nmapOutput = commandExecutor.execute("nmap --open " + ips + " -p 50070 -oX -"); XmlToJsonConverter converter = new XmlToJsonConverter(); PotentialNameNodeDiscoverer pnd = new PotentialNameNodeDiscoverer(); String jsonString = converter.process(nmapOutput); List<String> potentialNameNodes = pnd.getPotentialNameNodes(jsonString); for (String ip : potentialNameNodes) { String url = "http://" + ip + ":50070/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo"; HdfsNodeExtractor hdfsNodeExtractor = new HdfsNodeExtractor(url); List<LiveNode> liveDataNodes = hdfsNodeExtractor.getLiveDataNodes(); //hdfsNodeExtractor.prettyPrint(); System.out.print(liveDataNodes); } } }
Use program arguments to specify ip and ip ranges.
Use program arguments to specify ip and ip ranges.
Java
apache-2.0
IrimieBogdan/HadoopNodeDiscovery
java
## Code Before: import dto.LiveNode; import java.util.List; public class Client { public static void main(String[] args) { String ips = "109.231.122.0-100";//"109.231.122.54"; CommandExecutor commandExecutor = new CommandExecutor(); String nmapOutput = commandExecutor.execute("nmap --open " + ips + " -p 50070 -oX -"); XmlToJsonConverter converter = new XmlToJsonConverter(); PotentialNameNodeDiscoverer pnd = new PotentialNameNodeDiscoverer(); String jsonString = converter.process(nmapOutput); List<String> potentialNameNodes = pnd.getPotentialNameNodes(jsonString); for (String ip : potentialNameNodes) { String url = "http://" + ip + ":50070/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo"; HdfsNodeExtractor hdfsNodeExtractor = new HdfsNodeExtractor(url); List<LiveNode> liveDataNodes = hdfsNodeExtractor.getLiveDataNodes(); //hdfsNodeExtractor.prettyPrint(); System.out.print(liveDataNodes); } //"nmap --open 109.231.122.240 109.231.122.54 -p 50070" } } ## Instruction: Use program arguments to specify ip and ip ranges. ## Code After: import dto.LiveNode; import java.util.List; public class Client { public static void main(String[] args) { StringBuilder ipList = new StringBuilder(); for (String arg : args) { ipList.append(arg + " "); } String ips = ipList.toString().trim(); CommandExecutor commandExecutor = new CommandExecutor(); String nmapOutput = commandExecutor.execute("nmap --open " + ips + " -p 50070 -oX -"); XmlToJsonConverter converter = new XmlToJsonConverter(); PotentialNameNodeDiscoverer pnd = new PotentialNameNodeDiscoverer(); String jsonString = converter.process(nmapOutput); List<String> potentialNameNodes = pnd.getPotentialNameNodes(jsonString); for (String ip : potentialNameNodes) { String url = "http://" + ip + ":50070/jmx?qry=Hadoop:service=NameNode,name=NameNodeInfo"; HdfsNodeExtractor hdfsNodeExtractor = new HdfsNodeExtractor(url); List<LiveNode> liveDataNodes = hdfsNodeExtractor.getLiveDataNodes(); //hdfsNodeExtractor.prettyPrint(); System.out.print(liveDataNodes); } } }
... public class Client { public static void main(String[] args) { StringBuilder ipList = new StringBuilder(); for (String arg : args) { ipList.append(arg + " "); } String ips = ipList.toString().trim(); CommandExecutor commandExecutor = new CommandExecutor(); String nmapOutput = commandExecutor.execute("nmap --open " + ips + " -p 50070 -oX -"); ... //hdfsNodeExtractor.prettyPrint(); System.out.print(liveDataNodes); } } } ...
2a34baee8a33c01fcb253cb336144a570c32d5fa
digits/utils/lmdbreader.py
digits/utils/lmdbreader.py
from __future__ import absolute_import import lmdb class DbReader(object): """ Reads a database """ def __init__(self, location): """ Arguments: location -- where is the database """ self._db = lmdb.open( location, map_size=1024**3, # 1MB readonly=True, lock=False) with self._db.begin() as txn: self.total_entries = txn.stat()['entries'] def entries(self): """ Generator returning all entries in the DB """ with self._db.begin() as txn: cursor = txn.cursor() for item in cursor: yield item
from __future__ import absolute_import import lmdb class DbReader(object): """ Reads a database """ def __init__(self, location): """ Arguments: location -- where is the database """ self._db = lmdb.open( location, map_size=1024**3, # 1MB readonly=True, lock=False) with self._db.begin() as txn: self.total_entries = txn.stat()['entries'] self.txn = self._db.begin() def entries(self): """ Generator returning all entries in the DB """ with self._db.begin() as txn: cursor = txn.cursor() for item in cursor: yield item def entry(self, key): """Return single entry""" return self.txn.get(key)
Add API to LmdbReader (used by gan_features.py)
Add API to LmdbReader (used by gan_features.py)
Python
bsd-3-clause
ethantang95/DIGITS-GAN,gheinrich/DIGITS-GAN,ethantang95/DIGITS-GAN,gheinrich/DIGITS-GAN,gheinrich/DIGITS-GAN,gheinrich/DIGITS-GAN,ethantang95/DIGITS-GAN,ethantang95/DIGITS-GAN
python
## Code Before: from __future__ import absolute_import import lmdb class DbReader(object): """ Reads a database """ def __init__(self, location): """ Arguments: location -- where is the database """ self._db = lmdb.open( location, map_size=1024**3, # 1MB readonly=True, lock=False) with self._db.begin() as txn: self.total_entries = txn.stat()['entries'] def entries(self): """ Generator returning all entries in the DB """ with self._db.begin() as txn: cursor = txn.cursor() for item in cursor: yield item ## Instruction: Add API to LmdbReader (used by gan_features.py) ## Code After: from __future__ import absolute_import import lmdb class DbReader(object): """ Reads a database """ def __init__(self, location): """ Arguments: location -- where is the database """ self._db = lmdb.open( location, map_size=1024**3, # 1MB readonly=True, lock=False) with self._db.begin() as txn: self.total_entries = txn.stat()['entries'] self.txn = self._db.begin() def entries(self): """ Generator returning all entries in the DB """ with self._db.begin() as txn: cursor = txn.cursor() for item in cursor: yield item def entry(self, key): """Return single entry""" return self.txn.get(key)
# ... existing code ... with self._db.begin() as txn: self.total_entries = txn.stat()['entries'] self.txn = self._db.begin() def entries(self): """ Generator returning all entries in the DB # ... modified code ... cursor = txn.cursor() for item in cursor: yield item def entry(self, key): """Return single entry""" return self.txn.get(key) # ... rest of the code ...
47088dd1ed69207e6e74af98c1f6a4124493ed0c
forum/forms.py
forum/forms.py
from django.forms import ModelForm,Textarea,TextInput from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ('subject','body') widgets = { 'subject': TextInput(attrs={'autofocus':'autofocus'}), 'body': Textarea( attrs={ 'data-provide':'markdown', 'data-hidden-buttons':'cmdHeading', }), }
from django.forms import ModelForm,Textarea,TextInput from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ('subject','body') widgets = { 'subject': TextInput(attrs={'autofocus':'autofocus'}), 'body': Textarea( attrs={ 'data-provide':'markdown', 'data-hidden-buttons':'cmdHeading', 'data-iconlibrary':'octicons', }), }
Use Octicons in Markdown editor
Use Octicons in Markdown editor
Python
mit
Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters
python
## Code Before: from django.forms import ModelForm,Textarea,TextInput from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ('subject','body') widgets = { 'subject': TextInput(attrs={'autofocus':'autofocus'}), 'body': Textarea( attrs={ 'data-provide':'markdown', 'data-hidden-buttons':'cmdHeading', }), } ## Instruction: Use Octicons in Markdown editor ## Code After: from django.forms import ModelForm,Textarea,TextInput from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ('subject','body') widgets = { 'subject': TextInput(attrs={'autofocus':'autofocus'}), 'body': Textarea( attrs={ 'data-provide':'markdown', 'data-hidden-buttons':'cmdHeading', 'data-iconlibrary':'octicons', }), }
... attrs={ 'data-provide':'markdown', 'data-hidden-buttons':'cmdHeading', 'data-iconlibrary':'octicons', }), } ...
0a5331c36cb469b2af10d87ab375d9bd0c6c3fb8
tests/test_lattice.py
tests/test_lattice.py
import rml.lattice def test_create_lattice(): l = rml.lattice.Lattice() assert(len(l)) == 0
import rml.lattice def test_create_lattice(): l = rml.lattice.Lattice() assert(len(l)) == 0 def test_non_negative_lattice(): l = rml.lattice.Lattice() assert(len(l)) >= 0
Test lattince length for non-negative values
Test lattince length for non-negative values
Python
apache-2.0
willrogers/pml,razvanvasile/RML,willrogers/pml
python
## Code Before: import rml.lattice def test_create_lattice(): l = rml.lattice.Lattice() assert(len(l)) == 0 ## Instruction: Test lattince length for non-negative values ## Code After: import rml.lattice def test_create_lattice(): l = rml.lattice.Lattice() assert(len(l)) == 0 def test_non_negative_lattice(): l = rml.lattice.Lattice() assert(len(l)) >= 0
# ... existing code ... l = rml.lattice.Lattice() assert(len(l)) == 0 def test_non_negative_lattice(): l = rml.lattice.Lattice() assert(len(l)) >= 0 # ... rest of the code ...
9219a70106ce3008e5d4a394bb0d8507d474405b
pylib/mapit/areas/management/commands/utils.py
pylib/mapit/areas/management/commands/utils.py
import sys def save_polygons(lookup): for shape in lookup.values(): m, poly = shape if not poly: continue sys.stdout.write(".") sys.stdout.flush() #g = OGRGeometry(OGRGeomType('MultiPolygon')) m.polygons.all().delete() for p in poly: print p.geom_name if p.geom_name == 'POLYGON': shapes = [ p ] else: shapes = p for g in shapes: m.polygons.create(polygon=g.wkt) #m.polygon = g.wkt #m.save() poly[:] = [] # Clear the polygon's list, so that if it has both an ons_code and unit_id, it's not processed twice print ""
import sys def save_polygons(lookup): for shape in lookup.values(): m, poly = shape if not poly: continue sys.stdout.write(".") sys.stdout.flush() #g = OGRGeometry(OGRGeomType('MultiPolygon')) m.polygons.all().delete() for p in poly: print p.geom_name if p.geom_name == 'POLYGON': shapes = [ p ] else: shapes = p for g in shapes: # XXX Using g.wkt directly when importing Norway KML works fine # with Django 1.1, Postgres 8.3, PostGIS 1.3.3 but fails with # Django 1.2, Postgres 8.4, PostGIS 1.5.1, saying that the # dimensions constraint fails - because it is trying to import # a shape as 3D as the WKT contains " 0" at the end of every # co-ordinate. Removing the altitudes from the KML, and/or # using altitudeMode makes no difference to the WKT here, so # the only easy solution appears to be removing the altitude # directly from the WKT before using it. must_be_two_d = g.wkt.replace(' 0,', ',') m.polygons.create(polygon=must_be_two_d) #m.polygon = g.wkt #m.save() poly[:] = [] # Clear the polygon's list, so that if it has both an ons_code and unit_id, it's not processed twice print ""
Work around KML -> Django import bug.
Work around KML -> Django import bug.
Python
agpl-3.0
chris48s/mapit,chris48s/mapit,opencorato/mapit,chris48s/mapit,opencorato/mapit,New-Bamboo/mapit,Code4SA/mapit,opencorato/mapit,Sinar/mapit,Sinar/mapit,Code4SA/mapit,Code4SA/mapit,New-Bamboo/mapit
python
## Code Before: import sys def save_polygons(lookup): for shape in lookup.values(): m, poly = shape if not poly: continue sys.stdout.write(".") sys.stdout.flush() #g = OGRGeometry(OGRGeomType('MultiPolygon')) m.polygons.all().delete() for p in poly: print p.geom_name if p.geom_name == 'POLYGON': shapes = [ p ] else: shapes = p for g in shapes: m.polygons.create(polygon=g.wkt) #m.polygon = g.wkt #m.save() poly[:] = [] # Clear the polygon's list, so that if it has both an ons_code and unit_id, it's not processed twice print "" ## Instruction: Work around KML -> Django import bug. ## Code After: import sys def save_polygons(lookup): for shape in lookup.values(): m, poly = shape if not poly: continue sys.stdout.write(".") sys.stdout.flush() #g = OGRGeometry(OGRGeomType('MultiPolygon')) m.polygons.all().delete() for p in poly: print p.geom_name if p.geom_name == 'POLYGON': shapes = [ p ] else: shapes = p for g in shapes: # XXX Using g.wkt directly when importing Norway KML works fine # with Django 1.1, Postgres 8.3, PostGIS 1.3.3 but fails with # Django 1.2, Postgres 8.4, PostGIS 1.5.1, saying that the # dimensions constraint fails - because it is trying to import # a shape as 3D as the WKT contains " 0" at the end of every # co-ordinate. Removing the altitudes from the KML, and/or # using altitudeMode makes no difference to the WKT here, so # the only easy solution appears to be removing the altitude # directly from the WKT before using it. must_be_two_d = g.wkt.replace(' 0,', ',') m.polygons.create(polygon=must_be_two_d) #m.polygon = g.wkt #m.save() poly[:] = [] # Clear the polygon's list, so that if it has both an ons_code and unit_id, it's not processed twice print ""
... else: shapes = p for g in shapes: # XXX Using g.wkt directly when importing Norway KML works fine # with Django 1.1, Postgres 8.3, PostGIS 1.3.3 but fails with # Django 1.2, Postgres 8.4, PostGIS 1.5.1, saying that the # dimensions constraint fails - because it is trying to import # a shape as 3D as the WKT contains " 0" at the end of every # co-ordinate. Removing the altitudes from the KML, and/or # using altitudeMode makes no difference to the WKT here, so # the only easy solution appears to be removing the altitude # directly from the WKT before using it. must_be_two_d = g.wkt.replace(' 0,', ',') m.polygons.create(polygon=must_be_two_d) #m.polygon = g.wkt #m.save() poly[:] = [] # Clear the polygon's list, so that if it has both an ons_code and unit_id, it's not processed twice ...
fcff4e1d25abb173870fffdd0a0d1f63aca7fccf
numpy/_array_api/dtypes.py
numpy/_array_api/dtypes.py
from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']
from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64 # Note: This name is changed from .. import bool_ as bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']
Fix the bool name in the array API namespace
Fix the bool name in the array API namespace
Python
bsd-3-clause
mhvk/numpy,pdebuyl/numpy,mhvk/numpy,jakirkham/numpy,seberg/numpy,mattip/numpy,jakirkham/numpy,numpy/numpy,numpy/numpy,endolith/numpy,endolith/numpy,charris/numpy,rgommers/numpy,endolith/numpy,mattip/numpy,charris/numpy,pdebuyl/numpy,rgommers/numpy,simongibbons/numpy,charris/numpy,seberg/numpy,jakirkham/numpy,simongibbons/numpy,anntzer/numpy,charris/numpy,pdebuyl/numpy,mattip/numpy,simongibbons/numpy,numpy/numpy,jakirkham/numpy,mattip/numpy,seberg/numpy,rgommers/numpy,pdebuyl/numpy,jakirkham/numpy,numpy/numpy,anntzer/numpy,endolith/numpy,simongibbons/numpy,anntzer/numpy,simongibbons/numpy,mhvk/numpy,seberg/numpy,mhvk/numpy,anntzer/numpy,mhvk/numpy,rgommers/numpy
python
## Code Before: from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool'] ## Instruction: Fix the bool name in the array API namespace ## Code After: from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64 # Note: This name is changed from .. import bool_ as bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool']
// ... existing code ... from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64 # Note: This name is changed from .. import bool_ as bool __all__ = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'bool'] // ... rest of the code ...
881174144583c0da21ff14a5c310433bd8407263
src/test/java/com/github/onsdigital/perkin/transform/NumberServiceTest.java
src/test/java/com/github/onsdigital/perkin/transform/NumberServiceTest.java
package com.github.onsdigital.perkin.transform; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class NumberServiceTest { private NumberService classUnderTest; @Test public void shouldStartAtCorrectNumber() { //Given classUnderTest = new NumberService("test", 5L, 10L); //When long start = classUnderTest.getNext(); //Then assertThat(start, is(5L)); } @Test public void shouldWrapAroundToStart() { //Given long start = 5L; classUnderTest = new NumberService("test", start, 10L); classUnderTest.reset(); //When / Then for (int i = 0; i < 6; i++) { long sequence = classUnderTest.getNext(); assertThat(sequence, is(start + i)); } //Then long sequence = classUnderTest.getNext(); assertThat(sequence, is(start)); } }
package com.github.onsdigital.perkin.transform; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class NumberServiceTest { private NumberService classUnderTest; @Test public void shouldStartAtCorrectNumber() { //Given classUnderTest = new NumberService("test", 5L, 10L); //When long start = classUnderTest.getNext(); //Then assertThat(start, is(5L)); } @Test public void shouldWrapAroundToStart() { //Given long start = 5L; classUnderTest = new NumberService("test", start, 10L); classUnderTest.reset(); //When / Then for (int i = 0; i < 6; i++) { long sequence = classUnderTest.getNext(); assertThat(sequence, is(start + i)); } //Then long sequence = classUnderTest.getNext(); assertThat(sequence, is(start)); } @Test public void shouldWrapAroundToStartWhenSaved() { //Given long start = 5L; classUnderTest = new NumberService("test", start, 10L); classUnderTest.reset(); //When / Then for (int i = 0; i < 6; i++) { // Re-initialise (and re-load) on every increment: classUnderTest = new NumberService("test", start, 10L); long sequence = classUnderTest.getNext(); assertThat(sequence, is(start + i)); } //Then long sequence = new NumberService("test", start, 10L).getNext(); assertThat(sequence, is(start)); } }
Test for looping a sequence when the value is saved on every increment.
Test for looping a sequence when the value is saved on every increment.
Java
mit
ONSdigital/Perkin,ONSdigital/Perkin,ONSdigital/Perkin
java
## Code Before: package com.github.onsdigital.perkin.transform; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class NumberServiceTest { private NumberService classUnderTest; @Test public void shouldStartAtCorrectNumber() { //Given classUnderTest = new NumberService("test", 5L, 10L); //When long start = classUnderTest.getNext(); //Then assertThat(start, is(5L)); } @Test public void shouldWrapAroundToStart() { //Given long start = 5L; classUnderTest = new NumberService("test", start, 10L); classUnderTest.reset(); //When / Then for (int i = 0; i < 6; i++) { long sequence = classUnderTest.getNext(); assertThat(sequence, is(start + i)); } //Then long sequence = classUnderTest.getNext(); assertThat(sequence, is(start)); } } ## Instruction: Test for looping a sequence when the value is saved on every increment. ## Code After: package com.github.onsdigital.perkin.transform; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class NumberServiceTest { private NumberService classUnderTest; @Test public void shouldStartAtCorrectNumber() { //Given classUnderTest = new NumberService("test", 5L, 10L); //When long start = classUnderTest.getNext(); //Then assertThat(start, is(5L)); } @Test public void shouldWrapAroundToStart() { //Given long start = 5L; classUnderTest = new NumberService("test", start, 10L); classUnderTest.reset(); //When / Then for (int i = 0; i < 6; i++) { long sequence = classUnderTest.getNext(); assertThat(sequence, is(start + i)); } //Then long sequence = classUnderTest.getNext(); assertThat(sequence, is(start)); } @Test public void shouldWrapAroundToStartWhenSaved() { //Given long start = 5L; classUnderTest = new NumberService("test", start, 10L); classUnderTest.reset(); //When / Then for (int i = 0; i < 6; i++) { // Re-initialise (and re-load) on every increment: classUnderTest = new NumberService("test", start, 10L); long sequence = classUnderTest.getNext(); assertThat(sequence, is(start + i)); } //Then long sequence = new NumberService("test", start, 10L).getNext(); assertThat(sequence, is(start)); } }
// ... existing code ... long sequence = classUnderTest.getNext(); assertThat(sequence, is(start)); } @Test public void shouldWrapAroundToStartWhenSaved() { //Given long start = 5L; classUnderTest = new NumberService("test", start, 10L); classUnderTest.reset(); //When / Then for (int i = 0; i < 6; i++) { // Re-initialise (and re-load) on every increment: classUnderTest = new NumberService("test", start, 10L); long sequence = classUnderTest.getNext(); assertThat(sequence, is(start + i)); } //Then long sequence = new NumberService("test", start, 10L).getNext(); assertThat(sequence, is(start)); } } // ... rest of the code ...
717f0c4e6853708e1968c577c72f5fa89152b119
3DSView/src/main/java/eu/livotov/labs/android/d3s/D3SRegexUtils.java
3DSView/src/main/java/eu/livotov/labs/android/d3s/D3SRegexUtils.java
package eu.livotov.labs.android.d3s; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.util.regex.Pattern.CASE_INSENSITIVE; import static java.util.regex.Pattern.DOTALL; import static java.util.regex.Pattern.compile; /** * Utilities to find 3DS values in ACS webpages. */ final class D3SRegexUtils { /** * Pattern to find the value of an attribute named value from an html tag with an attribute named name and a value of PaRes. */ private static final Pattern paresFinder = compile("<input(?=.+?name=\"PaRes\")(?=.+?value=\"(\\S+?)\").+>", DOTALL | CASE_INSENSITIVE); /** * Finds the PaRes in an html page. * * @param html String representation of the html page to search within. * @return PaRes or null if not found */ @Nullable static String findPaRes(@NonNull String html) { if (html.trim().isEmpty()) return null; String paRes = null; Matcher paresMatcher = paresFinder.matcher(html); if (paresMatcher.find()) { paRes = paresMatcher.group(1); } return paRes; } }
package eu.livotov.labs.android.d3s; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.util.regex.Pattern.CASE_INSENSITIVE; import static java.util.regex.Pattern.DOTALL; import static java.util.regex.Pattern.compile; /** * Utilities to find 3DS values in ACS webpages. */ final class D3SRegexUtils { /** * Pattern to find the value of an attribute named value from an html tag with an attribute named name and a value of PaRes. */ private static final Pattern paresFinder = compile("<input(?=.+?name=\"PaRes\")(?=.+?value=\"(\\S+?)\").+>", DOTALL | CASE_INSENSITIVE); /** * Finds the PaRes in an html page. * <p> * Note: If more than one PaRes is found in a page only the first will be returned. * * @param html String representation of the html page to search within. * @return PaRes or null if not found */ @Nullable static String findPaRes(@NonNull String html) { if (html.trim().isEmpty()) return null; String paRes = null; Matcher paresMatcher = paresFinder.matcher(html); if (paresMatcher.find()) { paRes = paresMatcher.group(1); } return paRes; } }
Add additional comment about only matching first value
Add additional comment about only matching first value
Java
apache-2.0
LivotovLabs/3DSView
java
## Code Before: package eu.livotov.labs.android.d3s; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.util.regex.Pattern.CASE_INSENSITIVE; import static java.util.regex.Pattern.DOTALL; import static java.util.regex.Pattern.compile; /** * Utilities to find 3DS values in ACS webpages. */ final class D3SRegexUtils { /** * Pattern to find the value of an attribute named value from an html tag with an attribute named name and a value of PaRes. */ private static final Pattern paresFinder = compile("<input(?=.+?name=\"PaRes\")(?=.+?value=\"(\\S+?)\").+>", DOTALL | CASE_INSENSITIVE); /** * Finds the PaRes in an html page. * * @param html String representation of the html page to search within. * @return PaRes or null if not found */ @Nullable static String findPaRes(@NonNull String html) { if (html.trim().isEmpty()) return null; String paRes = null; Matcher paresMatcher = paresFinder.matcher(html); if (paresMatcher.find()) { paRes = paresMatcher.group(1); } return paRes; } } ## Instruction: Add additional comment about only matching first value ## Code After: package eu.livotov.labs.android.d3s; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.util.regex.Pattern.CASE_INSENSITIVE; import static java.util.regex.Pattern.DOTALL; import static java.util.regex.Pattern.compile; /** * Utilities to find 3DS values in ACS webpages. */ final class D3SRegexUtils { /** * Pattern to find the value of an attribute named value from an html tag with an attribute named name and a value of PaRes. */ private static final Pattern paresFinder = compile("<input(?=.+?name=\"PaRes\")(?=.+?value=\"(\\S+?)\").+>", DOTALL | CASE_INSENSITIVE); /** * Finds the PaRes in an html page. * <p> * Note: If more than one PaRes is found in a page only the first will be returned. * * @param html String representation of the html page to search within. * @return PaRes or null if not found */ @Nullable static String findPaRes(@NonNull String html) { if (html.trim().isEmpty()) return null; String paRes = null; Matcher paresMatcher = paresFinder.matcher(html); if (paresMatcher.find()) { paRes = paresMatcher.group(1); } return paRes; } }
... /** * Finds the PaRes in an html page. * <p> * Note: If more than one PaRes is found in a page only the first will be returned. * * @param html String representation of the html page to search within. * @return PaRes or null if not found ...
cd1c3645d733ab16355fe516bb2e505f87d49ace
backdrop/contrib/evl_upload.py
backdrop/contrib/evl_upload.py
from datetime import datetime import itertools from tests.support.test_helpers import d_tz def ceg_volumes(rows): def ceg_keys(rows): return [ "_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr", "relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent", "agent_automated_dupes", "calls_answered_by_advisor" ] def ceg_rows(rows): for column in itertools.count(3): date = ceg_date(rows, column) if not isinstance(date, datetime): return if date >= d_tz(2012, 4, 1): yield [ date, "month", rows[5][column], rows[6][column], rows[9][column], rows[11][column], rows[12][column], rows[13][column], rows[15][column], rows[17][column] ] def ceg_date(rows, column): try: return rows[3][column] except IndexError: return None yield ceg_keys(rows) for row in ceg_rows(rows): yield row
from datetime import datetime import itertools from tests.support.test_helpers import d_tz def ceg_volumes(rows): def ceg_keys(rows): return [ "_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr", "relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent", "agent_automated_dupes", "calls_answered_by_advisor" ] def ceg_rows(rows): rows = list(rows) for column in itertools.count(3): date = ceg_date(rows, column) if not isinstance(date, datetime): return if date >= d_tz(2012, 4, 1): yield [ date, "month", rows[5][column], rows[6][column], rows[9][column], rows[11][column], rows[12][column], rows[13][column], rows[15][column], rows[17][column] ] def ceg_date(rows, column): try: return rows[3][column] except IndexError: return None yield ceg_keys(rows) for row in ceg_rows(rows): yield row
Convert rows to list in EVL CEG parser
Convert rows to list in EVL CEG parser It needs to access cells directly
Python
mit
alphagov/backdrop,alphagov/backdrop,alphagov/backdrop
python
## Code Before: from datetime import datetime import itertools from tests.support.test_helpers import d_tz def ceg_volumes(rows): def ceg_keys(rows): return [ "_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr", "relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent", "agent_automated_dupes", "calls_answered_by_advisor" ] def ceg_rows(rows): for column in itertools.count(3): date = ceg_date(rows, column) if not isinstance(date, datetime): return if date >= d_tz(2012, 4, 1): yield [ date, "month", rows[5][column], rows[6][column], rows[9][column], rows[11][column], rows[12][column], rows[13][column], rows[15][column], rows[17][column] ] def ceg_date(rows, column): try: return rows[3][column] except IndexError: return None yield ceg_keys(rows) for row in ceg_rows(rows): yield row ## Instruction: Convert rows to list in EVL CEG parser It needs to access cells directly ## Code After: from datetime import datetime import itertools from tests.support.test_helpers import d_tz def ceg_volumes(rows): def ceg_keys(rows): return [ "_timestamp", "timeSpan", "relicensing_web", "relicensing_ivr", "relicensing_agent", "sorn_web", "sorn_ivr", "sorn_agent", "agent_automated_dupes", "calls_answered_by_advisor" ] def ceg_rows(rows): rows = list(rows) for column in itertools.count(3): date = ceg_date(rows, column) if not isinstance(date, datetime): return if date >= d_tz(2012, 4, 1): yield [ date, "month", rows[5][column], rows[6][column], rows[9][column], rows[11][column], rows[12][column], rows[13][column], rows[15][column], rows[17][column] ] def ceg_date(rows, column): try: return rows[3][column] except IndexError: return None yield ceg_keys(rows) for row in ceg_rows(rows): yield row
# ... existing code ... ] def ceg_rows(rows): rows = list(rows) for column in itertools.count(3): date = ceg_date(rows, column) if not isinstance(date, datetime): # ... rest of the code ...
06eb88db740b50342b74f116ab7d2d16aa09f405
plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenDependencyCompletionTest.java
plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenDependencyCompletionTest.java
package org.jetbrains.idea.maven.dom; import java.io.IOException; /** * @author Sergey Evdokimov */ public class MavenDependencyCompletionTest extends MavenDomWithIndicesTestCase { public void testCompletion() throws IOException { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " jun<caret>" + " </dependency>" + "</dependencies>"); assertCompletionVariantsInclude(myProjectPom, "junit:junit"); } }
package org.jetbrains.idea.maven.dom; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.codeInsight.lookup.LookupElement; import java.io.IOException; /** * @author Sergey Evdokimov */ public class MavenDependencyCompletionTest extends MavenDomWithIndicesTestCase { public void testCompletion() throws IOException { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <caret>" + " </dependency>" + "</dependencies>"); assertCompletionVariantsInclude(myProjectPom, "junit:junit"); } public void testInsertDependency() throws IOException { createProjectPom("<groupId>test</groupId>\n" + "<artifactId>project</artifactId>\n" + "<version>1</version>\n" + "<dependencies>\n" + " <dependency>ju<caret></dependency>\n" + "</dependencies>\n"); configTest(myProjectPom); myFixture.complete(CompletionType.SMART); assertContain(myFixture.getLookupElementStrings(), "4.0", "3.8.2"); myFixture.checkResult(createPomXml("<groupId>test</groupId>\n" + "<artifactId>project</artifactId>\n" + "<version>1</version>\n" + "<dependencies>\n" + " <dependency>\n" + " <groupId>junit</groupId>\n" + " <artifactId>junit</artifactId>\n" + " <version><caret></version>\n" + " </dependency>\n" + "</dependencies>\n")); } }
Add test for inserting maven dependency by smart completion
Add test for inserting maven dependency by smart completion
Java
apache-2.0
retomerz/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,petteyg/intellij-community,kool79/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,diorcety/intellij-community,izonder/intellij-community,supersven/intellij-community,slisson/intellij-community,ibinti/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,petteyg/intellij-community,xfournet/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,adedayo/intellij-community,asedunov/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,retomerz/intellij-community,ibinti/intellij-community,kool79/intellij-community,signed/intellij-community,da1z/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,da1z/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,slisson/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,apixandru/intellij-community,fitermay/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,signed/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,izonder/intellij-community,adedayo/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,ryano144/intellij-community,supersven/intellij-community,retomerz/intellij-community,signed/intellij-community,xfournet/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,caot/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,youdonghai/intellij-community,caot/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,semonte/intellij-community,allotria/intellij-community,petteyg/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,supersven/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,holmes/intellij-community,FHannes/intellij-community,supersven/intellij-community,kool79/intellij-community,semonte/intellij-community,allotria/intellij-community,robovm/robovm-studio,retomerz/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,ahb0327/intellij-community,semonte/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,amith01994/intellij-community,samthor/intellij-community,allotria/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,diorcety/intellij-community,hurricup/intellij-community,dslomov/intellij-community,diorcety/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,kdwink/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,samthor/intellij-community,allotria/intellij-community,xfournet/intellij-community,slisson/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,clumsy/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,izonder/intellij-community,dslomov/intellij-community,semonte/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,signed/intellij-community,supersven/intellij-community,apixandru/intellij-community,supersven/intellij-community,orekyuu/intellij-community,signed/intellij-community,TangHao1987/intellij-community,signed/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,amith01994/intellij-community,dslomov/intellij-community,clumsy/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,amith01994/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,fitermay/intellij-community,signed/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,mglukhikh/intellij-community,ryano144/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,retomerz/intellij-community,petteyg/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,vladmm/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,signed/intellij-community,ahb0327/intellij-community,samthor/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,apixandru/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,FHannes/intellij-community,semonte/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,izonder/intellij-community,caot/intellij-community,izonder/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,supersven/intellij-community,vladmm/intellij-community,ibinti/intellij-community,diorcety/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,caot/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,samthor/intellij-community,apixandru/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,kool79/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,fnouama/intellij-community,FHannes/intellij-community,caot/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,kool79/intellij-community,caot/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,semonte/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,supersven/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,signed/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,caot/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,semonte/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,kool79/intellij-community,izonder/intellij-community,wreckJ/intellij-community,samthor/intellij-community,kdwink/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,izonder/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,allotria/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,holmes/intellij-community,Lekanich/intellij-community,da1z/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,kdwink/intellij-community,signed/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,vladmm/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,supersven/intellij-community,fnouama/intellij-community,fnouama/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,petteyg/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,blademainer/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,slisson/intellij-community,robovm/robovm-studio,petteyg/intellij-community,clumsy/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,asedunov/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,ibinti/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,semonte/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,signed/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,ryano144/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,adedayo/intellij-community,blademainer/intellij-community,fitermay/intellij-community,fitermay/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,amith01994/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,signed/intellij-community,samthor/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,holmes/intellij-community,orekyuu/intellij-community,da1z/intellij-community,apixandru/intellij-community,dslomov/intellij-community,slisson/intellij-community,slisson/intellij-community,adedayo/intellij-community,vladmm/intellij-community,slisson/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,slisson/intellij-community,holmes/intellij-community,blademainer/intellij-community,robovm/robovm-studio,da1z/intellij-community,retomerz/intellij-community,caot/intellij-community,fitermay/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,ryano144/intellij-community,slisson/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,samthor/intellij-community,supersven/intellij-community,diorcety/intellij-community,samthor/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,kdwink/intellij-community
java
## Code Before: package org.jetbrains.idea.maven.dom; import java.io.IOException; /** * @author Sergey Evdokimov */ public class MavenDependencyCompletionTest extends MavenDomWithIndicesTestCase { public void testCompletion() throws IOException { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " jun<caret>" + " </dependency>" + "</dependencies>"); assertCompletionVariantsInclude(myProjectPom, "junit:junit"); } } ## Instruction: Add test for inserting maven dependency by smart completion ## Code After: package org.jetbrains.idea.maven.dom; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.codeInsight.lookup.LookupElement; import java.io.IOException; /** * @author Sergey Evdokimov */ public class MavenDependencyCompletionTest extends MavenDomWithIndicesTestCase { public void testCompletion() throws IOException { createProjectPom("<groupId>test</groupId>" + "<artifactId>project</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <caret>" + " </dependency>" + "</dependencies>"); assertCompletionVariantsInclude(myProjectPom, "junit:junit"); } public void testInsertDependency() throws IOException { createProjectPom("<groupId>test</groupId>\n" + "<artifactId>project</artifactId>\n" + "<version>1</version>\n" + "<dependencies>\n" + " <dependency>ju<caret></dependency>\n" + "</dependencies>\n"); configTest(myProjectPom); myFixture.complete(CompletionType.SMART); assertContain(myFixture.getLookupElementStrings(), "4.0", "3.8.2"); myFixture.checkResult(createPomXml("<groupId>test</groupId>\n" + "<artifactId>project</artifactId>\n" + "<version>1</version>\n" + "<dependencies>\n" + " <dependency>\n" + " <groupId>junit</groupId>\n" + " <artifactId>junit</artifactId>\n" + " <version><caret></version>\n" + " </dependency>\n" + "</dependencies>\n")); } }
// ... existing code ... package org.jetbrains.idea.maven.dom; import com.intellij.codeInsight.completion.CompletionType; import com.intellij.codeInsight.lookup.LookupElement; import java.io.IOException; // ... modified code ... "<dependencies>" + " <dependency>" + " <caret>" + " </dependency>" + "</dependencies>"); ... assertCompletionVariantsInclude(myProjectPom, "junit:junit"); } public void testInsertDependency() throws IOException { createProjectPom("<groupId>test</groupId>\n" + "<artifactId>project</artifactId>\n" + "<version>1</version>\n" + "<dependencies>\n" + " <dependency>ju<caret></dependency>\n" + "</dependencies>\n"); configTest(myProjectPom); myFixture.complete(CompletionType.SMART); assertContain(myFixture.getLookupElementStrings(), "4.0", "3.8.2"); myFixture.checkResult(createPomXml("<groupId>test</groupId>\n" + "<artifactId>project</artifactId>\n" + "<version>1</version>\n" + "<dependencies>\n" + " <dependency>\n" + " <groupId>junit</groupId>\n" + " <artifactId>junit</artifactId>\n" + " <version><caret></version>\n" + " </dependency>\n" + "</dependencies>\n")); } } // ... rest of the code ...
279f0b984209f27743791aca9cf3da7941e5d520
zephyr/lib/minify.py
zephyr/lib/minify.py
from django.conf import settings from hashlib import sha1 from os import path from pipeline.compressors import SubProcessCompressor class ClosureSourceMapCompressor(SubProcessCompressor): def compress_js(self, js): # js is the full text of the JavaScript source, and we can't # easily get either the input file names or the output file # name. So we just pick a unique arbitrary name. This is # okay because we can figure out from the source map file # contents which JavaScript files it corresponds to. source_map = path.join(settings.PIPELINE_CLOSURE_SOURCE_MAP_DIR, sha1(js).hexdigest() + '.map') command = '%s --create_source_map %s' % ( settings.PIPELINE_CLOSURE_BINARY, source_map) return self.execute_command(command, js)
from django.conf import settings from hashlib import sha1 from os import path from pipeline.compressors import SubProcessCompressor class ClosureSourceMapCompressor(SubProcessCompressor): def compress_js(self, js): # js is the full text of the JavaScript source, and we can't # easily get either the input file names or the output file # name. So we just pick a unique arbitrary name. This is # okay because we can figure out from the source map file # contents which JavaScript files it corresponds to. # As a hack to make things easier, assume that any large input # corresponds to app.js. This is like 60 times bigger than # any other input file, at present. if len(js) > 100000: source_map_name = 'app.js.map' else: source_map_name = sha1(js).hexdigest() + '.map' source_map = path.join( settings.PIPELINE_CLOSURE_SOURCE_MAP_DIR, source_map_name) command = '%s --create_source_map %s' % ( settings.PIPELINE_CLOSURE_BINARY, source_map) return self.execute_command(command, js)
Make it easier to find the source map for app.js
Make it easier to find the source map for app.js (imported from commit bca27c9838573fb4b74e2d269b253a48702c9e1c)
Python
apache-2.0
gigawhitlocks/zulip,hayderimran7/zulip,dhcrzf/zulip,jackrzhang/zulip,MariaFaBella85/zulip,verma-varsha/zulip,esander91/zulip,jonesgithub/zulip,johnnygaddarr/zulip,hackerkid/zulip,joshisa/zulip,Frouk/zulip,arpitpanwar/zulip,qq1012803704/zulip,dawran6/zulip,RobotCaleb/zulip,wavelets/zulip,qq1012803704/zulip,jerryge/zulip,isht3/zulip,itnihao/zulip,hj3938/zulip,ufosky-server/zulip,yuvipanda/zulip,pradiptad/zulip,adnanh/zulip,xuanhan863/zulip,ahmadassaf/zulip,jimmy54/zulip,MariaFaBella85/zulip,dattatreya303/zulip,timabbott/zulip,he15his/zulip,ryanbackman/zulip,Drooids/zulip,PaulPetring/zulip,yocome/zulip,JanzTam/zulip,karamcnair/zulip,j831/zulip,atomic-labs/zulip,rht/zulip,Cheppers/zulip,sharmaeklavya2/zulip,Vallher/zulip,moria/zulip,paxapy/zulip,wangdeshui/zulip,m1ssou/zulip,dwrpayne/zulip,vikas-parashar/zulip,christi3k/zulip,amyliu345/zulip,andersk/zulip,xuxiao/zulip,moria/zulip,bluesea/zulip,aakash-cr7/zulip,aps-sids/zulip,jerryge/zulip,so0k/zulip,cosmicAsymmetry/zulip,Diptanshu8/zulip,vaidap/zulip,PaulPetring/zulip,developerfm/zulip,blaze225/zulip,vikas-parashar/zulip,Qgap/zulip,kou/zulip,PhilSk/zulip,hj3938/zulip,hafeez3000/zulip,paxapy/zulip,ahmadassaf/zulip,andersk/zulip,KingxBanana/zulip,wangdeshui/zulip,proliming/zulip,ufosky-server/zulip,dwrpayne/zulip,hengqujushi/zulip,susansls/zulip,praveenaki/zulip,gigawhitlocks/zulip,DazWorrall/zulip,huangkebo/zulip,technicalpickles/zulip,thomasboyt/zulip,levixie/zulip,guiquanz/zulip,Qgap/zulip,avastu/zulip,yocome/zulip,guiquanz/zulip,umkay/zulip,saitodisse/zulip,mansilladev/zulip,JanzTam/zulip,Jianchun1/zulip,amanharitsh123/zulip,hj3938/zulip,Frouk/zulip,pradiptad/zulip,zofuthan/zulip,dwrpayne/zulip,xuanhan863/zulip,hackerkid/zulip,cosmicAsymmetry/zulip,huangkebo/zulip,kaiyuanheshang/zulip,hafeez3000/zulip,luyifan/zulip,bitemyapp/zulip,adnanh/zulip,jessedhillon/zulip,praveenaki/zulip,xuanhan863/zulip,noroot/zulip,armooo/zulip,reyha/zulip,sharmaeklavya2/zulip,armooo/zulip,verma-varsha/zulip,Batterfii/zulip,suxinde2009/zulip,KingxBanana/zulip,eastlhu/zulip,willingc/zulip,peguin40/zulip,samatdav/zulip,AZtheAsian/zulip,aakash-cr7/zulip,tbutter/zulip,ryansnowboarder/zulip,johnnygaddarr/zulip,stamhe/zulip,atomic-labs/zulip,guiquanz/zulip,dwrpayne/zulip,codeKonami/zulip,ericzhou2008/zulip,amanharitsh123/zulip,SmartPeople/zulip,stamhe/zulip,dwrpayne/zulip,ikasumiwt/zulip,aps-sids/zulip,amallia/zulip,ufosky-server/zulip,voidException/zulip,eeshangarg/zulip,hayderimran7/zulip,karamcnair/zulip,zacps/zulip,dawran6/zulip,sup95/zulip,yuvipanda/zulip,karamcnair/zulip,ericzhou2008/zulip,dattatreya303/zulip,hafeez3000/zulip,shrikrishnaholla/zulip,joshisa/zulip,mohsenSy/zulip,udxxabp/zulip,swinghu/zulip,jeffcao/zulip,ipernet/zulip,peiwei/zulip,vakila/zulip,esander91/zulip,jainayush975/zulip,stamhe/zulip,amyliu345/zulip,niftynei/zulip,KJin99/zulip,guiquanz/zulip,babbage/zulip,shrikrishnaholla/zulip,saitodisse/zulip,Frouk/zulip,m1ssou/zulip,amallia/zulip,KJin99/zulip,babbage/zulip,codeKonami/zulip,levixie/zulip,he15his/zulip,johnnygaddarr/zulip,he15his/zulip,swinghu/zulip,sonali0901/zulip,akuseru/zulip,ryansnowboarder/zulip,tdr130/zulip,dxq-git/zulip,MariaFaBella85/zulip,j831/zulip,zacps/zulip,zofuthan/zulip,joshisa/zulip,natanovia/zulip,vaidap/zulip,tdr130/zulip,thomasboyt/zulip,deer-hope/zulip,dxq-git/zulip,aliceriot/zulip,noroot/zulip,noroot/zulip,wdaher/zulip,souravbadami/zulip,andersk/zulip,ApsOps/zulip,andersk/zulip,susansls/zulip,PaulPetring/zulip,jainayush975/zulip,KJin99/zulip,peguin40/zulip,glovebx/zulip,sup95/zulip,vaidap/zulip,SmartPeople/zulip,zacps/zulip,EasonYi/zulip,schatt/zulip,zachallaun/zulip,jonesgithub/zulip,synicalsyntax/zulip,zofuthan/zulip,wavelets/zulip,vabs22/zulip,armooo/zulip,AZtheAsian/zulip,jphilipsen05/zulip,eastlhu/zulip,JPJPJPOPOP/zulip,lfranchi/zulip,j831/zulip,aakash-cr7/zulip,zwily/zulip,Suninus/zulip,voidException/zulip,udxxabp/zulip,technicalpickles/zulip,krtkmj/zulip,zorojean/zulip,voidException/zulip,jerryge/zulip,rishig/zulip,arpitpanwar/zulip,hackerkid/zulip,glovebx/zulip,bitemyapp/zulip,so0k/zulip,LeeRisk/zulip,MayB/zulip,bowlofstew/zulip,mansilladev/zulip,KJin99/zulip,alliejones/zulip,reyha/zulip,MayB/zulip,gigawhitlocks/zulip,grave-w-grave/zulip,dnmfarrell/zulip,jeffcao/zulip,lfranchi/zulip,hafeez3000/zulip,Juanvulcano/zulip,dxq-git/zulip,timabbott/zulip,fw1121/zulip,dxq-git/zulip,saitodisse/zulip,jackrzhang/zulip,eeshangarg/zulip,krtkmj/zulip,sharmaeklavya2/zulip,hackerkid/zulip,synicalsyntax/zulip,rht/zulip,bastianh/zulip,mdavid/zulip,tdr130/zulip,dwrpayne/zulip,suxinde2009/zulip,brockwhittaker/zulip,ikasumiwt/zulip,Frouk/zulip,Gabriel0402/zulip,Jianchun1/zulip,arpith/zulip,umkay/zulip,christi3k/zulip,tommyip/zulip,thomasboyt/zulip,dotcool/zulip,ufosky-server/zulip,swinghu/zulip,Qgap/zulip,showell/zulip,LeeRisk/zulip,johnnygaddarr/zulip,pradiptad/zulip,arpitpanwar/zulip,zofuthan/zulip,aakash-cr7/zulip,wangdeshui/zulip,easyfmxu/zulip,zulip/zulip,Galexrt/zulip,yocome/zulip,johnnygaddarr/zulip,sonali0901/zulip,Cheppers/zulip,proliming/zulip,Juanvulcano/zulip,peguin40/zulip,jeffcao/zulip,developerfm/zulip,saitodisse/zulip,itnihao/zulip,arpith/zulip,gkotian/zulip,shrikrishnaholla/zulip,technicalpickles/zulip,tommyip/zulip,rishig/zulip,wavelets/zulip,JanzTam/zulip,bastianh/zulip,punchagan/zulip,developerfm/zulip,Qgap/zulip,schatt/zulip,Suninus/zulip,ashwinirudrappa/zulip,jeffcao/zulip,tommyip/zulip,dhcrzf/zulip,noroot/zulip,tbutter/zulip,praveenaki/zulip,Diptanshu8/zulip,MayB/zulip,paxapy/zulip,bluesea/zulip,suxinde2009/zulip,xuanhan863/zulip,brainwane/zulip,arpitpanwar/zulip,xuxiao/zulip,christi3k/zulip,esander91/zulip,zorojean/zulip,pradiptad/zulip,schatt/zulip,firstblade/zulip,KingxBanana/zulip,tommyip/zulip,JPJPJPOPOP/zulip,zachallaun/zulip,adnanh/zulip,eeshangarg/zulip,developerfm/zulip,nicholasbs/zulip,jerryge/zulip,ahmadassaf/zulip,timabbott/zulip,seapasulli/zulip,zorojean/zulip,ApsOps/zulip,synicalsyntax/zulip,sharmaeklavya2/zulip,wweiradio/zulip,MariaFaBella85/zulip,PaulPetring/zulip,codeKonami/zulip,swinghu/zulip,Gabriel0402/zulip,dattatreya303/zulip,timabbott/zulip,bssrdf/zulip,ipernet/zulip,Galexrt/zulip,Qgap/zulip,peguin40/zulip,jphilipsen05/zulip,jonesgithub/zulip,saitodisse/zulip,jrowan/zulip,yocome/zulip,ashwinirudrappa/zulip,pradiptad/zulip,Batterfii/zulip,eeshangarg/zulip,bssrdf/zulip,eastlhu/zulip,deer-hope/zulip,blaze225/zulip,DazWorrall/zulip,udxxabp/zulip,vakila/zulip,sup95/zulip,souravbadami/zulip,punchagan/zulip,huangkebo/zulip,natanovia/zulip,moria/zulip,joshisa/zulip,vikas-parashar/zulip,thomasboyt/zulip,adnanh/zulip,andersk/zulip,zulip/zulip,nicholasbs/zulip,amallia/zulip,firstblade/zulip,reyha/zulip,themass/zulip,tbutter/zulip,shaunstanislaus/zulip,jeffcao/zulip,shrikrishnaholla/zulip,verma-varsha/zulip,synicalsyntax/zulip,vabs22/zulip,JanzTam/zulip,vikas-parashar/zulip,DazWorrall/zulip,guiquanz/zulip,fw1121/zulip,bluesea/zulip,shaunstanislaus/zulip,sup95/zulip,isht3/zulip,easyfmxu/zulip,krtkmj/zulip,akuseru/zulip,udxxabp/zulip,punchagan/zulip,akuseru/zulip,noroot/zulip,adnanh/zulip,nicholasbs/zulip,easyfmxu/zulip,Diptanshu8/zulip,Jianchun1/zulip,schatt/zulip,jimmy54/zulip,umkay/zulip,showell/zulip,hackerkid/zulip,synicalsyntax/zulip,AZtheAsian/zulip,isht3/zulip,he15his/zulip,jerryge/zulip,xuxiao/zulip,themass/zulip,Frouk/zulip,johnny9/zulip,jackrzhang/zulip,isht3/zulip,bastianh/zulip,calvinleenyc/zulip,zulip/zulip,amanharitsh123/zulip,eastlhu/zulip,lfranchi/zulip,punchagan/zulip,mohsenSy/zulip,fw1121/zulip,blaze225/zulip,itnihao/zulip,ashwinirudrappa/zulip,tdr130/zulip,qq1012803704/zulip,sup95/zulip,jessedhillon/zulip,ericzhou2008/zulip,jonesgithub/zulip,noroot/zulip,gkotian/zulip,glovebx/zulip,LAndreas/zulip,glovebx/zulip,PaulPetring/zulip,alliejones/zulip,rishig/zulip,verma-varsha/zulip,peiwei/zulip,peiwei/zulip,hengqujushi/zulip,seapasulli/zulip,grave-w-grave/zulip,DazWorrall/zulip,kaiyuanheshang/zulip,reyha/zulip,hayderimran7/zulip,gigawhitlocks/zulip,dxq-git/zulip,KingxBanana/zulip,showell/zulip,zorojean/zulip,grave-w-grave/zulip,lfranchi/zulip,mohsenSy/zulip,SmartPeople/zulip,kokoar/zulip,fw1121/zulip,wdaher/zulip,zulip/zulip,mansilladev/zulip,thomasboyt/zulip,wweiradio/zulip,wavelets/zulip,atomic-labs/zulip,jessedhillon/zulip,souravbadami/zulip,hayderimran7/zulip,jainayush975/zulip,thomasboyt/zulip,blaze225/zulip,dxq-git/zulip,punchagan/zulip,dhcrzf/zulip,mdavid/zulip,aliceriot/zulip,bluesea/zulip,aakash-cr7/zulip,dnmfarrell/zulip,Frouk/zulip,jimmy54/zulip,Suninus/zulip,avastu/zulip,shaunstanislaus/zulip,ufosky-server/zulip,alliejones/zulip,Galexrt/zulip,peguin40/zulip,ikasumiwt/zulip,avastu/zulip,ashwinirudrappa/zulip,pradiptad/zulip,JPJPJPOPOP/zulip,moria/zulip,ahmadassaf/zulip,Vallher/zulip,joyhchen/zulip,bastianh/zulip,andersk/zulip,bastianh/zulip,levixie/zulip,kokoar/zulip,kaiyuanheshang/zulip,ryansnowboarder/zulip,Vallher/zulip,brockwhittaker/zulip,yuvipanda/zulip,ashwinirudrappa/zulip,showell/zulip,KJin99/zulip,brainwane/zulip,grave-w-grave/zulip,technicalpickles/zulip,LeeRisk/zulip,zachallaun/zulip,JPJPJPOPOP/zulip,jonesgithub/zulip,RobotCaleb/zulip,LeeRisk/zulip,calvinleenyc/zulip,PaulPetring/zulip,hackerkid/zulip,eeshangarg/zulip,developerfm/zulip,dotcool/zulip,samatdav/zulip,proliming/zulip,aps-sids/zulip,ahmadassaf/zulip,developerfm/zulip,mahim97/zulip,isht3/zulip,johnnygaddarr/zulip,alliejones/zulip,zulip/zulip,littledogboy/zulip,synicalsyntax/zulip,SmartPeople/zulip,aliceriot/zulip,atomic-labs/zulip,zwily/zulip,Diptanshu8/zulip,hengqujushi/zulip,shubhamdhama/zulip,hayderimran7/zulip,bitemyapp/zulip,ipernet/zulip,LeeRisk/zulip,johnny9/zulip,kou/zulip,tiansiyuan/zulip,susansls/zulip,joshisa/zulip,dattatreya303/zulip,Drooids/zulip,kou/zulip,TigorC/zulip,themass/zulip,zorojean/zulip,j831/zulip,nicholasbs/zulip,armooo/zulip,aps-sids/zulip,dnmfarrell/zulip,LAndreas/zulip,tdr130/zulip,shaunstanislaus/zulip,bowlofstew/zulip,alliejones/zulip,brockwhittaker/zulip,qq1012803704/zulip,johnny9/zulip,bluesea/zulip,littledogboy/zulip,zwily/zulip,MariaFaBella85/zulip,voidException/zulip,esander91/zulip,suxinde2009/zulip,eastlhu/zulip,Jianchun1/zulip,Galexrt/zulip,gigawhitlocks/zulip,niftynei/zulip,zulip/zulip,mahim97/zulip,zwily/zulip,zwily/zulip,wdaher/zulip,qq1012803704/zulip,gigawhitlocks/zulip,mahim97/zulip,hj3938/zulip,bowlofstew/zulip,AZtheAsian/zulip,bitemyapp/zulip,kou/zulip,ahmadassaf/zulip,tdr130/zulip,ericzhou2008/zulip,fw1121/zulip,ikasumiwt/zulip,yuvipanda/zulip,he15his/zulip,ryansnowboarder/zulip,PhilSk/zulip,jrowan/zulip,Batterfii/zulip,tdr130/zulip,Drooids/zulip,paxapy/zulip,arpitpanwar/zulip,tiansiyuan/zulip,luyifan/zulip,huangkebo/zulip,reyha/zulip,natanovia/zulip,ericzhou2008/zulip,zacps/zulip,TigorC/zulip,xuanhan863/zulip,mansilladev/zulip,bitemyapp/zulip,vakila/zulip,joshisa/zulip,TigorC/zulip,dotcool/zulip,suxinde2009/zulip,yocome/zulip,aps-sids/zulip,krtkmj/zulip,Batterfii/zulip,wangdeshui/zulip,nicholasbs/zulip,jackrzhang/zulip,gkotian/zulip,MayB/zulip,bowlofstew/zulip,dattatreya303/zulip,nicholasbs/zulip,wavelets/zulip,hustlzp/zulip,jessedhillon/zulip,hj3938/zulip,moria/zulip,avastu/zulip,xuxiao/zulip,Cheppers/zulip,bitemyapp/zulip,willingc/zulip,KJin99/zulip,joyhchen/zulip,firstblade/zulip,zwily/zulip,ikasumiwt/zulip,EasonYi/zulip,zhaoweigg/zulip,amyliu345/zulip,amallia/zulip,susansls/zulip,cosmicAsymmetry/zulip,sonali0901/zulip,jrowan/zulip,voidException/zulip,wangdeshui/zulip,deer-hope/zulip,grave-w-grave/zulip,ikasumiwt/zulip,akuseru/zulip,gigawhitlocks/zulip,arpitpanwar/zulip,jrowan/zulip,jphilipsen05/zulip,tommyip/zulip,zacps/zulip,amallia/zulip,gkotian/zulip,christi3k/zulip,ryanbackman/zulip,shrikrishnaholla/zulip,KJin99/zulip,Jianchun1/zulip,lfranchi/zulip,jainayush975/zulip,jackrzhang/zulip,ipernet/zulip,voidException/zulip,lfranchi/zulip,luyifan/zulip,saitodisse/zulip,hj3938/zulip,yuvipanda/zulip,Suninus/zulip,EasonYi/zulip,brainwane/zulip,aps-sids/zulip,TigorC/zulip,littledogboy/zulip,dhcrzf/zulip,arpith/zulip,ahmadassaf/zulip,developerfm/zulip,stamhe/zulip,glovebx/zulip,bssrdf/zulip,Diptanshu8/zulip,kou/zulip,dotcool/zulip,hengqujushi/zulip,praveenaki/zulip,Qgap/zulip,kokoar/zulip,esander91/zulip,Juanvulcano/zulip,j831/zulip,amyliu345/zulip,firstblade/zulip,fw1121/zulip,firstblade/zulip,krtkmj/zulip,susansls/zulip,amyliu345/zulip,bowlofstew/zulip,luyifan/zulip,levixie/zulip,he15his/zulip,ericzhou2008/zulip,dnmfarrell/zulip,zwily/zulip,brockwhittaker/zulip,willingc/zulip,rht/zulip,babbage/zulip,littledogboy/zulip,arpitpanwar/zulip,timabbott/zulip,suxinde2009/zulip,joyhchen/zulip,xuxiao/zulip,shrikrishnaholla/zulip,umkay/zulip,tiansiyuan/zulip,Qgap/zulip,aps-sids/zulip,yuvipanda/zulip,rht/zulip,schatt/zulip,peiwei/zulip,mdavid/zulip,calvinleenyc/zulip,punchagan/zulip,fw1121/zulip,tommyip/zulip,m1ssou/zulip,gkotian/zulip,gkotian/zulip,suxinde2009/zulip,praveenaki/zulip,ApsOps/zulip,susansls/zulip,stamhe/zulip,LAndreas/zulip,amanharitsh123/zulip,tbutter/zulip,brainwane/zulip,KingxBanana/zulip,so0k/zulip,peiwei/zulip,mohsenSy/zulip,themass/zulip,shaunstanislaus/zulip,adnanh/zulip,itnihao/zulip,esander91/zulip,hengqujushi/zulip,Jianchun1/zulip,EasonYi/zulip,mahim97/zulip,blaze225/zulip,samatdav/zulip,atomic-labs/zulip,umkay/zulip,xuxiao/zulip,dattatreya303/zulip,niftynei/zulip,tiansiyuan/zulip,adnanh/zulip,zorojean/zulip,ApsOps/zulip,akuseru/zulip,proliming/zulip,swinghu/zulip,jrowan/zulip,eastlhu/zulip,mdavid/zulip,Gabriel0402/zulip,hustlzp/zulip,zhaoweigg/zulip,zachallaun/zulip,zofuthan/zulip,guiquanz/zulip,brainwane/zulip,souravbadami/zulip,verma-varsha/zulip,levixie/zulip,PhilSk/zulip,bssrdf/zulip,m1ssou/zulip,calvinleenyc/zulip,kokoar/zulip,ashwinirudrappa/zulip,zhaoweigg/zulip,jimmy54/zulip,vakila/zulip,johnny9/zulip,gkotian/zulip,LeeRisk/zulip,TigorC/zulip,JPJPJPOPOP/zulip,eeshangarg/zulip,wavelets/zulip,bowlofstew/zulip,mahim97/zulip,tiansiyuan/zulip,cosmicAsymmetry/zulip,thomasboyt/zulip,Suninus/zulip,Drooids/zulip,showell/zulip,tiansiyuan/zulip,jessedhillon/zulip,SmartPeople/zulip,LeeRisk/zulip,so0k/zulip,bluesea/zulip,seapasulli/zulip,shubhamdhama/zulip,jonesgithub/zulip,samatdav/zulip,zulip/zulip,sonali0901/zulip,Drooids/zulip,firstblade/zulip,bitemyapp/zulip,samatdav/zulip,cosmicAsymmetry/zulip,rishig/zulip,blaze225/zulip,sharmaeklavya2/zulip,moria/zulip,andersk/zulip,samatdav/zulip,schatt/zulip,eastlhu/zulip,AZtheAsian/zulip,littledogboy/zulip,showell/zulip,dnmfarrell/zulip,zhaoweigg/zulip,RobotCaleb/zulip,PaulPetring/zulip,zorojean/zulip,DazWorrall/zulip,willingc/zulip,timabbott/zulip,Drooids/zulip,RobotCaleb/zulip,glovebx/zulip,hengqujushi/zulip,dawran6/zulip,esander91/zulip,aakash-cr7/zulip,Batterfii/zulip,Vallher/zulip,he15his/zulip,reyha/zulip,saitodisse/zulip,wweiradio/zulip,calvinleenyc/zulip,nicholasbs/zulip,Galexrt/zulip,zhaoweigg/zulip,jainayush975/zulip,dhcrzf/zulip,Gabriel0402/zulip,Galexrt/zulip,ApsOps/zulip,wdaher/zulip,easyfmxu/zulip,zofuthan/zulip,jerryge/zulip,Batterfii/zulip,mansilladev/zulip,willingc/zulip,armooo/zulip,levixie/zulip,RobotCaleb/zulip,jessedhillon/zulip,brockwhittaker/zulip,EasonYi/zulip,stamhe/zulip,guiquanz/zulip,hafeez3000/zulip,atomic-labs/zulip,arpith/zulip,mahim97/zulip,karamcnair/zulip,johnny9/zulip,rht/zulip,LAndreas/zulip,easyfmxu/zulip,synicalsyntax/zulip,zachallaun/zulip,deer-hope/zulip,vaidap/zulip,kaiyuanheshang/zulip,kou/zulip,jimmy54/zulip,moria/zulip,jackrzhang/zulip,johnny9/zulip,peiwei/zulip,vabs22/zulip,Frouk/zulip,mansilladev/zulip,codeKonami/zulip,LAndreas/zulip,jimmy54/zulip,vabs22/zulip,jphilipsen05/zulip,amyliu345/zulip,so0k/zulip,showell/zulip,bssrdf/zulip,ipernet/zulip,ipernet/zulip,m1ssou/zulip,mdavid/zulip,pradiptad/zulip,m1ssou/zulip,swinghu/zulip,amanharitsh123/zulip,yocome/zulip,aliceriot/zulip,aliceriot/zulip,tiansiyuan/zulip,dhcrzf/zulip,amallia/zulip,so0k/zulip,dnmfarrell/zulip,Vallher/zulip,zachallaun/zulip,huangkebo/zulip,qq1012803704/zulip,karamcnair/zulip,hustlzp/zulip,natanovia/zulip,kaiyuanheshang/zulip,xuanhan863/zulip,MariaFaBella85/zulip,ryanbackman/zulip,jrowan/zulip,wweiradio/zulip,amanharitsh123/zulip,peiwei/zulip,mdavid/zulip,Galexrt/zulip,deer-hope/zulip,ufosky-server/zulip,bssrdf/zulip,willingc/zulip,so0k/zulip,easyfmxu/zulip,DazWorrall/zulip,JPJPJPOPOP/zulip,luyifan/zulip,wweiradio/zulip,mdavid/zulip,tommyip/zulip,Suninus/zulip,PhilSk/zulip,Drooids/zulip,vakila/zulip,luyifan/zulip,bastianh/zulip,ApsOps/zulip,rishig/zulip,kaiyuanheshang/zulip,JanzTam/zulip,joyhchen/zulip,Vallher/zulip,Cheppers/zulip,udxxabp/zulip,paxapy/zulip,PhilSk/zulip,christi3k/zulip,rishig/zulip,dhcrzf/zulip,grave-w-grave/zulip,peguin40/zulip,kokoar/zulip,alliejones/zulip,Cheppers/zulip,hafeez3000/zulip,MayB/zulip,avastu/zulip,qq1012803704/zulip,tbutter/zulip,johnnygaddarr/zulip,babbage/zulip,bluesea/zulip,LAndreas/zulip,ikasumiwt/zulip,lfranchi/zulip,shubhamdhama/zulip,niftynei/zulip,seapasulli/zulip,JanzTam/zulip,deer-hope/zulip,itnihao/zulip,glovebx/zulip,Gabriel0402/zulip,JanzTam/zulip,calvinleenyc/zulip,proliming/zulip,KingxBanana/zulip,seapasulli/zulip,noroot/zulip,praveenaki/zulip,timabbott/zulip,j831/zulip,udxxabp/zulip,hustlzp/zulip,hustlzp/zulip,brainwane/zulip,AZtheAsian/zulip,ryanbackman/zulip,zofuthan/zulip,tbutter/zulip,brockwhittaker/zulip,TigorC/zulip,jainayush975/zulip,vikas-parashar/zulip,johnny9/zulip,sup95/zulip,Cheppers/zulip,zhaoweigg/zulip,shubhamdhama/zulip,umkay/zulip,kou/zulip,technicalpickles/zulip,niftynei/zulip,luyifan/zulip,sharmaeklavya2/zulip,EasonYi/zulip,mohsenSy/zulip,MayB/zulip,Juanvulcano/zulip,xuxiao/zulip,ApsOps/zulip,dnmfarrell/zulip,yocome/zulip,vakila/zulip,jerryge/zulip,codeKonami/zulip,xuanhan863/zulip,hustlzp/zulip,ryansnowboarder/zulip,jackrzhang/zulip,littledogboy/zulip,wdaher/zulip,Batterfii/zulip,mohsenSy/zulip,ryansnowboarder/zulip,codeKonami/zulip,Vallher/zulip,vabs22/zulip,mansilladev/zulip,niftynei/zulip,PhilSk/zulip,dotcool/zulip,seapasulli/zulip,levixie/zulip,dotcool/zulip,ipernet/zulip,ryanbackman/zulip,Gabriel0402/zulip,armooo/zulip,Juanvulcano/zulip,wangdeshui/zulip,yuvipanda/zulip,hayderimran7/zulip,praveenaki/zulip,dwrpayne/zulip,shubhamdhama/zulip,Diptanshu8/zulip,proliming/zulip,amallia/zulip,schatt/zulip,shaunstanislaus/zulip,babbage/zulip,jimmy54/zulip,shubhamdhama/zulip,hengqujushi/zulip,armooo/zulip,wweiradio/zulip,kokoar/zulip,zachallaun/zulip,udxxabp/zulip,firstblade/zulip,bastianh/zulip,avastu/zulip,verma-varsha/zulip,codeKonami/zulip,punchagan/zulip,ericzhou2008/zulip,stamhe/zulip,avastu/zulip,dotcool/zulip,natanovia/zulip,easyfmxu/zulip,dxq-git/zulip,itnihao/zulip,alliejones/zulip,ufosky-server/zulip,wdaher/zulip,krtkmj/zulip,vaidap/zulip,natanovia/zulip,joshisa/zulip,jessedhillon/zulip,rht/zulip,akuseru/zulip,hayderimran7/zulip,dawran6/zulip,christi3k/zulip,sonali0901/zulip,souravbadami/zulip,hackerkid/zulip,EasonYi/zulip,zacps/zulip,jeffcao/zulip,dawran6/zulip,eeshangarg/zulip,souravbadami/zulip,rht/zulip,hafeez3000/zulip,LAndreas/zulip,Suninus/zulip,deer-hope/zulip,joyhchen/zulip,wweiradio/zulip,isht3/zulip,zhaoweigg/zulip,vaidap/zulip,tbutter/zulip,SmartPeople/zulip,ryanbackman/zulip,swinghu/zulip,littledogboy/zulip,umkay/zulip,paxapy/zulip,brainwane/zulip,shubhamdhama/zulip,themass/zulip,seapasulli/zulip,shrikrishnaholla/zulip,willingc/zulip,dawran6/zulip,vabs22/zulip,hustlzp/zulip,huangkebo/zulip,karamcnair/zulip,aliceriot/zulip,proliming/zulip,babbage/zulip,Juanvulcano/zulip,themass/zulip,MayB/zulip,shaunstanislaus/zulip,sonali0901/zulip,bssrdf/zulip,joyhchen/zulip,vakila/zulip,akuseru/zulip,vikas-parashar/zulip,jonesgithub/zulip,technicalpickles/zulip,arpith/zulip,Gabriel0402/zulip,wavelets/zulip,themass/zulip,voidException/zulip,jeffcao/zulip,ashwinirudrappa/zulip,cosmicAsymmetry/zulip,karamcnair/zulip,DazWorrall/zulip,jphilipsen05/zulip,hj3938/zulip,RobotCaleb/zulip,MariaFaBella85/zulip,Cheppers/zulip,natanovia/zulip,jphilipsen05/zulip,technicalpickles/zulip,m1ssou/zulip,wangdeshui/zulip,kokoar/zulip,aliceriot/zulip,ryansnowboarder/zulip,kaiyuanheshang/zulip,atomic-labs/zulip,krtkmj/zulip,babbage/zulip,wdaher/zulip,rishig/zulip,itnihao/zulip,bowlofstew/zulip,RobotCaleb/zulip,arpith/zulip,huangkebo/zulip
python
## Code Before: from django.conf import settings from hashlib import sha1 from os import path from pipeline.compressors import SubProcessCompressor class ClosureSourceMapCompressor(SubProcessCompressor): def compress_js(self, js): # js is the full text of the JavaScript source, and we can't # easily get either the input file names or the output file # name. So we just pick a unique arbitrary name. This is # okay because we can figure out from the source map file # contents which JavaScript files it corresponds to. source_map = path.join(settings.PIPELINE_CLOSURE_SOURCE_MAP_DIR, sha1(js).hexdigest() + '.map') command = '%s --create_source_map %s' % ( settings.PIPELINE_CLOSURE_BINARY, source_map) return self.execute_command(command, js) ## Instruction: Make it easier to find the source map for app.js (imported from commit bca27c9838573fb4b74e2d269b253a48702c9e1c) ## Code After: from django.conf import settings from hashlib import sha1 from os import path from pipeline.compressors import SubProcessCompressor class ClosureSourceMapCompressor(SubProcessCompressor): def compress_js(self, js): # js is the full text of the JavaScript source, and we can't # easily get either the input file names or the output file # name. So we just pick a unique arbitrary name. This is # okay because we can figure out from the source map file # contents which JavaScript files it corresponds to. # As a hack to make things easier, assume that any large input # corresponds to app.js. This is like 60 times bigger than # any other input file, at present. if len(js) > 100000: source_map_name = 'app.js.map' else: source_map_name = sha1(js).hexdigest() + '.map' source_map = path.join( settings.PIPELINE_CLOSURE_SOURCE_MAP_DIR, source_map_name) command = '%s --create_source_map %s' % ( settings.PIPELINE_CLOSURE_BINARY, source_map) return self.execute_command(command, js)
# ... existing code ... # name. So we just pick a unique arbitrary name. This is # okay because we can figure out from the source map file # contents which JavaScript files it corresponds to. # As a hack to make things easier, assume that any large input # corresponds to app.js. This is like 60 times bigger than # any other input file, at present. if len(js) > 100000: source_map_name = 'app.js.map' else: source_map_name = sha1(js).hexdigest() + '.map' source_map = path.join( settings.PIPELINE_CLOSURE_SOURCE_MAP_DIR, source_map_name) command = '%s --create_source_map %s' % ( settings.PIPELINE_CLOSURE_BINARY, source_map) # ... rest of the code ...
c2a8e69a5deee8f72c561f50732570801d4fc9ae
tests/test_stack_operations.py
tests/test_stack_operations.py
import pytest from thinglang.execution.errors import UnknownVariable from thinglang.runner import run def test_stack_resolution_in_block(): assert run(""" thing Program does start number i = 0 Output.write("outside before, i =", i) if true Output.write("inside before, i =", i) i = 10 Output.write("inside after, i =", i) Output.write("outside after, i =", i) """).output == """ outside before, i = 0 inside before, i = 0 inside after, i = 10 outside after, i = 10""".strip()
import pytest from thinglang.execution.errors import UnknownVariable from thinglang.runner import run def test_stack_resolution_in_block(): assert run(""" thing Program does start number i = 0 Output.write("outside before, i =", i) if true Output.write("inside before, i =", i) i = 10 Output.write("inside after, i =", i) Output.write("outside after, i =", i) """).output == """ outside before, i = 0 inside before, i = 0 inside after, i = 10 outside after, i = 10""".strip() def test_stack_resolution_error_during_access_after_nested_deceleration(): with pytest.raises(UnknownVariable): run(""" thing Program does start if true number i = 10 Output.write("inside after, i =", i) Output.write("outside after, i =", i) """)
Add test for variables declared inside a scope (and accessed outside)
Add test for variables declared inside a scope (and accessed outside)
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
python
## Code Before: import pytest from thinglang.execution.errors import UnknownVariable from thinglang.runner import run def test_stack_resolution_in_block(): assert run(""" thing Program does start number i = 0 Output.write("outside before, i =", i) if true Output.write("inside before, i =", i) i = 10 Output.write("inside after, i =", i) Output.write("outside after, i =", i) """).output == """ outside before, i = 0 inside before, i = 0 inside after, i = 10 outside after, i = 10""".strip() ## Instruction: Add test for variables declared inside a scope (and accessed outside) ## Code After: import pytest from thinglang.execution.errors import UnknownVariable from thinglang.runner import run def test_stack_resolution_in_block(): assert run(""" thing Program does start number i = 0 Output.write("outside before, i =", i) if true Output.write("inside before, i =", i) i = 10 Output.write("inside after, i =", i) Output.write("outside after, i =", i) """).output == """ outside before, i = 0 inside before, i = 0 inside after, i = 10 outside after, i = 10""".strip() def test_stack_resolution_error_during_access_after_nested_deceleration(): with pytest.raises(UnknownVariable): run(""" thing Program does start if true number i = 10 Output.write("inside after, i =", i) Output.write("outside after, i =", i) """)
# ... existing code ... outside after, i = 10""".strip() def test_stack_resolution_error_during_access_after_nested_deceleration(): with pytest.raises(UnknownVariable): run(""" thing Program does start if true number i = 10 Output.write("inside after, i =", i) Output.write("outside after, i =", i) """) # ... rest of the code ...
0855f9b5a9d36817139e61937419553f6ad21f78
symposion/proposals/urls.py
symposion/proposals/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns("symposion.proposals.views", url(r"^submit/$", "proposal_submit", name="proposal_submit"), url(r"^submit/(\w+)/$", "proposal_submit_kind", name="proposal_submit_kind"), url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"), url(r"^(\d+)/edit/$", "proposal_edit", name="proposal_edit"), url(r"^(\d+)/speakers/$", "proposal_speaker_manage", name="proposal_speaker_manage"), url(r"^(\d+)/cancel/$", "proposal_cancel", name="proposal_cancel"), url(r"^(\d+)/leave/$", "proposal_leave", name="proposal_leave"), url(r"^(\d+)/join/$", "proposal_pending_join", name="proposal_pending_join"), url(r"^(\d+)/decline/$", "proposal_pending_decline", name="proposal_pending_decline"), url(r"^(\d+)/document/create/$", "document_create", name="proposal_document_create"), url(r"^document/(\d+)/delete/$", "document_delete", name="proposal_document_delete"), url(r"^document/(\d+)/([^/]+)$", "document_download", name="proposal_document_download"), )
from django.conf.urls import patterns, url urlpatterns = patterns("symposion.proposals.views", url(r"^submit/$", "proposal_submit", name="proposal_submit"), url(r"^submit/([\w-]+)/$", "proposal_submit_kind", name="proposal_submit_kind"), url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"), url(r"^(\d+)/edit/$", "proposal_edit", name="proposal_edit"), url(r"^(\d+)/speakers/$", "proposal_speaker_manage", name="proposal_speaker_manage"), url(r"^(\d+)/cancel/$", "proposal_cancel", name="proposal_cancel"), url(r"^(\d+)/leave/$", "proposal_leave", name="proposal_leave"), url(r"^(\d+)/join/$", "proposal_pending_join", name="proposal_pending_join"), url(r"^(\d+)/decline/$", "proposal_pending_decline", name="proposal_pending_decline"), url(r"^(\d+)/document/create/$", "document_create", name="proposal_document_create"), url(r"^document/(\d+)/delete/$", "document_delete", name="proposal_document_delete"), url(r"^document/(\d+)/([^/]+)$", "document_download", name="proposal_document_download"), )
Allow dashes in proposal kind slugs
Allow dashes in proposal kind slugs We can see from the setting PROPOSAL_FORMS that at least one proposal kind, Sponsor Tutorial, has a slug with a dash in it: sponsor-tutorial. Yet the URL pattern for submitting a proposal doesn't accept dashes in the slug. Fix it.
Python
bsd-3-clause
njl/pycon,pyconjp/pyconjp-website,njl/pycon,Diwahars/pycon,smellman/sotmjp-website,pyconjp/pyconjp-website,pyconjp/pyconjp-website,PyCon/pycon,osmfj/sotmjp-website,njl/pycon,Diwahars/pycon,PyCon/pycon,pyconjp/pyconjp-website,osmfj/sotmjp-website,osmfj/sotmjp-website,PyCon/pycon,osmfj/sotmjp-website,smellman/sotmjp-website,smellman/sotmjp-website,PyCon/pycon,smellman/sotmjp-website,Diwahars/pycon,Diwahars/pycon,njl/pycon
python
## Code Before: from django.conf.urls.defaults import * urlpatterns = patterns("symposion.proposals.views", url(r"^submit/$", "proposal_submit", name="proposal_submit"), url(r"^submit/(\w+)/$", "proposal_submit_kind", name="proposal_submit_kind"), url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"), url(r"^(\d+)/edit/$", "proposal_edit", name="proposal_edit"), url(r"^(\d+)/speakers/$", "proposal_speaker_manage", name="proposal_speaker_manage"), url(r"^(\d+)/cancel/$", "proposal_cancel", name="proposal_cancel"), url(r"^(\d+)/leave/$", "proposal_leave", name="proposal_leave"), url(r"^(\d+)/join/$", "proposal_pending_join", name="proposal_pending_join"), url(r"^(\d+)/decline/$", "proposal_pending_decline", name="proposal_pending_decline"), url(r"^(\d+)/document/create/$", "document_create", name="proposal_document_create"), url(r"^document/(\d+)/delete/$", "document_delete", name="proposal_document_delete"), url(r"^document/(\d+)/([^/]+)$", "document_download", name="proposal_document_download"), ) ## Instruction: Allow dashes in proposal kind slugs We can see from the setting PROPOSAL_FORMS that at least one proposal kind, Sponsor Tutorial, has a slug with a dash in it: sponsor-tutorial. Yet the URL pattern for submitting a proposal doesn't accept dashes in the slug. Fix it. ## Code After: from django.conf.urls import patterns, url urlpatterns = patterns("symposion.proposals.views", url(r"^submit/$", "proposal_submit", name="proposal_submit"), url(r"^submit/([\w-]+)/$", "proposal_submit_kind", name="proposal_submit_kind"), url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"), url(r"^(\d+)/edit/$", "proposal_edit", name="proposal_edit"), url(r"^(\d+)/speakers/$", "proposal_speaker_manage", name="proposal_speaker_manage"), url(r"^(\d+)/cancel/$", "proposal_cancel", name="proposal_cancel"), url(r"^(\d+)/leave/$", "proposal_leave", name="proposal_leave"), url(r"^(\d+)/join/$", "proposal_pending_join", name="proposal_pending_join"), url(r"^(\d+)/decline/$", "proposal_pending_decline", name="proposal_pending_decline"), url(r"^(\d+)/document/create/$", "document_create", name="proposal_document_create"), url(r"^document/(\d+)/delete/$", "document_delete", name="proposal_document_delete"), url(r"^document/(\d+)/([^/]+)$", "document_download", name="proposal_document_download"), )
... from django.conf.urls import patterns, url urlpatterns = patterns("symposion.proposals.views", url(r"^submit/$", "proposal_submit", name="proposal_submit"), url(r"^submit/([\w-]+)/$", "proposal_submit_kind", name="proposal_submit_kind"), url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"), url(r"^(\d+)/edit/$", "proposal_edit", name="proposal_edit"), url(r"^(\d+)/speakers/$", "proposal_speaker_manage", name="proposal_speaker_manage"), ...
fd87d09b03be003dcd13d778c175f796c4fdf7d6
test_http2_server.py
test_http2_server.py
from echo_client import client def test_ok(): response = client('GET a_web_page.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 200 OK' def test_body(): response = client('GET sample.txt HTTP/1.1').split('\r\n') body = response[4] assert 'This is a very simple text file.' in body def test_directory(): response = client('GET / HTTP/1.1').split('\r\n') body = response[4] assert 'make_time.py' in body def test_404(): response = client('GET does/not/exist.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 404 Not Found'
from echo_client import client def test_ok(): response = client('GET a_web_page.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 200 OK' def test_body(): response = client('GET sample.txt HTTP/1.1').split('\r\n') body = response[4] assert 'This is a very simple text file.' in body def test_directory(): response = client('GET / HTTP/1.1').split('\r\n') body = response[4] assert "<a href='make_time.py'>make_time.py</a>" in body def test_404(): response = client('GET does/not/exist.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 404 Not Found'
Change directory test to look for link, rather than just file name
Change directory test to look for link, rather than just file name
Python
mit
jwarren116/network-tools,jwarren116/network-tools
python
## Code Before: from echo_client import client def test_ok(): response = client('GET a_web_page.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 200 OK' def test_body(): response = client('GET sample.txt HTTP/1.1').split('\r\n') body = response[4] assert 'This is a very simple text file.' in body def test_directory(): response = client('GET / HTTP/1.1').split('\r\n') body = response[4] assert 'make_time.py' in body def test_404(): response = client('GET does/not/exist.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 404 Not Found' ## Instruction: Change directory test to look for link, rather than just file name ## Code After: from echo_client import client def test_ok(): response = client('GET a_web_page.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 200 OK' def test_body(): response = client('GET sample.txt HTTP/1.1').split('\r\n') body = response[4] assert 'This is a very simple text file.' in body def test_directory(): response = client('GET / HTTP/1.1').split('\r\n') body = response[4] assert "<a href='make_time.py'>make_time.py</a>" in body def test_404(): response = client('GET does/not/exist.html HTTP/1.1').split('\r\n') first_line = response[0] assert first_line == 'HTTP/1.1 404 Not Found'
// ... existing code ... def test_directory(): response = client('GET / HTTP/1.1').split('\r\n') body = response[4] assert "<a href='make_time.py'>make_time.py</a>" in body def test_404(): // ... rest of the code ...
04890d8fa647c6e392b33d1a9edfe7bf79d9300d
pm-server/src/main/java/com/pm/server/player/GhostRepositoryImpl.java
pm-server/src/main/java/com/pm/server/player/GhostRepositoryImpl.java
package com.pm.server.player; import java.util.List; import org.springframework.stereotype.Repository; @Repository public class GhostRepositoryImpl implements GhostRepository { private List<Ghost> ghosts; public Ghost getGhostById(Integer id) { for(Ghost ghost : ghosts) { if(ghost.getId() == id) { return ghost; } } return null; } public List<Ghost> getAllGhosts() { return ghosts; } public void addGhost(Ghost ghost) throws Exception { if(getGhostById(ghost.getId()) != null) { ghosts.add(ghost); } else { throw new IllegalArgumentException( "addGhost() was given an id belonging to a ghost which is " + "already in the registry." ); } } }
package com.pm.server.player; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Repository; @Repository public class GhostRepositoryImpl implements GhostRepository { private List<Ghost> ghosts; GhostRepositoryImpl() { ghosts = new ArrayList<Ghost>(); } public Ghost getGhostById(Integer id) { for(Ghost ghost : ghosts) { if(ghost.getId() == id) { return ghost; } } return null; } public List<Ghost> getAllGhosts() { return ghosts; } public void addGhost(Ghost ghost) throws Exception { if(getGhostById(ghost.getId()) != null) { ghosts.add(ghost); } else { throw new IllegalArgumentException( "addGhost() was given an id belonging to a ghost which is " + "already in the registry." ); } } }
Initialize ghost list in GhostRespository
Initialize ghost list in GhostRespository
Java
mit
pacmacro/pm-server,pacmacro/pm-server,pacmacro/pm-server
java
## Code Before: package com.pm.server.player; import java.util.List; import org.springframework.stereotype.Repository; @Repository public class GhostRepositoryImpl implements GhostRepository { private List<Ghost> ghosts; public Ghost getGhostById(Integer id) { for(Ghost ghost : ghosts) { if(ghost.getId() == id) { return ghost; } } return null; } public List<Ghost> getAllGhosts() { return ghosts; } public void addGhost(Ghost ghost) throws Exception { if(getGhostById(ghost.getId()) != null) { ghosts.add(ghost); } else { throw new IllegalArgumentException( "addGhost() was given an id belonging to a ghost which is " + "already in the registry." ); } } } ## Instruction: Initialize ghost list in GhostRespository ## Code After: package com.pm.server.player; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Repository; @Repository public class GhostRepositoryImpl implements GhostRepository { private List<Ghost> ghosts; GhostRepositoryImpl() { ghosts = new ArrayList<Ghost>(); } public Ghost getGhostById(Integer id) { for(Ghost ghost : ghosts) { if(ghost.getId() == id) { return ghost; } } return null; } public List<Ghost> getAllGhosts() { return ghosts; } public void addGhost(Ghost ghost) throws Exception { if(getGhostById(ghost.getId()) != null) { ghosts.add(ghost); } else { throw new IllegalArgumentException( "addGhost() was given an id belonging to a ghost which is " + "already in the registry." ); } } }
// ... existing code ... package com.pm.server.player; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Repository; // ... modified code ... public class GhostRepositoryImpl implements GhostRepository { private List<Ghost> ghosts; GhostRepositoryImpl() { ghosts = new ArrayList<Ghost>(); } public Ghost getGhostById(Integer id) { // ... rest of the code ...
f11528381ba055ebc6042bde4cb35e0dd0512a3c
wandb/integration/sagemaker/resources.py
wandb/integration/sagemaker/resources.py
import json import os import socket from . import files as sm_files def parse_sm_secrets(): """We read our api_key from secrets.env in SageMaker""" env_dict = dict() # Set secret variables if os.path.exists(sm_files.SM_SECRETS): for line in open(sm_files.SM_SECRETS, "r"): key, val = line.strip().split("=", 1) env_dict[key] = val return env_dict def parse_sm_resources(): run_dict = dict() env_dict = dict() run_id = os.getenv("TRAINING_JOB_NAME") if run_id: run_dict["run_id"] = "-".join( [run_id, os.getenv("CURRENT_HOST", socket.gethostname())] ) conf = json.load(open(sm_files.SM_RESOURCE_CONFIG)) if len(conf["hosts"]) > 1: run_dict["run_group"] = os.getenv("TRAINING_JOB_NAME") env_dict = parse_sm_secrets() return run_dict, env_dict
import json import os import socket from . import files as sm_files def parse_sm_secrets(): """We read our api_key from secrets.env in SageMaker""" env_dict = dict() # Set secret variables if os.path.exists(sm_files.SM_SECRETS): for line in open(sm_files.SM_SECRETS, "r"): key, val = line.strip().split("=", 1) env_dict[key] = val return env_dict def parse_sm_resources(): run_dict = dict() env_dict = dict() run_id = os.getenv("TRAINING_JOB_NAME") if run_id and os.getenv("WANDB_RUN_ID") is None: run_dict["run_id"] = "-".join( [run_id, os.getenv("CURRENT_HOST", socket.gethostname())] ) conf = json.load(open(sm_files.SM_RESOURCE_CONFIG)) if len(conf["hosts"]) > 1: run_dict["run_group"] = os.getenv("TRAINING_JOB_NAME") env_dict = parse_sm_secrets() return run_dict, env_dict
Fix issue where sagemaker run ids break run queues
[WB-8591] Fix issue where sagemaker run ids break run queues
Python
mit
wandb/client,wandb/client,wandb/client
python
## Code Before: import json import os import socket from . import files as sm_files def parse_sm_secrets(): """We read our api_key from secrets.env in SageMaker""" env_dict = dict() # Set secret variables if os.path.exists(sm_files.SM_SECRETS): for line in open(sm_files.SM_SECRETS, "r"): key, val = line.strip().split("=", 1) env_dict[key] = val return env_dict def parse_sm_resources(): run_dict = dict() env_dict = dict() run_id = os.getenv("TRAINING_JOB_NAME") if run_id: run_dict["run_id"] = "-".join( [run_id, os.getenv("CURRENT_HOST", socket.gethostname())] ) conf = json.load(open(sm_files.SM_RESOURCE_CONFIG)) if len(conf["hosts"]) > 1: run_dict["run_group"] = os.getenv("TRAINING_JOB_NAME") env_dict = parse_sm_secrets() return run_dict, env_dict ## Instruction: [WB-8591] Fix issue where sagemaker run ids break run queues ## Code After: import json import os import socket from . import files as sm_files def parse_sm_secrets(): """We read our api_key from secrets.env in SageMaker""" env_dict = dict() # Set secret variables if os.path.exists(sm_files.SM_SECRETS): for line in open(sm_files.SM_SECRETS, "r"): key, val = line.strip().split("=", 1) env_dict[key] = val return env_dict def parse_sm_resources(): run_dict = dict() env_dict = dict() run_id = os.getenv("TRAINING_JOB_NAME") if run_id and os.getenv("WANDB_RUN_ID") is None: run_dict["run_id"] = "-".join( [run_id, os.getenv("CURRENT_HOST", socket.gethostname())] ) conf = json.load(open(sm_files.SM_RESOURCE_CONFIG)) if len(conf["hosts"]) > 1: run_dict["run_group"] = os.getenv("TRAINING_JOB_NAME") env_dict = parse_sm_secrets() return run_dict, env_dict
# ... existing code ... run_dict = dict() env_dict = dict() run_id = os.getenv("TRAINING_JOB_NAME") if run_id and os.getenv("WANDB_RUN_ID") is None: run_dict["run_id"] = "-".join( [run_id, os.getenv("CURRENT_HOST", socket.gethostname())] ) # ... rest of the code ...
3fe40e91f70e8256d7c86c46f866e82e3ccf26e2
commandment/profiles/cert.py
commandment/profiles/cert.py
''' Copyright (c) 2015 Jesse Peterson Licensed under the MIT license. See the included LICENSE.txt file for details. ''' from . import Payload import plistlib # needed for Data() wrapper class PEMCertificatePayload(Payload): '''PEM-encoded certificate without private key. May contain root certificates. Payload type of "com.apple.security.pem". Further encodes cert_data as plistlib.Data instance (Base64 data).''' payload_type = 'com.apple.security.pem' def __init__(self, identifier, cert_data, uuid=None, **kwargs): Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs) self.payload['PayloadContent'] = plistlib.Data(cert_data) class PKCS12CertificatePayload(Payload): '''Password-protected identity certificate. Only one certificate may be included. Payload type of "com.apple.security.pkcs12". Include a PKCS#12 (.p12) identity as cert_data. Further encodes cert_data as plistlib.Data instance (Base64 data). Include a password argument for the PKCS#12 identity.''' payload_type = 'com.apple.security.pkcs12' def __init__(self, identifier, cert_data, password=None, uuid=None, **kwargs): Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs) self.payload['PayloadContent'] = plistlib.Data(cert_data) if password: self.payload['Password'] = password
''' Copyright (c) 2015 Jesse Peterson Licensed under the MIT license. See the included LICENSE.txt file for details. ''' from . import Payload import plistlib # needed for Data() wrapper class PEMCertificatePayload(Payload): '''PEM-encoded certificate without private key. May contain root certificates. Payload type of "com.apple.security.pem". Further encodes cert_data as plistlib.Data instance (Base64 data).''' payload_type = 'com.apple.security.pem' def __init__(self, identifier, cert_data, uuid=None, **kwargs): kwargs['PayloadContent'] = plistlib.Data(cert_data) Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs) class PKCS12CertificatePayload(Payload): '''Password-protected identity certificate. Only one certificate may be included. Payload type of "com.apple.security.pkcs12". Include a PKCS#12 (.p12) identity as cert_data. Further encodes cert_data as plistlib.Data instance (Base64 data). Include a password argument for the PKCS#12 identity.''' payload_type = 'com.apple.security.pkcs12' def __init__(self, identifier, cert_data, password=None, uuid=None, **kwargs): kwargs['PayloadContent'] = plistlib.Data(cert_data) if password: kwargs['Password'] = password Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs)
Change style of Payload suclasses to better encapsulate internal structure
Change style of Payload suclasses to better encapsulate internal structure
Python
mit
mosen/commandment,jessepeterson/commandment,mosen/commandment,mosen/commandment,mosen/commandment,jessepeterson/commandment,mosen/commandment
python
## Code Before: ''' Copyright (c) 2015 Jesse Peterson Licensed under the MIT license. See the included LICENSE.txt file for details. ''' from . import Payload import plistlib # needed for Data() wrapper class PEMCertificatePayload(Payload): '''PEM-encoded certificate without private key. May contain root certificates. Payload type of "com.apple.security.pem". Further encodes cert_data as plistlib.Data instance (Base64 data).''' payload_type = 'com.apple.security.pem' def __init__(self, identifier, cert_data, uuid=None, **kwargs): Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs) self.payload['PayloadContent'] = plistlib.Data(cert_data) class PKCS12CertificatePayload(Payload): '''Password-protected identity certificate. Only one certificate may be included. Payload type of "com.apple.security.pkcs12". Include a PKCS#12 (.p12) identity as cert_data. Further encodes cert_data as plistlib.Data instance (Base64 data). Include a password argument for the PKCS#12 identity.''' payload_type = 'com.apple.security.pkcs12' def __init__(self, identifier, cert_data, password=None, uuid=None, **kwargs): Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs) self.payload['PayloadContent'] = plistlib.Data(cert_data) if password: self.payload['Password'] = password ## Instruction: Change style of Payload suclasses to better encapsulate internal structure ## Code After: ''' Copyright (c) 2015 Jesse Peterson Licensed under the MIT license. See the included LICENSE.txt file for details. ''' from . import Payload import plistlib # needed for Data() wrapper class PEMCertificatePayload(Payload): '''PEM-encoded certificate without private key. May contain root certificates. Payload type of "com.apple.security.pem". Further encodes cert_data as plistlib.Data instance (Base64 data).''' payload_type = 'com.apple.security.pem' def __init__(self, identifier, cert_data, uuid=None, **kwargs): kwargs['PayloadContent'] = plistlib.Data(cert_data) Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs) class PKCS12CertificatePayload(Payload): '''Password-protected identity certificate. Only one certificate may be included. Payload type of "com.apple.security.pkcs12". Include a PKCS#12 (.p12) identity as cert_data. Further encodes cert_data as plistlib.Data instance (Base64 data). Include a password argument for the PKCS#12 identity.''' payload_type = 'com.apple.security.pkcs12' def __init__(self, identifier, cert_data, password=None, uuid=None, **kwargs): kwargs['PayloadContent'] = plistlib.Data(cert_data) if password: kwargs['Password'] = password Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs)
... payload_type = 'com.apple.security.pem' def __init__(self, identifier, cert_data, uuid=None, **kwargs): kwargs['PayloadContent'] = plistlib.Data(cert_data) Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs) class PKCS12CertificatePayload(Payload): '''Password-protected identity certificate. Only one certificate may be ... payload_type = 'com.apple.security.pkcs12' def __init__(self, identifier, cert_data, password=None, uuid=None, **kwargs): kwargs['PayloadContent'] = plistlib.Data(cert_data) if password: kwargs['Password'] = password Payload.__init__(self, self.payload_type, identifier, uuid, **kwargs) ...
d16373609b2f30c6ffa576c1269c529f12c9622c
backend/uclapi/timetable/urls.py
backend/uclapi/timetable/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^personal_fast$', views.get_personal_timetable_fast), url(r'^personal$', views.get_personal_timetable), url(r'^bymodule$', views.get_modules_timetable), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^personal$', views.get_personal_timetable_fast), url(r'^bymodule$', views.get_modules_timetable), ]
Switch to fast method for personal timetable
Switch to fast method for personal timetable
Python
mit
uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi
python
## Code Before: from django.conf.urls import url from . import views urlpatterns = [ url(r'^personal_fast$', views.get_personal_timetable_fast), url(r'^personal$', views.get_personal_timetable), url(r'^bymodule$', views.get_modules_timetable), ] ## Instruction: Switch to fast method for personal timetable ## Code After: from django.conf.urls import url from . import views urlpatterns = [ url(r'^personal$', views.get_personal_timetable_fast), url(r'^bymodule$', views.get_modules_timetable), ]
# ... existing code ... from . import views urlpatterns = [ url(r'^personal$', views.get_personal_timetable_fast), url(r'^bymodule$', views.get_modules_timetable), ] # ... rest of the code ...
4dd0931520ce22603f707eb3c5eacba1ac17ca23
service-realization/src/main/java/sg/ncl/service/realization/web/RealizationsController.java
service-realization/src/main/java/sg/ncl/service/realization/web/RealizationsController.java
package sg.ncl.service.realization.web; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import sg.ncl.service.realization.data.jpa.RealizationEntity; import sg.ncl.service.realization.logic.RealizationService; import javax.inject.Inject; /** * @author Christopher Zhong */ @RestController @RequestMapping(path = "/realizations", produces = MediaType.APPLICATION_JSON_VALUE) public class RealizationsController { private final RealizationService realizationService; @Inject protected RealizationsController(final RealizationService realizationService) { this.realizationService = realizationService; } @RequestMapping(method = RequestMethod.GET) public void get() {} @RequestMapping(path = "/start/{experimentId}", method = RequestMethod.PUT) public void startExperiment(@PathVariable Long experimentId) { RealizationEntity realizationEntity = realizationService.getByExperimentId(experimentId); realizationService.startExperimentInDeter(realizationEntity.getTeamId(), realizationEntity.getExperimentName()); } }
package sg.ncl.service.realization.web; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import sg.ncl.service.realization.data.jpa.RealizationEntity; import sg.ncl.service.realization.logic.RealizationService; import javax.inject.Inject; /** * @author Christopher Zhong */ @RestController @RequestMapping(path = "/realizations", produces = MediaType.APPLICATION_JSON_VALUE) public class RealizationsController { private final RealizationService realizationService; @Inject protected RealizationsController(final RealizationService realizationService) { this.realizationService = realizationService; } @RequestMapping(method = RequestMethod.GET) public void get() {} @RequestMapping(path = "/start", method = RequestMethod.PUT) public void startExperiment(final RealizationEntity realizationEntity) { RealizationEntity realizationEntityDb = realizationService.getByExperimentId(realizationEntity.getExperimentId()); if (realizationEntity == null) { realizationService.save(realizationEntity); } realizationService.startExperimentInDeter(realizationEntityDb.getTeamId(), realizationEntityDb.getExperimentName()); } }
Add start method to controller
Add start method to controller
Java
apache-2.0
nus-ncl/services-in-one,nus-ncl/services-in-one
java
## Code Before: package sg.ncl.service.realization.web; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import sg.ncl.service.realization.data.jpa.RealizationEntity; import sg.ncl.service.realization.logic.RealizationService; import javax.inject.Inject; /** * @author Christopher Zhong */ @RestController @RequestMapping(path = "/realizations", produces = MediaType.APPLICATION_JSON_VALUE) public class RealizationsController { private final RealizationService realizationService; @Inject protected RealizationsController(final RealizationService realizationService) { this.realizationService = realizationService; } @RequestMapping(method = RequestMethod.GET) public void get() {} @RequestMapping(path = "/start/{experimentId}", method = RequestMethod.PUT) public void startExperiment(@PathVariable Long experimentId) { RealizationEntity realizationEntity = realizationService.getByExperimentId(experimentId); realizationService.startExperimentInDeter(realizationEntity.getTeamId(), realizationEntity.getExperimentName()); } } ## Instruction: Add start method to controller ## Code After: package sg.ncl.service.realization.web; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import sg.ncl.service.realization.data.jpa.RealizationEntity; import sg.ncl.service.realization.logic.RealizationService; import javax.inject.Inject; /** * @author Christopher Zhong */ @RestController @RequestMapping(path = "/realizations", produces = MediaType.APPLICATION_JSON_VALUE) public class RealizationsController { private final RealizationService realizationService; @Inject protected RealizationsController(final RealizationService realizationService) { this.realizationService = realizationService; } @RequestMapping(method = RequestMethod.GET) public void get() {} @RequestMapping(path = "/start", method = RequestMethod.PUT) public void startExperiment(final RealizationEntity realizationEntity) { RealizationEntity realizationEntityDb = realizationService.getByExperimentId(realizationEntity.getExperimentId()); if (realizationEntity == null) { realizationService.save(realizationEntity); } realizationService.startExperimentInDeter(realizationEntityDb.getTeamId(), realizationEntityDb.getExperimentName()); } }
# ... existing code ... @RequestMapping(method = RequestMethod.GET) public void get() {} @RequestMapping(path = "/start", method = RequestMethod.PUT) public void startExperiment(final RealizationEntity realizationEntity) { RealizationEntity realizationEntityDb = realizationService.getByExperimentId(realizationEntity.getExperimentId()); if (realizationEntity == null) { realizationService.save(realizationEntity); } realizationService.startExperimentInDeter(realizationEntityDb.getTeamId(), realizationEntityDb.getExperimentName()); } } # ... rest of the code ...
f2012869d3e16f0a610e18021e6ec8967eddf635
tests/sqltypes_test.py
tests/sqltypes_test.py
import enum from sqlalchemy.schema import Column from sqlalchemy.types import Integer from cliche.sqltypes import EnumType from cliche.orm import Base class Color(enum.Enum): red = 1 green = 2 blue = 3 class ColorTable(Base): __tablename__ = 'color_table' id = Column(Integer, primary_key=True) test_col = Column(EnumType(Color)) def test_enum_type(fx_session): red_obj = ColorTable(test_col=Color.red) green_obj = ColorTable(test_col=Color.green) blue_obj = ColorTable(test_col=Color.blue) fx_session.add(red_obj) fx_session.add(green_obj) fx_session.add(blue_obj) fx_session.flush() result_obj = fx_session.query(ColorTable) \ .filter(ColorTable.test_col == Color.green) \ .one() assert green_obj is result_obj
import enum from sqlalchemy.schema import Column from sqlalchemy.types import Integer from cliche.sqltypes import EnumType from cliche.orm import Base class Color(enum.Enum): red = 1 green = 2 blue = 3 class ColorTable(Base): __tablename__ = 'color_table' id = Column(Integer, primary_key=True) color = Column(EnumType(Color, name='color')) def test_enum_type(fx_session): red_obj = ColorTable(color=Color.red) green_obj = ColorTable(color=Color.green) blue_obj = ColorTable(color=Color.blue) fx_session.add(red_obj) fx_session.add(green_obj) fx_session.add(blue_obj) fx_session.flush() result_obj = fx_session.query(ColorTable) \ .filter(ColorTable.color == Color.green) \ .one() assert green_obj is result_obj
Add name to EnumType in test since pgsql needs it.
Add name to EnumType in test since pgsql needs it.
Python
mit
item4/cliche,clicheio/cliche,item4/cliche,clicheio/cliche,clicheio/cliche
python
## Code Before: import enum from sqlalchemy.schema import Column from sqlalchemy.types import Integer from cliche.sqltypes import EnumType from cliche.orm import Base class Color(enum.Enum): red = 1 green = 2 blue = 3 class ColorTable(Base): __tablename__ = 'color_table' id = Column(Integer, primary_key=True) test_col = Column(EnumType(Color)) def test_enum_type(fx_session): red_obj = ColorTable(test_col=Color.red) green_obj = ColorTable(test_col=Color.green) blue_obj = ColorTable(test_col=Color.blue) fx_session.add(red_obj) fx_session.add(green_obj) fx_session.add(blue_obj) fx_session.flush() result_obj = fx_session.query(ColorTable) \ .filter(ColorTable.test_col == Color.green) \ .one() assert green_obj is result_obj ## Instruction: Add name to EnumType in test since pgsql needs it. ## Code After: import enum from sqlalchemy.schema import Column from sqlalchemy.types import Integer from cliche.sqltypes import EnumType from cliche.orm import Base class Color(enum.Enum): red = 1 green = 2 blue = 3 class ColorTable(Base): __tablename__ = 'color_table' id = Column(Integer, primary_key=True) color = Column(EnumType(Color, name='color')) def test_enum_type(fx_session): red_obj = ColorTable(color=Color.red) green_obj = ColorTable(color=Color.green) blue_obj = ColorTable(color=Color.blue) fx_session.add(red_obj) fx_session.add(green_obj) fx_session.add(blue_obj) fx_session.flush() result_obj = fx_session.query(ColorTable) \ .filter(ColorTable.color == Color.green) \ .one() assert green_obj is result_obj
... __tablename__ = 'color_table' id = Column(Integer, primary_key=True) color = Column(EnumType(Color, name='color')) def test_enum_type(fx_session): red_obj = ColorTable(color=Color.red) green_obj = ColorTable(color=Color.green) blue_obj = ColorTable(color=Color.blue) fx_session.add(red_obj) fx_session.add(green_obj) fx_session.add(blue_obj) fx_session.flush() result_obj = fx_session.query(ColorTable) \ .filter(ColorTable.color == Color.green) \ .one() assert green_obj is result_obj ...