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
72727bfb04499b60ca8ed91398fbabf0d88fe4cf
include/parrot/string_primitives.h
include/parrot/string_primitives.h
/* string_funcs.h * Copyright (C) 2001-2003, The Perl Foundation. * SVN Info * $Id$ * Overview: * This is the api header for the string subsystem * Data Structure and Algorithms: * History: * Notes: * References: */ #ifndef PARROT_STRING_PRIMITIVES_H_GUARD #define PARROT_STRING_PRIMITIVES_H_GUARD #ifdef PARROT_IN_CORE /* Set the directory where ICU finds its data files (encodings, locales, etc.) */ void string_set_data_directory(const char *dir); /* Convert from any supported encoding, into our internal format */ void string_fill_from_buffer(Interp *interp, const void *buffer, UINTVAL len, const char *encoding_name, STRING *s); /* Utility method which knows how to uwind a single escape sequence */ typedef Parrot_UInt2 (*Parrot_unescape_cb)(Parrot_Int4 offset, void *context); Parrot_UInt4 string_unescape_one(Interp *interp, UINTVAL *offset, STRING *string); UINTVAL Parrot_char_digit_value(Interp *interp, UINTVAL character); #endif /* PARROT_IN_CORE */ #endif /* PARROT_STRING_PRIMITIVES_H_GUARD */ /* * Local variables: * c-file-style: "parrot" * End: * vim: expandtab shiftwidth=4: */
/* string_funcs.h * Copyright (C) 2001-2003, The Perl Foundation. * SVN Info * $Id$ * Overview: * This is the api header for the string subsystem * Data Structure and Algorithms: * History: * Notes: * References: */ #ifndef PARROT_STRING_PRIMITIVES_H_GUARD #define PARROT_STRING_PRIMITIVES_H_GUARD #ifdef PARROT_IN_CORE /* Set the directory where ICU finds its data files (encodings, locales, etc.) */ PARROT_API void string_set_data_directory(const char *dir); /* Convert from any supported encoding, into our internal format */ PARROT_API void string_fill_from_buffer(Interp *interp, const void *buffer, UINTVAL len, const char *encoding_name, STRING *s); /* Utility method which knows how to uwind a single escape sequence */ typedef Parrot_UInt2 (*Parrot_unescape_cb)(Parrot_Int4 offset, void *context); PARROT_API Parrot_UInt4 string_unescape_one(Interp *interp, UINTVAL *offset, STRING *string); PARROT_API UINTVAL Parrot_char_digit_value(Interp *interp, UINTVAL character); #endif /* PARROT_IN_CORE */ #endif /* PARROT_STRING_PRIMITIVES_H_GUARD */ /* * Local variables: * c-file-style: "parrot" * End: * vim: expandtab shiftwidth=4: */
Fix the build on Win32 by making linkage of various symbols consistent again.
Fix the build on Win32 by making linkage of various symbols consistent again. git-svn-id: 6e74a02f85675cec270f5d931b0f6998666294a3@18778 d31e2699-5ff4-0310-a27c-f18f2fbe73fe
C
artistic-2.0
ashgti/parrot,ashgti/parrot,ashgti/parrot,ashgti/parrot,ashgti/parrot,ashgti/parrot,ashgti/parrot
c
## Code Before: /* string_funcs.h * Copyright (C) 2001-2003, The Perl Foundation. * SVN Info * $Id$ * Overview: * This is the api header for the string subsystem * Data Structure and Algorithms: * History: * Notes: * References: */ #ifndef PARROT_STRING_PRIMITIVES_H_GUARD #define PARROT_STRING_PRIMITIVES_H_GUARD #ifdef PARROT_IN_CORE /* Set the directory where ICU finds its data files (encodings, locales, etc.) */ void string_set_data_directory(const char *dir); /* Convert from any supported encoding, into our internal format */ void string_fill_from_buffer(Interp *interp, const void *buffer, UINTVAL len, const char *encoding_name, STRING *s); /* Utility method which knows how to uwind a single escape sequence */ typedef Parrot_UInt2 (*Parrot_unescape_cb)(Parrot_Int4 offset, void *context); Parrot_UInt4 string_unescape_one(Interp *interp, UINTVAL *offset, STRING *string); UINTVAL Parrot_char_digit_value(Interp *interp, UINTVAL character); #endif /* PARROT_IN_CORE */ #endif /* PARROT_STRING_PRIMITIVES_H_GUARD */ /* * Local variables: * c-file-style: "parrot" * End: * vim: expandtab shiftwidth=4: */ ## Instruction: Fix the build on Win32 by making linkage of various symbols consistent again. git-svn-id: 6e74a02f85675cec270f5d931b0f6998666294a3@18778 d31e2699-5ff4-0310-a27c-f18f2fbe73fe ## Code After: /* string_funcs.h * Copyright (C) 2001-2003, The Perl Foundation. * SVN Info * $Id$ * Overview: * This is the api header for the string subsystem * Data Structure and Algorithms: * History: * Notes: * References: */ #ifndef PARROT_STRING_PRIMITIVES_H_GUARD #define PARROT_STRING_PRIMITIVES_H_GUARD #ifdef PARROT_IN_CORE /* Set the directory where ICU finds its data files (encodings, locales, etc.) */ PARROT_API void string_set_data_directory(const char *dir); /* Convert from any supported encoding, into our internal format */ PARROT_API void string_fill_from_buffer(Interp *interp, const void *buffer, UINTVAL len, const char *encoding_name, STRING *s); /* Utility method which knows how to uwind a single escape sequence */ typedef Parrot_UInt2 (*Parrot_unescape_cb)(Parrot_Int4 offset, void *context); PARROT_API Parrot_UInt4 string_unescape_one(Interp *interp, UINTVAL *offset, STRING *string); PARROT_API UINTVAL Parrot_char_digit_value(Interp *interp, UINTVAL character); #endif /* PARROT_IN_CORE */ #endif /* PARROT_STRING_PRIMITIVES_H_GUARD */ /* * Local variables: * c-file-style: "parrot" * End: * vim: expandtab shiftwidth=4: */
# ... existing code ... /* Set the directory where ICU finds its data files (encodings, locales, etc.) */ PARROT_API void string_set_data_directory(const char *dir); /* Convert from any supported encoding, into our internal format */ PARROT_API void string_fill_from_buffer(Interp *interp, const void *buffer, UINTVAL len, const char *encoding_name, STRING *s); /* Utility method which knows how to uwind a single escape sequence */ typedef Parrot_UInt2 (*Parrot_unescape_cb)(Parrot_Int4 offset, void *context); PARROT_API Parrot_UInt4 string_unescape_one(Interp *interp, UINTVAL *offset, STRING *string); PARROT_API UINTVAL Parrot_char_digit_value(Interp *interp, UINTVAL character); #endif /* PARROT_IN_CORE */ # ... rest of the code ...
9ad0dd8a1fac2e03be1fe3b44eb3b198994586ad
setup.py
setup.py
import setuptools setuptools.setup( setup_requires=['pbr>=1.3', 'setuptools>=17.1'], pbr=True)
import setuptools setuptools.setup( setup_requires=['pbr>=1.3', 'setuptools>=17.1'], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', pbr=True)
Add python_requires to help pip
Add python_requires to help pip
Python
bsd-2-clause
testing-cabal/mock
python
## Code Before: import setuptools setuptools.setup( setup_requires=['pbr>=1.3', 'setuptools>=17.1'], pbr=True) ## Instruction: Add python_requires to help pip ## Code After: import setuptools setuptools.setup( setup_requires=['pbr>=1.3', 'setuptools>=17.1'], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', pbr=True)
... setuptools.setup( setup_requires=['pbr>=1.3', 'setuptools>=17.1'], python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', pbr=True) ...
a4c9dd451062b83b907a350ea30f2d36badb6522
parsers/__init__.py
parsers/__init__.py
import importlib parsers = """ singtao.STParser apple.AppleParser """.split() parser_dict = {} # Import the parser and fill in parser_dict: domain -> parser for parser_name in parsers: module, class_name = parser_name.rsplit('.', 1) parser = getattr(importlib.import_module('parsers.' + module), class_name) for domain in parser.domains: parser_dict[domain] = parser def get_parser(url): return parser_dict[url.split('/')[2]] # Each feeder places URLs into the database to be checked periodically. parsers = [parser for parser in parser_dict.values()] __all__ = ['parsers', 'get_parser']
import importlib parsers = """ singtao.STParser apple.AppleParser tvb.TVBParser """.split() parser_dict = {} # Import the parser and fill in parser_dict: domain -> parser for parser_name in parsers: module, class_name = parser_name.rsplit('.', 1) parser = getattr(importlib.import_module('parsers.' + module), class_name) for domain in parser.domains: parser_dict[domain] = parser def get_parser(url): return parser_dict[url.split('/')[2]] # Each feeder places URLs into the database to be checked periodically. parsers = [parser for parser in parser_dict.values()] __all__ = ['parsers', 'get_parser']
Add tvb Parser to the init
Add tvb Parser to the init
Python
mit
code4hk/hk-news-scrapper
python
## Code Before: import importlib parsers = """ singtao.STParser apple.AppleParser """.split() parser_dict = {} # Import the parser and fill in parser_dict: domain -> parser for parser_name in parsers: module, class_name = parser_name.rsplit('.', 1) parser = getattr(importlib.import_module('parsers.' + module), class_name) for domain in parser.domains: parser_dict[domain] = parser def get_parser(url): return parser_dict[url.split('/')[2]] # Each feeder places URLs into the database to be checked periodically. parsers = [parser for parser in parser_dict.values()] __all__ = ['parsers', 'get_parser'] ## Instruction: Add tvb Parser to the init ## Code After: import importlib parsers = """ singtao.STParser apple.AppleParser tvb.TVBParser """.split() parser_dict = {} # Import the parser and fill in parser_dict: domain -> parser for parser_name in parsers: module, class_name = parser_name.rsplit('.', 1) parser = getattr(importlib.import_module('parsers.' + module), class_name) for domain in parser.domains: parser_dict[domain] = parser def get_parser(url): return parser_dict[url.split('/')[2]] # Each feeder places URLs into the database to be checked periodically. parsers = [parser for parser in parser_dict.values()] __all__ = ['parsers', 'get_parser']
... parsers = """ singtao.STParser apple.AppleParser tvb.TVBParser """.split() parser_dict = {} ...
09931cfbba746daf5127b6113187042341e3be3d
tests/conftest.py
tests/conftest.py
import pytest @pytest.fixture def credentials(): """Fake set of MWS credentials""" return { "access_key": "AAAAAAAAAAAAAAAAAAAA", "secret_key": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "account_id": "AAAAAAAAAAAAAA", }
import pytest @pytest.fixture def access_key(): return "AAAAAAAAAAAAAAAAAAAA" @pytest.fixture def secret_key(): return "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" @pytest.fixture def account_id(): return "AAAAAAAAAAAAAA" @pytest.fixture def timestamp(): return '2017-08-12T19:40:35Z' @pytest.fixture def credentials(access_key, secret_key, account_id): """Fake set of MWS credentials""" return { "access_key": access_key, "secret_key": secret_key, "account_id": account_id, }
Add more pytest fixtures (access_key, secret_key, account_id, timestamp)
Add more pytest fixtures (access_key, secret_key, account_id, timestamp)
Python
unlicense
GriceTurrble/python-amazon-mws,Bobspadger/python-amazon-mws
python
## Code Before: import pytest @pytest.fixture def credentials(): """Fake set of MWS credentials""" return { "access_key": "AAAAAAAAAAAAAAAAAAAA", "secret_key": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "account_id": "AAAAAAAAAAAAAA", } ## Instruction: Add more pytest fixtures (access_key, secret_key, account_id, timestamp) ## Code After: import pytest @pytest.fixture def access_key(): return "AAAAAAAAAAAAAAAAAAAA" @pytest.fixture def secret_key(): return "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" @pytest.fixture def account_id(): return "AAAAAAAAAAAAAA" @pytest.fixture def timestamp(): return '2017-08-12T19:40:35Z' @pytest.fixture def credentials(access_key, secret_key, account_id): """Fake set of MWS credentials""" return { "access_key": access_key, "secret_key": secret_key, "account_id": account_id, }
// ... existing code ... @pytest.fixture def access_key(): return "AAAAAAAAAAAAAAAAAAAA" @pytest.fixture def secret_key(): return "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" @pytest.fixture def account_id(): return "AAAAAAAAAAAAAA" @pytest.fixture def timestamp(): return '2017-08-12T19:40:35Z' @pytest.fixture def credentials(access_key, secret_key, account_id): """Fake set of MWS credentials""" return { "access_key": access_key, "secret_key": secret_key, "account_id": account_id, } // ... rest of the code ...
e412a68afe691913525245d2a8a3a8e9e3ba532d
python/xicore.py
python/xicore.py
import sys import struct import json def sendraw(buf): sys.stdout.write(struct.pack("<q", len(buf))) sys.stdout.write(buf) sys.stdout.flush() def send(obj): sendraw(json.dumps(obj)) def mainloop(): text = '' while True: sizebuf = sys.stdin.read(8) if len(sizebuf) == 0: return (size,) = struct.unpack("<q", sizebuf) cmd, arg = json.loads(sys.stdin.read(size)) print >> sys.stderr, cmd, arg if cmd == 'key': chars = arg['chars'] if chars == u'\x7f': if len(text): text = text[:-1] else: text += chars send(['settext', text]) mainloop()
import sys import struct import json def sendraw(buf): sys.stdout.write(struct.pack("<q", len(buf))) sys.stdout.write(buf) sys.stdout.flush() def send(obj): sendraw(json.dumps(obj)) def mainloop(): text = '' while True: sizebuf = sys.stdin.read(8) if len(sizebuf) == 0: return (size,) = struct.unpack("<q", sizebuf) cmd, arg = json.loads(sys.stdin.read(size)) print >> sys.stderr, cmd, arg if cmd == 'key': chars = arg['chars'] if chars == u'\x7f': if len(text): text = text[:-1] else: text += chars send(['settext', text]) mainloop()
Replace tab indentation with 4 spaces
Replace tab indentation with 4 spaces
Python
apache-2.0
google/xi-editor,google/xi-editor,fuchsia-mirror/third_party-xi-editor,modelorganism/xi-editor,modelorganism/xi-editor,fuchsia-mirror/third_party-xi-editor,fuchsia-mirror/third_party-xi-editor,google/xi-editor,google/xi-editor,fuchsia-mirror/third_party-xi-editor,modelorganism/xi-editor
python
## Code Before: import sys import struct import json def sendraw(buf): sys.stdout.write(struct.pack("<q", len(buf))) sys.stdout.write(buf) sys.stdout.flush() def send(obj): sendraw(json.dumps(obj)) def mainloop(): text = '' while True: sizebuf = sys.stdin.read(8) if len(sizebuf) == 0: return (size,) = struct.unpack("<q", sizebuf) cmd, arg = json.loads(sys.stdin.read(size)) print >> sys.stderr, cmd, arg if cmd == 'key': chars = arg['chars'] if chars == u'\x7f': if len(text): text = text[:-1] else: text += chars send(['settext', text]) mainloop() ## Instruction: Replace tab indentation with 4 spaces ## Code After: import sys import struct import json def sendraw(buf): sys.stdout.write(struct.pack("<q", len(buf))) sys.stdout.write(buf) sys.stdout.flush() def send(obj): sendraw(json.dumps(obj)) def mainloop(): text = '' while True: sizebuf = sys.stdin.read(8) if len(sizebuf) == 0: return (size,) = struct.unpack("<q", sizebuf) cmd, arg = json.loads(sys.stdin.read(size)) print >> sys.stderr, cmd, arg if cmd == 'key': chars = arg['chars'] if chars == u'\x7f': if len(text): text = text[:-1] else: text += chars send(['settext', text]) mainloop()
# ... existing code ... import json def sendraw(buf): sys.stdout.write(struct.pack("<q", len(buf))) sys.stdout.write(buf) sys.stdout.flush() def send(obj): sendraw(json.dumps(obj)) # ... rest of the code ...
89d9787fc5aa595f6d93d49565313212c2f95b6b
helper_servers/flask_upload.py
helper_servers/flask_upload.py
from flask import Flask, render_template, request, redirect, url_for from werkzeug.utils import secure_filename import datetime import os def timestamp(): return datetime.datetime.now().strftime('%Y%m%d%H%M%S') app = Flask(__name__) app.config['UPLOAD_FOLDER'] = '/uploads' @app.route('/', methods=['GET']) def index(): return ''' <!doctype html> <title>Hi</title> Hi ''' #curl -F file=@"/tmp/test.txt" https://[site]/[app_path]/ul @app.route('/ul', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': if 'file' not in request.files: return redirect(request.url) file = request.files['file'] if file.filename == '': return redirect(request.url) if file: filename = '{}_{}.data'.format(timestamp(), secure_filename(file.filename)) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('upload_file')) return ''' <!doctype html> <title>Hi</title> Hi '''
from flask import Flask, render_template, request, redirect, url_for from werkzeug.utils import secure_filename import datetime import os def timestamp(): return datetime.datetime.now().strftime('%Y%m%d%H%M%S') app = Flask(__name__) app.config['UPLOAD_FOLDER'] = '/uploads' @app.route('/', methods=['GET']) def index(): return ''' <!doctype html> <title>Hi</title> Hi ''' #curl -F file=@"/tmp/test.txt" https://[site]/[app_path]/ul @app.route('/ul', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': if 'file' not in request.files: return redirect(request.url) file = request.files['file'] if file.filename == '': return redirect(request.url) if file: filename = '{}_{}.data'.format(timestamp(), secure_filename(file.filename)) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('upload_file')) return ''' <!doctype html> <title>Upload</title> <form enctype="multipart/form-data" action="/ul" method="POST"> <input type="file" id="file" name="file"> <input type="submit"> </form> ''' if __name__ == '__main__': app.run(host='0.0.0.0', port=8000)
Add simple form to flask upload server
Add simple form to flask upload server
Python
bsd-3-clause
stephenbradshaw/pentesting_stuff,stephenbradshaw/pentesting_stuff,stephenbradshaw/pentesting_stuff,stephenbradshaw/pentesting_stuff
python
## Code Before: from flask import Flask, render_template, request, redirect, url_for from werkzeug.utils import secure_filename import datetime import os def timestamp(): return datetime.datetime.now().strftime('%Y%m%d%H%M%S') app = Flask(__name__) app.config['UPLOAD_FOLDER'] = '/uploads' @app.route('/', methods=['GET']) def index(): return ''' <!doctype html> <title>Hi</title> Hi ''' #curl -F file=@"/tmp/test.txt" https://[site]/[app_path]/ul @app.route('/ul', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': if 'file' not in request.files: return redirect(request.url) file = request.files['file'] if file.filename == '': return redirect(request.url) if file: filename = '{}_{}.data'.format(timestamp(), secure_filename(file.filename)) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('upload_file')) return ''' <!doctype html> <title>Hi</title> Hi ''' ## Instruction: Add simple form to flask upload server ## Code After: from flask import Flask, render_template, request, redirect, url_for from werkzeug.utils import secure_filename import datetime import os def timestamp(): return datetime.datetime.now().strftime('%Y%m%d%H%M%S') app = Flask(__name__) app.config['UPLOAD_FOLDER'] = '/uploads' @app.route('/', methods=['GET']) def index(): return ''' <!doctype html> <title>Hi</title> Hi ''' #curl -F file=@"/tmp/test.txt" https://[site]/[app_path]/ul @app.route('/ul', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': if 'file' not in request.files: return redirect(request.url) file = request.files['file'] if file.filename == '': return redirect(request.url) if file: filename = '{}_{}.data'.format(timestamp(), secure_filename(file.filename)) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('upload_file')) return ''' <!doctype html> <title>Upload</title> <form enctype="multipart/form-data" action="/ul" method="POST"> <input type="file" id="file" name="file"> <input type="submit"> </form> ''' if __name__ == '__main__': app.run(host='0.0.0.0', port=8000)
... return redirect(url_for('upload_file')) return ''' <!doctype html> <title>Upload</title> <form enctype="multipart/form-data" action="/ul" method="POST"> <input type="file" id="file" name="file"> <input type="submit"> </form> ''' if __name__ == '__main__': app.run(host='0.0.0.0', port=8000) ...
9546faddab321eb508f358883faf45cbc7d48dd8
calexicon/internal/tests/test_julian.py
calexicon/internal/tests/test_julian.py
import unittest from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian class TestJulian(unittest.TestCase): def test_distant_julian_to_gregorian(self): self.assertEqual(distant_julian_to_gregorian(9999, 12, 1), (10000, 2, 12)) def test_julian_to_gregorian(self): self.assertEqual(julian_to_gregorian(1984, 2, 29), (1984, 3, 13))
import unittest from datetime import date as vanilla_date from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian class TestJulian(unittest.TestCase): def test_distant_julian_to_gregorian(self): self.assertEqual(distant_julian_to_gregorian(9999, 12, 1), (10000, 2, 12)) def test_julian_to_gregorian(self): self.assertEqual(julian_to_gregorian(1984, 2, 29), vanilla_date(1984, 3, 13))
Correct test - vanilla_date not tuple.
Correct test - vanilla_date not tuple.
Python
apache-2.0
jwg4/calexicon,jwg4/qual
python
## Code Before: import unittest from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian class TestJulian(unittest.TestCase): def test_distant_julian_to_gregorian(self): self.assertEqual(distant_julian_to_gregorian(9999, 12, 1), (10000, 2, 12)) def test_julian_to_gregorian(self): self.assertEqual(julian_to_gregorian(1984, 2, 29), (1984, 3, 13)) ## Instruction: Correct test - vanilla_date not tuple. ## Code After: import unittest from datetime import date as vanilla_date from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian class TestJulian(unittest.TestCase): def test_distant_julian_to_gregorian(self): self.assertEqual(distant_julian_to_gregorian(9999, 12, 1), (10000, 2, 12)) def test_julian_to_gregorian(self): self.assertEqual(julian_to_gregorian(1984, 2, 29), vanilla_date(1984, 3, 13))
... import unittest from datetime import date as vanilla_date from calexicon.internal.julian import distant_julian_to_gregorian, julian_to_gregorian ... self.assertEqual(distant_julian_to_gregorian(9999, 12, 1), (10000, 2, 12)) def test_julian_to_gregorian(self): self.assertEqual(julian_to_gregorian(1984, 2, 29), vanilla_date(1984, 3, 13)) ...
352b05d7928fe74c9d18956971048d548e0d7b30
method_signatures/src/main/kotlin/org/kethereum/methodsignatures/model/TextMethodSignature.kt
method_signatures/src/main/kotlin/org/kethereum/methodsignatures/model/TextMethodSignature.kt
package org.kethereum.methodsignatures.model data class TextMethodSignature(val signature: String) { val functionName by lazy { signature.substringBefore("(").trim() } val parameters by lazy { signature.substringAfter("(").substringBefore(")").split(",").map { it.trim() } } // see https://solidity.readthedocs.io/en/develop/abi-spec.htm val normalizedParameters by lazy { parameters.map { when (it) { "uint" -> "uint256" "int" -> "int256" "fixed" -> "fixed128x18" "ufixed" -> "ufixed128x18" else -> it } } } private val normalizedParametersString by lazy { normalizedParameters.joinToString(",")} val normalizedSignature by lazy { "$functionName($normalizedParametersString)" } }
package org.kethereum.methodsignatures.model data class TextMethodSignature(val signature: String) { val functionName by lazy { signature.substringBefore("(").trim() } val parameters by lazy { signature.substringAfter("(").substringBefore(")").split(",").map { it.trim() } } // see https://solidity.readthedocs.io/en/develop/abi-spec.htm val normalizedParameters by lazy { parameters.map { when (it) { "uint" -> "uint256" "int" -> "int256" "fixed" -> "fixed128x18" "ufixed" -> "ufixed128x18" "byte" -> "bytes1" else -> it } } } private val normalizedParametersString by lazy { normalizedParameters.joinToString(",")} val normalizedSignature by lazy { "$functionName($normalizedParametersString)" } }
Add mapping from byte to bytes1
Add mapping from byte to bytes1
Kotlin
mit
walleth/kethereum
kotlin
## Code Before: package org.kethereum.methodsignatures.model data class TextMethodSignature(val signature: String) { val functionName by lazy { signature.substringBefore("(").trim() } val parameters by lazy { signature.substringAfter("(").substringBefore(")").split(",").map { it.trim() } } // see https://solidity.readthedocs.io/en/develop/abi-spec.htm val normalizedParameters by lazy { parameters.map { when (it) { "uint" -> "uint256" "int" -> "int256" "fixed" -> "fixed128x18" "ufixed" -> "ufixed128x18" else -> it } } } private val normalizedParametersString by lazy { normalizedParameters.joinToString(",")} val normalizedSignature by lazy { "$functionName($normalizedParametersString)" } } ## Instruction: Add mapping from byte to bytes1 ## Code After: package org.kethereum.methodsignatures.model data class TextMethodSignature(val signature: String) { val functionName by lazy { signature.substringBefore("(").trim() } val parameters by lazy { signature.substringAfter("(").substringBefore(")").split(",").map { it.trim() } } // see https://solidity.readthedocs.io/en/develop/abi-spec.htm val normalizedParameters by lazy { parameters.map { when (it) { "uint" -> "uint256" "int" -> "int256" "fixed" -> "fixed128x18" "ufixed" -> "ufixed128x18" "byte" -> "bytes1" else -> it } } } private val normalizedParametersString by lazy { normalizedParameters.joinToString(",")} val normalizedSignature by lazy { "$functionName($normalizedParametersString)" } }
// ... existing code ... "int" -> "int256" "fixed" -> "fixed128x18" "ufixed" -> "ufixed128x18" "byte" -> "bytes1" else -> it } } // ... rest of the code ...
f6c2f222db0f529d3f5906d5de7a7541e835ea77
litecord/api/guilds.py
litecord/api/guilds.py
''' guilds.py - All handlers under /guilds/* ''' import json import logging from ..utils import _err, _json, strip_user_data log = logging.getLogger(__name__) class GuildsEndpoint: def __init__(self, server): self.server = server async def h_post_guilds(self, request): pass
''' guilds.py - All handlers under /guilds/* ''' import json import logging from ..utils import _err, _json, strip_user_data log = logging.getLogger(__name__) class GuildsEndpoint: def __init__(self, server): self.server = server async def h_post_guilds(self, request): pass async def h_guilds(self, request): ''' GuildsEndpoint.h_guilds Handle `GET /guilds/{guild_id}` ''' _error = await self.server.check_request(request) _error_json = json.loads(_error.text) if _error_json['code'] == 0: return _error guild_id = request.match_info['guild_id'] guild = self.server.guild_man.get_guild(guild_id) if guild is None: return _err('404: Not Found') return _json(guild.as_json) async def h_get_guild_channels(self, request): ''' GuildsEndpoint.h_get_guild_channels `GET /guilds/{guild_id}/channels` ''' _error = await self.server.check_request(request) _error_json = json.loads(_error.text) if _error_json['code'] == 0: return _error guild_id = request.match_info['guild_id'] return _json('Not Implemented')
Add some dummy routes in GuildsEndpoint
Add some dummy routes in GuildsEndpoint
Python
mit
nullpixel/litecord,nullpixel/litecord
python
## Code Before: ''' guilds.py - All handlers under /guilds/* ''' import json import logging from ..utils import _err, _json, strip_user_data log = logging.getLogger(__name__) class GuildsEndpoint: def __init__(self, server): self.server = server async def h_post_guilds(self, request): pass ## Instruction: Add some dummy routes in GuildsEndpoint ## Code After: ''' guilds.py - All handlers under /guilds/* ''' import json import logging from ..utils import _err, _json, strip_user_data log = logging.getLogger(__name__) class GuildsEndpoint: def __init__(self, server): self.server = server async def h_post_guilds(self, request): pass async def h_guilds(self, request): ''' GuildsEndpoint.h_guilds Handle `GET /guilds/{guild_id}` ''' _error = await self.server.check_request(request) _error_json = json.loads(_error.text) if _error_json['code'] == 0: return _error guild_id = request.match_info['guild_id'] guild = self.server.guild_man.get_guild(guild_id) if guild is None: return _err('404: Not Found') return _json(guild.as_json) async def h_get_guild_channels(self, request): ''' GuildsEndpoint.h_get_guild_channels `GET /guilds/{guild_id}/channels` ''' _error = await self.server.check_request(request) _error_json = json.loads(_error.text) if _error_json['code'] == 0: return _error guild_id = request.match_info['guild_id'] return _json('Not Implemented')
# ... existing code ... async def h_post_guilds(self, request): pass async def h_guilds(self, request): ''' GuildsEndpoint.h_guilds Handle `GET /guilds/{guild_id}` ''' _error = await self.server.check_request(request) _error_json = json.loads(_error.text) if _error_json['code'] == 0: return _error guild_id = request.match_info['guild_id'] guild = self.server.guild_man.get_guild(guild_id) if guild is None: return _err('404: Not Found') return _json(guild.as_json) async def h_get_guild_channels(self, request): ''' GuildsEndpoint.h_get_guild_channels `GET /guilds/{guild_id}/channels` ''' _error = await self.server.check_request(request) _error_json = json.loads(_error.text) if _error_json['code'] == 0: return _error guild_id = request.match_info['guild_id'] return _json('Not Implemented') # ... rest of the code ...
d89e43c649aba78ac9722ca39f9e0c67be0cc897
precision/accounts/models.py
precision/accounts/models.py
from django.db import models # Create your models here.
from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ class SchoolAdministrator(AbstractUser): pass
Add an simple abstract user model for school administrators which will be used later
Add an simple abstract user model for school administrators which will be used later
Python
mit
FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management
python
## Code Before: from django.db import models # Create your models here. ## Instruction: Add an simple abstract user model for school administrators which will be used later ## Code After: from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ class SchoolAdministrator(AbstractUser): pass
// ... existing code ... from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ class SchoolAdministrator(AbstractUser): pass // ... rest of the code ...
52e6dabe13abdcd81a097beaacca585800397552
examples/upperair/Wyoming_Request.py
examples/upperair/Wyoming_Request.py
from datetime import datetime from siphon.simplewebservice.wyoming import WyomingUpperAir #################################################### # Create a datetime object for the sounding and string of the station identifier. date = datetime(2017, 9, 10, 6) station = 'MFL' #################################################### # Make the request (a pandas dataframe is returned). df = WyomingUpperAir.request_data(date, station) #################################################### # Inspect data columns in the dataframe. print(df.columns) #################################################### # Pull out a specific column of data. print(df['pressure']) #################################################### # Units are stored in a dictionary with the variable name as the key in the `units` attribute # of the dataframe. print(df.units) #################################################### print(df.units['pressure'])
from datetime import datetime from metpy.units import units from siphon.simplewebservice.wyoming import WyomingUpperAir #################################################### # Create a datetime object for the sounding and string of the station identifier. date = datetime(2017, 9, 10, 6) station = 'MFL' #################################################### # Make the request (a pandas dataframe is returned). df = WyomingUpperAir.request_data(date, station) #################################################### # Inspect data columns in the dataframe. print(df.columns) #################################################### # Pull out a specific column of data. print(df['pressure']) #################################################### # Units are stored in a dictionary with the variable name as the key in the `units` attribute # of the dataframe. print(df.units) #################################################### print(df.units['pressure']) #################################################### # Units can then be attached to the values from the dataframe. pressure = df['pressure'].values * units(df.units['pressure']) temperature = df['temperature'].values * units(df.units['temperature']) dewpoint = df['dewpoint'].values * units(df.units['dewpoint']) u_wind = df['u_wind'].values * units(df.units['u_wind']) v_wind = df['v_wind'].values * units(df.units['v_wind'])
Add attaching units to example.
Add attaching units to example.
Python
bsd-3-clause
Unidata/siphon
python
## Code Before: from datetime import datetime from siphon.simplewebservice.wyoming import WyomingUpperAir #################################################### # Create a datetime object for the sounding and string of the station identifier. date = datetime(2017, 9, 10, 6) station = 'MFL' #################################################### # Make the request (a pandas dataframe is returned). df = WyomingUpperAir.request_data(date, station) #################################################### # Inspect data columns in the dataframe. print(df.columns) #################################################### # Pull out a specific column of data. print(df['pressure']) #################################################### # Units are stored in a dictionary with the variable name as the key in the `units` attribute # of the dataframe. print(df.units) #################################################### print(df.units['pressure']) ## Instruction: Add attaching units to example. ## Code After: from datetime import datetime from metpy.units import units from siphon.simplewebservice.wyoming import WyomingUpperAir #################################################### # Create a datetime object for the sounding and string of the station identifier. date = datetime(2017, 9, 10, 6) station = 'MFL' #################################################### # Make the request (a pandas dataframe is returned). df = WyomingUpperAir.request_data(date, station) #################################################### # Inspect data columns in the dataframe. print(df.columns) #################################################### # Pull out a specific column of data. print(df['pressure']) #################################################### # Units are stored in a dictionary with the variable name as the key in the `units` attribute # of the dataframe. print(df.units) #################################################### print(df.units['pressure']) #################################################### # Units can then be attached to the values from the dataframe. pressure = df['pressure'].values * units(df.units['pressure']) temperature = df['temperature'].values * units(df.units['temperature']) dewpoint = df['dewpoint'].values * units(df.units['dewpoint']) u_wind = df['u_wind'].values * units(df.units['u_wind']) v_wind = df['v_wind'].values * units(df.units['v_wind'])
// ... existing code ... from datetime import datetime from metpy.units import units from siphon.simplewebservice.wyoming import WyomingUpperAir // ... modified code ... #################################################### print(df.units['pressure']) #################################################### # Units can then be attached to the values from the dataframe. pressure = df['pressure'].values * units(df.units['pressure']) temperature = df['temperature'].values * units(df.units['temperature']) dewpoint = df['dewpoint'].values * units(df.units['dewpoint']) u_wind = df['u_wind'].values * units(df.units['u_wind']) v_wind = df['v_wind'].values * units(df.units['v_wind']) // ... rest of the code ...
027ae8b8029d01622e3a9647f3ec6b1fca4c4d9d
chainerrl/wrappers/__init__.py
chainerrl/wrappers/__init__.py
from chainerrl.wrappers.cast_observation import CastObservation # NOQA from chainerrl.wrappers.cast_observation import CastObservationToFloat32 # NOQA from chainerrl.wrappers.randomize_action import RandomizeAction # NOQA from chainerrl.wrappers.scale_reward import ScaleReward # NOQA
from chainerrl.wrappers.cast_observation import CastObservation # NOQA from chainerrl.wrappers.cast_observation import CastObservationToFloat32 # NOQA from chainerrl.wrappers.randomize_action import RandomizeAction # NOQA from chainerrl.wrappers.render import Render # NOQA from chainerrl.wrappers.scale_reward import ScaleReward # NOQA
Make Render available under chainerrl.wrappers
Make Render available under chainerrl.wrappers
Python
mit
toslunar/chainerrl,toslunar/chainerrl
python
## Code Before: from chainerrl.wrappers.cast_observation import CastObservation # NOQA from chainerrl.wrappers.cast_observation import CastObservationToFloat32 # NOQA from chainerrl.wrappers.randomize_action import RandomizeAction # NOQA from chainerrl.wrappers.scale_reward import ScaleReward # NOQA ## Instruction: Make Render available under chainerrl.wrappers ## Code After: from chainerrl.wrappers.cast_observation import CastObservation # NOQA from chainerrl.wrappers.cast_observation import CastObservationToFloat32 # NOQA from chainerrl.wrappers.randomize_action import RandomizeAction # NOQA from chainerrl.wrappers.render import Render # NOQA from chainerrl.wrappers.scale_reward import ScaleReward # NOQA
# ... existing code ... from chainerrl.wrappers.randomize_action import RandomizeAction # NOQA from chainerrl.wrappers.render import Render # NOQA from chainerrl.wrappers.scale_reward import ScaleReward # NOQA # ... rest of the code ...
5da62bbe9df92df58dea742120f4e78555509bd0
lib/log_processor.py
lib/log_processor.py
import re import snmpy class log_processor(snmpy.plugin): def create(self): for k, v in sorted(self.conf['objects'].items()): extra = { 'count': re.compile(v['count']), 'reset': re.compile(v['reset']) if 'reset' in v else None, 'start': int(v['start']) if 'start' in v else 0, 'rotate': bool(v['rotate']) if 'rotate' in v else False } self.data['1.%s' % k] = 'string', v['label'] self.data['2.%s' % k] = 'integer', extra['start'], extra self.tail() @snmpy.plugin.task def tail(self): for line in snmpy.plugin.tail(self.conf['file_name'], True): if line is True: for item in self.data['2.0':]: if self.data[item:'rotate'] and line is True: self.data[item] = self.data[item:'start'] continue for item in self.data['2.0':]: count = self.data[item:'count'].search(line) if count: self.data[item] = self.data[item:True] + (int(count.group(1)) if len(count.groups()) > 0 else 1) break if self.data[item:'reset'] is not None and self.data[item:'reset'].search(line): self.data[item] = self.data[item:'start'] break
import glob import re import snmpy class log_processor(snmpy.plugin): def create(self): for k, v in sorted(self.conf['objects'].items()): extra = { 'count': re.compile(v['count']), 'reset': re.compile(v['reset']) if 'reset' in v else None, 'start': int(v['start']) if 'start' in v else 0, 'rotate': bool(v['rotate']) if 'rotate' in v else False } self.data['1.%s' % k] = 'string', v['label'] self.data['2.%s' % k] = 'integer', extra['start'], extra self.tail() @snmpy.plugin.task def tail(self): for line in snmpy.plugin.tail(glob.glob(self.conf['file_name'])[0], True): if line is True: for item in self.data['2.0':]: if self.data[item:'rotate'] and line is True: self.data[item] = self.data[item:'start'] continue for item in self.data['2.0':]: count = self.data[item:'count'].search(line) if count: self.data[item] = self.data[item:True] + (int(count.group(1)) if len(count.groups()) > 0 else 1) break if self.data[item:'reset'] is not None and self.data[item:'reset'].search(line): self.data[item] = self.data[item:'start'] break
Support file globbing for log processor since names could be dynamic (based on hostname, etc.).
Support file globbing for log processor since names could be dynamic (based on hostname, etc.).
Python
mit
mk23/snmpy,mk23/snmpy
python
## Code Before: import re import snmpy class log_processor(snmpy.plugin): def create(self): for k, v in sorted(self.conf['objects'].items()): extra = { 'count': re.compile(v['count']), 'reset': re.compile(v['reset']) if 'reset' in v else None, 'start': int(v['start']) if 'start' in v else 0, 'rotate': bool(v['rotate']) if 'rotate' in v else False } self.data['1.%s' % k] = 'string', v['label'] self.data['2.%s' % k] = 'integer', extra['start'], extra self.tail() @snmpy.plugin.task def tail(self): for line in snmpy.plugin.tail(self.conf['file_name'], True): if line is True: for item in self.data['2.0':]: if self.data[item:'rotate'] and line is True: self.data[item] = self.data[item:'start'] continue for item in self.data['2.0':]: count = self.data[item:'count'].search(line) if count: self.data[item] = self.data[item:True] + (int(count.group(1)) if len(count.groups()) > 0 else 1) break if self.data[item:'reset'] is not None and self.data[item:'reset'].search(line): self.data[item] = self.data[item:'start'] break ## Instruction: Support file globbing for log processor since names could be dynamic (based on hostname, etc.). ## Code After: import glob import re import snmpy class log_processor(snmpy.plugin): def create(self): for k, v in sorted(self.conf['objects'].items()): extra = { 'count': re.compile(v['count']), 'reset': re.compile(v['reset']) if 'reset' in v else None, 'start': int(v['start']) if 'start' in v else 0, 'rotate': bool(v['rotate']) if 'rotate' in v else False } self.data['1.%s' % k] = 'string', v['label'] self.data['2.%s' % k] = 'integer', extra['start'], extra self.tail() @snmpy.plugin.task def tail(self): for line in snmpy.plugin.tail(glob.glob(self.conf['file_name'])[0], True): if line is True: for item in self.data['2.0':]: if self.data[item:'rotate'] and line is True: self.data[item] = self.data[item:'start'] continue for item in self.data['2.0':]: count = self.data[item:'count'].search(line) if count: self.data[item] = self.data[item:True] + (int(count.group(1)) if len(count.groups()) > 0 else 1) break if self.data[item:'reset'] is not None and self.data[item:'reset'].search(line): self.data[item] = self.data[item:'start'] break
// ... existing code ... import glob import re import snmpy // ... modified code ... @snmpy.plugin.task def tail(self): for line in snmpy.plugin.tail(glob.glob(self.conf['file_name'])[0], True): if line is True: for item in self.data['2.0':]: if self.data[item:'rotate'] and line is True: // ... rest of the code ...
0292a9d160588c87ebc52815764c888081ae06ce
WaniKani/src/tr/xip/wanikani/managers/PrefManager.java
WaniKani/src/tr/xip/wanikani/managers/PrefManager.java
package tr.xip.wanikani.managers; import android.content.Context; import android.content.SharedPreferences; import android.os.Environment; import android.preference.PreferenceManager; /** * Created by xihsa_000 on 3/11/14. */ public class PrefManager { private static SharedPreferences prefs; private static SharedPreferences.Editor prefeditor; private static Context context; public PrefManager(Context mContext) { context = mContext; prefs = context.getSharedPreferences("prefs", 0); prefeditor = prefs.edit(); } public String getApiKey() { return prefs.getString("api_key", "0"); } public boolean isFirstLaunch() { return prefs.getBoolean("first_launch", true); } public void setFirstLaunch(boolean value) { prefeditor.putBoolean("first_launch", value).commit(); } public void setApiKey(String key) { prefeditor.putString("api_key", key).commit(); } public boolean isProfileFirstTime() { return prefs.getBoolean("first_time_profile", true); } public void setProfileFirstTime(boolean value) { prefeditor.putBoolean("first_time_profile", value).commit(); } public void logout() { prefeditor.clear().commit(); } }
package tr.xip.wanikani.managers; import android.content.Context; import android.content.SharedPreferences; import android.os.Environment; import android.preference.PreferenceManager; /** * Created by xihsa_000 on 3/11/14. */ public class PrefManager { private static SharedPreferences prefs; private static SharedPreferences offlineData; private static SharedPreferences.Editor prefeditor; private static SharedPreferences.Editor offlineDataEditor; private static Context context; public PrefManager(Context mContext) { context = mContext; prefs = context.getSharedPreferences("prefs", 0); offlineData = context.getSharedPreferences("offline_data", 0); prefeditor = prefs.edit(); offlineDataEditor = offlineData.edit(); } public String getApiKey() { return prefs.getString("api_key", "0"); } public boolean isFirstLaunch() { return prefs.getBoolean("first_launch", true); } public void setFirstLaunch(boolean value) { prefeditor.putBoolean("first_launch", value).commit(); } public void setApiKey(String key) { prefeditor.putString("api_key", key).commit(); } public boolean isProfileFirstTime() { return prefs.getBoolean("first_time_profile", true); } public void setProfileFirstTime(boolean value) { prefeditor.putBoolean("first_time_profile", value).commit(); } public void logout() { prefeditor.clear().commit(); offlineDataEditor.clear().commit(); } }
Clear offline data on logout
Clear offline data on logout
Java
bsd-2-clause
0359xiaodong/WaniKani-for-Android,diptakobu/WaniKani-for-Android,shekibobo/WaniKani-for-Android,0359xiaodong/WaniKani-for-Android,leerduo/WaniKani-for-Android,gkathir15/WaniKani-for-Android,dhamofficial/WaniKani-for-Android,diptakobu/WaniKani-for-Android,jiangzhonghui/WaniKani-for-Android,Gustorn/WaniKani-for-Android,shekibobo/WaniKani-for-Android,msdgwzhy6/WaniKani-for-Android,leerduo/WaniKani-for-Android,dhamofficial/WaniKani-for-Android,gkathir15/WaniKani-for-Android,jiangzhonghui/WaniKani-for-Android,Gustorn/WaniKani-for-Android,msdgwzhy6/WaniKani-for-Android
java
## Code Before: package tr.xip.wanikani.managers; import android.content.Context; import android.content.SharedPreferences; import android.os.Environment; import android.preference.PreferenceManager; /** * Created by xihsa_000 on 3/11/14. */ public class PrefManager { private static SharedPreferences prefs; private static SharedPreferences.Editor prefeditor; private static Context context; public PrefManager(Context mContext) { context = mContext; prefs = context.getSharedPreferences("prefs", 0); prefeditor = prefs.edit(); } public String getApiKey() { return prefs.getString("api_key", "0"); } public boolean isFirstLaunch() { return prefs.getBoolean("first_launch", true); } public void setFirstLaunch(boolean value) { prefeditor.putBoolean("first_launch", value).commit(); } public void setApiKey(String key) { prefeditor.putString("api_key", key).commit(); } public boolean isProfileFirstTime() { return prefs.getBoolean("first_time_profile", true); } public void setProfileFirstTime(boolean value) { prefeditor.putBoolean("first_time_profile", value).commit(); } public void logout() { prefeditor.clear().commit(); } } ## Instruction: Clear offline data on logout ## Code After: package tr.xip.wanikani.managers; import android.content.Context; import android.content.SharedPreferences; import android.os.Environment; import android.preference.PreferenceManager; /** * Created by xihsa_000 on 3/11/14. */ public class PrefManager { private static SharedPreferences prefs; private static SharedPreferences offlineData; private static SharedPreferences.Editor prefeditor; private static SharedPreferences.Editor offlineDataEditor; private static Context context; public PrefManager(Context mContext) { context = mContext; prefs = context.getSharedPreferences("prefs", 0); offlineData = context.getSharedPreferences("offline_data", 0); prefeditor = prefs.edit(); offlineDataEditor = offlineData.edit(); } public String getApiKey() { return prefs.getString("api_key", "0"); } public boolean isFirstLaunch() { return prefs.getBoolean("first_launch", true); } public void setFirstLaunch(boolean value) { prefeditor.putBoolean("first_launch", value).commit(); } public void setApiKey(String key) { prefeditor.putString("api_key", key).commit(); } public boolean isProfileFirstTime() { return prefs.getBoolean("first_time_profile", true); } public void setProfileFirstTime(boolean value) { prefeditor.putBoolean("first_time_profile", value).commit(); } public void logout() { prefeditor.clear().commit(); offlineDataEditor.clear().commit(); } }
// ... existing code ... */ public class PrefManager { private static SharedPreferences prefs; private static SharedPreferences offlineData; private static SharedPreferences.Editor prefeditor; private static SharedPreferences.Editor offlineDataEditor; private static Context context; public PrefManager(Context mContext) { context = mContext; prefs = context.getSharedPreferences("prefs", 0); offlineData = context.getSharedPreferences("offline_data", 0); prefeditor = prefs.edit(); offlineDataEditor = offlineData.edit(); } public String getApiKey() { // ... modified code ... public void logout() { prefeditor.clear().commit(); offlineDataEditor.clear().commit(); } } // ... rest of the code ...
6fa2d67e27fcbd0cc8ff5858e4038e14a0ab8ae1
bika/lims/skins/bika/guard_receive_transition.py
bika/lims/skins/bika/guard_receive_transition.py
from DateTime import DateTime workflow = context.portal_workflow # False if object is cancelled if workflow.getInfoFor(context, 'cancellation_state', "active") == "cancelled": return False if context.portal_type == 'AnalysisRequest': # False if our Sample's SamplingDate is the future if context.getSample().getSamplingDate() > DateTime(): return False # False if any Field Analyses in any of our sample's ARs have no result. for ar in context.getSample().getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') if a.getObject().getResult() == '']: return False elif context.portal_type == 'Sample': # False if our SamplingDate is the future if context.getSamplingDate() > DateTime(): return False # False if any of this Sample's ARs have Field Analyses without results. for ar in context.getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') if a.getObject().getResult() == '']: return False return True
from DateTime import DateTime workflow = context.portal_workflow # False if object is cancelled if workflow.getInfoFor(context, 'cancellation_state', "active") == "cancelled": return False if context.portal_type == 'AnalysisRequest': # False if any Field Analyses in any of our sample's ARs have no result. for ar in context.getSample().getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') if a.getObject().getResult() == '']: return False elif context.portal_type == 'Sample': # False if any of this Sample's ARs have Field Analyses without results. for ar in context.getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') if a.getObject().getResult() == '']: return False return True
Allow receive of future-dated samples
Allow receive of future-dated samples
Python
agpl-3.0
veroc/Bika-LIMS,DeBortoliWines/Bika-LIMS,veroc/Bika-LIMS,anneline/Bika-LIMS,labsanmartin/Bika-LIMS,veroc/Bika-LIMS,DeBortoliWines/Bika-LIMS,labsanmartin/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,labsanmartin/Bika-LIMS,anneline/Bika-LIMS,rockfruit/bika.lims,rockfruit/bika.lims
python
## Code Before: from DateTime import DateTime workflow = context.portal_workflow # False if object is cancelled if workflow.getInfoFor(context, 'cancellation_state', "active") == "cancelled": return False if context.portal_type == 'AnalysisRequest': # False if our Sample's SamplingDate is the future if context.getSample().getSamplingDate() > DateTime(): return False # False if any Field Analyses in any of our sample's ARs have no result. for ar in context.getSample().getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') if a.getObject().getResult() == '']: return False elif context.portal_type == 'Sample': # False if our SamplingDate is the future if context.getSamplingDate() > DateTime(): return False # False if any of this Sample's ARs have Field Analyses without results. for ar in context.getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') if a.getObject().getResult() == '']: return False return True ## Instruction: Allow receive of future-dated samples ## Code After: from DateTime import DateTime workflow = context.portal_workflow # False if object is cancelled if workflow.getInfoFor(context, 'cancellation_state', "active") == "cancelled": return False if context.portal_type == 'AnalysisRequest': # False if any Field Analyses in any of our sample's ARs have no result. for ar in context.getSample().getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') if a.getObject().getResult() == '']: return False elif context.portal_type == 'Sample': # False if any of this Sample's ARs have Field Analyses without results. for ar in context.getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') if a.getObject().getResult() == '']: return False return True
# ... existing code ... if context.portal_type == 'AnalysisRequest': # False if any Field Analyses in any of our sample's ARs have no result. for ar in context.getSample().getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') # ... modified code ... elif context.portal_type == 'Sample': # False if any of this Sample's ARs have Field Analyses without results. for ar in context.getAnalysisRequests(): if [a for a in ar.getAnalyses(getPointOfCapture='field') # ... rest of the code ...
9c96ab17b1a2686fa5d391b756ba714d0288b8ca
base/src/main/java/edu/umass/cs/ciir/waltz/io/galago/ReadableBufferStaticStream.java
base/src/main/java/edu/umass/cs/ciir/waltz/io/galago/ReadableBufferStaticStream.java
package edu.umass.cs.ciir.waltz.io.galago; import edu.umass.cs.ciir.waltz.io.streams.SkipInputStream; import edu.umass.cs.ciir.waltz.io.streams.StaticStream; import org.lemurproject.galago.utility.btree.disk.DiskBTreeIterator; import org.lemurproject.galago.utility.buffer.CachedBufferDataStream; import org.lemurproject.galago.utility.buffer.ReadableBuffer; import java.io.IOException; /** * @author jfoley */ class ReadableBufferStaticStream implements StaticStream { private final long start; private final long end; private final ReadableBuffer file; public ReadableBufferStaticStream(DiskBTreeIterator iterator) throws IOException { this.start = iterator.getValueStart(); this.end = iterator.getValueEnd(); this.file = iterator.input; } @Override public SkipInputStream getNewStream() { return new GalagoSkipInputStream(new CachedBufferDataStream(file, start, end)); } @Override public long length() { return end - start; } }
package edu.umass.cs.ciir.waltz.io.galago; import edu.umass.cs.ciir.waltz.io.streams.SkipInputStream; import edu.umass.cs.ciir.waltz.io.streams.StaticStream; import org.lemurproject.galago.utility.btree.disk.DiskBTreeIterator; import org.lemurproject.galago.utility.buffer.CachedBufferDataStream; import org.lemurproject.galago.utility.buffer.ReadableBuffer; import java.io.IOException; /** * @author jfoley */ class ReadableBufferStaticStream implements StaticStream { private final long start; private final long end; private final ReadableBuffer file; // Convenience method, probably shouldn't be here... public ReadableBufferStaticStream(DiskBTreeIterator iterator) throws IOException { this(iterator.input, iterator.getValueStart(), iterator.getValueEnd()); } public ReadableBufferStaticStream(ReadableBuffer file, long start, long end) throws IOException { this.start = start; this.end = end; this.file = file; } @Override public SkipInputStream getNewStream() { return new GalagoSkipInputStream(new CachedBufferDataStream(file, start, end)); } @Override public long length() { return end - start; } }
Make a better public constructor for that thing.
Make a better public constructor for that thing.
Java
bsd-3-clause
jjfiv/waltz
java
## Code Before: package edu.umass.cs.ciir.waltz.io.galago; import edu.umass.cs.ciir.waltz.io.streams.SkipInputStream; import edu.umass.cs.ciir.waltz.io.streams.StaticStream; import org.lemurproject.galago.utility.btree.disk.DiskBTreeIterator; import org.lemurproject.galago.utility.buffer.CachedBufferDataStream; import org.lemurproject.galago.utility.buffer.ReadableBuffer; import java.io.IOException; /** * @author jfoley */ class ReadableBufferStaticStream implements StaticStream { private final long start; private final long end; private final ReadableBuffer file; public ReadableBufferStaticStream(DiskBTreeIterator iterator) throws IOException { this.start = iterator.getValueStart(); this.end = iterator.getValueEnd(); this.file = iterator.input; } @Override public SkipInputStream getNewStream() { return new GalagoSkipInputStream(new CachedBufferDataStream(file, start, end)); } @Override public long length() { return end - start; } } ## Instruction: Make a better public constructor for that thing. ## Code After: package edu.umass.cs.ciir.waltz.io.galago; import edu.umass.cs.ciir.waltz.io.streams.SkipInputStream; import edu.umass.cs.ciir.waltz.io.streams.StaticStream; import org.lemurproject.galago.utility.btree.disk.DiskBTreeIterator; import org.lemurproject.galago.utility.buffer.CachedBufferDataStream; import org.lemurproject.galago.utility.buffer.ReadableBuffer; import java.io.IOException; /** * @author jfoley */ class ReadableBufferStaticStream implements StaticStream { private final long start; private final long end; private final ReadableBuffer file; // Convenience method, probably shouldn't be here... public ReadableBufferStaticStream(DiskBTreeIterator iterator) throws IOException { this(iterator.input, iterator.getValueStart(), iterator.getValueEnd()); } public ReadableBufferStaticStream(ReadableBuffer file, long start, long end) throws IOException { this.start = start; this.end = end; this.file = file; } @Override public SkipInputStream getNewStream() { return new GalagoSkipInputStream(new CachedBufferDataStream(file, start, end)); } @Override public long length() { return end - start; } }
// ... existing code ... private final long end; private final ReadableBuffer file; // Convenience method, probably shouldn't be here... public ReadableBufferStaticStream(DiskBTreeIterator iterator) throws IOException { this(iterator.input, iterator.getValueStart(), iterator.getValueEnd()); } public ReadableBufferStaticStream(ReadableBuffer file, long start, long end) throws IOException { this.start = start; this.end = end; this.file = file; } @Override // ... rest of the code ...
d731ad50b863d32740bec857d46cc0c80e440185
tests/melopy_tests.py
tests/melopy_tests.py
from unittest import TestCase from nose.tools import * from melopy.melopy import * class MelopyTests(TestCase): def test_dummy(self): assert True
from unittest import TestCase from nose.tools import * from melopy import * class LibraryFunctionsTests(TestCase): def test_frequency_from_key(self): key = 49 assert frequency_from_key(key) == 440 def test_frequency_from_note(self): note = 'A4' assert frequency_from_note(note) == 440 def test_key_from_note(self): note = 'A4' assert key_from_note(note) == 49 def test_note_from_key(self): key = 49 assert note_from_key(key) == 'A4' def test_iterate(self): start = 'D4' pattern = [2, 2, 1, 2, 2, 2] should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5'] assert iterate(start, pattern) == should_be def test_generate_major_scale(self): start = 'D4' should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5'] assert generate_major_scale(start) == should_be def test_generate_minor_scale(self): start = 'C4' should_be = ['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4'] assert generate_minor_scale(start) == should_be def test_generate_major_triad(self): start = 'A4' should_be = ['A4', 'C#5', 'E5'] assert generate_major_triad(start) == should_be def test_generate_minor_triad(self): start = 'C5' should_be = ['C5', 'Eb5', 'G5'] assert generate_minor_triad(start) == should_be class MelopyTests(TestCase): def test_dummy(self): assert True
Add tests for the library methods. All except 2 pass right now.
Add tests for the library methods. All except 2 pass right now. The two that don't pass, fail because I have changed what their output should be. In the docs, it is shown that the output of `generate_minor_scale`, given 'C4', is: ['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'A#4'] This is incorrect. The actual minor scale is: ['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4'] The same kind of inconsistency is found in the `generate_minor_triad` output. This is not a proper minor triad: ['C5', 'D#5', 'G5'] because C -> D# is not a minor third interval, it is an augmented second interval. I know, for all practical purposes it will generate the same tone, but my musical OCD can't stand to see it this way lol!
Python
mit
jdan/Melopy,juliowaissman/Melopy
python
## Code Before: from unittest import TestCase from nose.tools import * from melopy.melopy import * class MelopyTests(TestCase): def test_dummy(self): assert True ## Instruction: Add tests for the library methods. All except 2 pass right now. The two that don't pass, fail because I have changed what their output should be. In the docs, it is shown that the output of `generate_minor_scale`, given 'C4', is: ['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'A#4'] This is incorrect. The actual minor scale is: ['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4'] The same kind of inconsistency is found in the `generate_minor_triad` output. This is not a proper minor triad: ['C5', 'D#5', 'G5'] because C -> D# is not a minor third interval, it is an augmented second interval. I know, for all practical purposes it will generate the same tone, but my musical OCD can't stand to see it this way lol! ## Code After: from unittest import TestCase from nose.tools import * from melopy import * class LibraryFunctionsTests(TestCase): def test_frequency_from_key(self): key = 49 assert frequency_from_key(key) == 440 def test_frequency_from_note(self): note = 'A4' assert frequency_from_note(note) == 440 def test_key_from_note(self): note = 'A4' assert key_from_note(note) == 49 def test_note_from_key(self): key = 49 assert note_from_key(key) == 'A4' def test_iterate(self): start = 'D4' pattern = [2, 2, 1, 2, 2, 2] should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5'] assert iterate(start, pattern) == should_be def test_generate_major_scale(self): start = 'D4' should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5'] assert generate_major_scale(start) == should_be def test_generate_minor_scale(self): start = 'C4' should_be = ['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4'] assert generate_minor_scale(start) == should_be def test_generate_major_triad(self): start = 'A4' should_be = ['A4', 'C#5', 'E5'] assert generate_major_triad(start) == should_be def test_generate_minor_triad(self): start = 'C5' should_be = ['C5', 'Eb5', 'G5'] assert generate_minor_triad(start) == should_be class MelopyTests(TestCase): def test_dummy(self): assert True
# ... existing code ... from nose.tools import * from melopy import * class LibraryFunctionsTests(TestCase): def test_frequency_from_key(self): key = 49 assert frequency_from_key(key) == 440 def test_frequency_from_note(self): note = 'A4' assert frequency_from_note(note) == 440 def test_key_from_note(self): note = 'A4' assert key_from_note(note) == 49 def test_note_from_key(self): key = 49 assert note_from_key(key) == 'A4' def test_iterate(self): start = 'D4' pattern = [2, 2, 1, 2, 2, 2] should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5'] assert iterate(start, pattern) == should_be def test_generate_major_scale(self): start = 'D4' should_be = ['D4', 'E4', 'F#4', 'G4', 'A4', 'B4', 'C#5'] assert generate_major_scale(start) == should_be def test_generate_minor_scale(self): start = 'C4' should_be = ['C4', 'D4', 'Eb4', 'F4', 'G4', 'Ab4', 'Bb4'] assert generate_minor_scale(start) == should_be def test_generate_major_triad(self): start = 'A4' should_be = ['A4', 'C#5', 'E5'] assert generate_major_triad(start) == should_be def test_generate_minor_triad(self): start = 'C5' should_be = ['C5', 'Eb5', 'G5'] assert generate_minor_triad(start) == should_be class MelopyTests(TestCase): def test_dummy(self): # ... rest of the code ...
c9275ff9859f28753e2e261054e7c0aacc4c28dc
monitoring/co2/local/k30.py
monitoring/co2/local/k30.py
import serial import time from optparse import OptionParser import sys ser = serial.Serial("/dev/ttyAMA0") print("Serial Connected!", file=sys.stderr) ser.flushInput() time.sleep(1) parser = OptionParser() parser.add_option("-t", "--average-time", dest="avgtime", help="Report value averaged across this period of time", metavar="SECONDS") (options, args) = parser.parse_args() sum = 0 num = int(options.avgtime) num_init = num while True: ser.write("\xFE\x44\x00\x08\x02\x9F\x25".encode()) time.sleep(.01) resp = ser.read(7) high = ord(resp[3]) low = ord(resp[4]) co2 = (high*256) + low sum += co2 num -= 1 print(time.strftime("%c") + ": CO2 = " + str(co2) + " ppm", file=sys.stderr) if (num > 0): time.sleep(1) if (num == 0): break print(int(sum/num_init))
import serial import time from optparse import OptionParser import sys ser = serial.Serial("/dev/serial0") #print("Serial Connected!", file=sys.stderr) ser.flushInput() time.sleep(1) parser = OptionParser() parser.add_option("-t", "--average-time", dest="avgtime", help="Report value averaged across this period of time", metavar="SECONDS") (options, args) = parser.parse_args() sum = 0 num = int(options.avgtime) num_init = num while True: #ser.write("\xFE\x44\x00\x08\x02\x9F\x25".encode()) ser.write("\xFE\x44\x00\x08\x02\x9F\x25") time.sleep(.01) resp = ser.read(7) high = ord(resp[3]) low = ord(resp[4]) co2 = (high*256) + low sum += co2 num -= 1 #print(time.strftime("%c") + ": CO2 = " + str(co2) + " ppm", file=sys.stderr) if (num > 0): time.sleep(1) if (num == 0): break #print(int(sum/num_init)) print int(sum/num_init)
Revert to python2, python3 converted code isn't working as expected
Revert to python2, python3 converted code isn't working as expected
Python
mit
xopok/xopok-scripts,xopok/xopok-scripts
python
## Code Before: import serial import time from optparse import OptionParser import sys ser = serial.Serial("/dev/ttyAMA0") print("Serial Connected!", file=sys.stderr) ser.flushInput() time.sleep(1) parser = OptionParser() parser.add_option("-t", "--average-time", dest="avgtime", help="Report value averaged across this period of time", metavar="SECONDS") (options, args) = parser.parse_args() sum = 0 num = int(options.avgtime) num_init = num while True: ser.write("\xFE\x44\x00\x08\x02\x9F\x25".encode()) time.sleep(.01) resp = ser.read(7) high = ord(resp[3]) low = ord(resp[4]) co2 = (high*256) + low sum += co2 num -= 1 print(time.strftime("%c") + ": CO2 = " + str(co2) + " ppm", file=sys.stderr) if (num > 0): time.sleep(1) if (num == 0): break print(int(sum/num_init)) ## Instruction: Revert to python2, python3 converted code isn't working as expected ## Code After: import serial import time from optparse import OptionParser import sys ser = serial.Serial("/dev/serial0") #print("Serial Connected!", file=sys.stderr) ser.flushInput() time.sleep(1) parser = OptionParser() parser.add_option("-t", "--average-time", dest="avgtime", help="Report value averaged across this period of time", metavar="SECONDS") (options, args) = parser.parse_args() sum = 0 num = int(options.avgtime) num_init = num while True: #ser.write("\xFE\x44\x00\x08\x02\x9F\x25".encode()) ser.write("\xFE\x44\x00\x08\x02\x9F\x25") time.sleep(.01) resp = ser.read(7) high = ord(resp[3]) low = ord(resp[4]) co2 = (high*256) + low sum += co2 num -= 1 #print(time.strftime("%c") + ": CO2 = " + str(co2) + " ppm", file=sys.stderr) if (num > 0): time.sleep(1) if (num == 0): break #print(int(sum/num_init)) print int(sum/num_init)
// ... existing code ... from optparse import OptionParser import sys ser = serial.Serial("/dev/serial0") #print("Serial Connected!", file=sys.stderr) ser.flushInput() time.sleep(1) // ... modified code ... num_init = num while True: #ser.write("\xFE\x44\x00\x08\x02\x9F\x25".encode()) ser.write("\xFE\x44\x00\x08\x02\x9F\x25") time.sleep(.01) resp = ser.read(7) high = ord(resp[3]) ... co2 = (high*256) + low sum += co2 num -= 1 #print(time.strftime("%c") + ": CO2 = " + str(co2) + " ppm", file=sys.stderr) if (num > 0): time.sleep(1) if (num == 0): break #print(int(sum/num_init)) print int(sum/num_init) // ... rest of the code ...
c35c11fb546123d0aada37fe7d7ab1829a6fa9f0
graphenebase/transactions.py
graphenebase/transactions.py
from collections import OrderedDict from binascii import hexlify, unhexlify from calendar import timegm from datetime import datetime import json import struct import time from .account import PublicKey from .chains import known_chains from .signedtransactions import Signed_Transaction from .operations import Operation from .objects import GrapheneObject, isArgsThisClass timeformat = '%Y-%m-%dT%H:%M:%S%Z' def getBlockParams(ws): """ Auxiliary method to obtain ``ref_block_num`` and ``ref_block_prefix``. Requires a websocket connection to a witness node! """ dynBCParams = ws.get_dynamic_global_properties() ref_block_num = dynBCParams["last_irreversible_block_num"] & 0xFFFF ref_block_prefix = struct.unpack_from("<I", unhexlify(dynBCParams["head_block_id"]), 4)[0] return ref_block_num, ref_block_prefix def formatTimeFromNow(secs=0): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str """ return datetime.utcfromtimestamp(time.time() + int(secs)).strftime(timeformat)
from collections import OrderedDict from binascii import hexlify, unhexlify from calendar import timegm from datetime import datetime import json import struct import time from .account import PublicKey from .chains import known_chains from .signedtransactions import Signed_Transaction from .operations import Operation from .objects import GrapheneObject, isArgsThisClass timeformat = '%Y-%m-%dT%H:%M:%S%Z' def getBlockParams(ws): """ Auxiliary method to obtain ``ref_block_num`` and ``ref_block_prefix``. Requires a websocket connection to a witness node! """ dynBCParams = ws.get_dynamic_global_properties() ref_block_num = dynBCParams["head_block_number"] & 0xFFFF ref_block_prefix = struct.unpack_from("<I", unhexlify(dynBCParams["head_block_id"]), 4)[0] return ref_block_num, ref_block_prefix def formatTimeFromNow(secs=0): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str """ return datetime.utcfromtimestamp(time.time() + int(secs)).strftime(timeformat)
Revert "[TaPOS] link to the last irreversible block instead of headblock"
Revert "[TaPOS] link to the last irreversible block instead of headblock" This reverts commit 05cec8e450a09fd0d3fa2b40860760f7bff0c125.
Python
mit
xeroc/python-graphenelib
python
## Code Before: from collections import OrderedDict from binascii import hexlify, unhexlify from calendar import timegm from datetime import datetime import json import struct import time from .account import PublicKey from .chains import known_chains from .signedtransactions import Signed_Transaction from .operations import Operation from .objects import GrapheneObject, isArgsThisClass timeformat = '%Y-%m-%dT%H:%M:%S%Z' def getBlockParams(ws): """ Auxiliary method to obtain ``ref_block_num`` and ``ref_block_prefix``. Requires a websocket connection to a witness node! """ dynBCParams = ws.get_dynamic_global_properties() ref_block_num = dynBCParams["last_irreversible_block_num"] & 0xFFFF ref_block_prefix = struct.unpack_from("<I", unhexlify(dynBCParams["head_block_id"]), 4)[0] return ref_block_num, ref_block_prefix def formatTimeFromNow(secs=0): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str """ return datetime.utcfromtimestamp(time.time() + int(secs)).strftime(timeformat) ## Instruction: Revert "[TaPOS] link to the last irreversible block instead of headblock" This reverts commit 05cec8e450a09fd0d3fa2b40860760f7bff0c125. ## Code After: from collections import OrderedDict from binascii import hexlify, unhexlify from calendar import timegm from datetime import datetime import json import struct import time from .account import PublicKey from .chains import known_chains from .signedtransactions import Signed_Transaction from .operations import Operation from .objects import GrapheneObject, isArgsThisClass timeformat = '%Y-%m-%dT%H:%M:%S%Z' def getBlockParams(ws): """ Auxiliary method to obtain ``ref_block_num`` and ``ref_block_prefix``. Requires a websocket connection to a witness node! """ dynBCParams = ws.get_dynamic_global_properties() ref_block_num = dynBCParams["head_block_number"] & 0xFFFF ref_block_prefix = struct.unpack_from("<I", unhexlify(dynBCParams["head_block_id"]), 4)[0] return ref_block_num, ref_block_prefix def formatTimeFromNow(secs=0): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str """ return datetime.utcfromtimestamp(time.time() + int(secs)).strftime(timeformat)
// ... existing code ... witness node! """ dynBCParams = ws.get_dynamic_global_properties() ref_block_num = dynBCParams["head_block_number"] & 0xFFFF ref_block_prefix = struct.unpack_from("<I", unhexlify(dynBCParams["head_block_id"]), 4)[0] return ref_block_num, ref_block_prefix // ... rest of the code ...
b33fcfe3752caeb61a83eb04c3b8399b7c44c9a4
sylvia/__init__.py
sylvia/__init__.py
from PhonemeDetails import * from LetterDetails import * from PronunciationInferencer import * from PhoneticDictionary import * from Poem import * from SylviaConsole import * from SylviaEpcServer import *
import sys if sys.version_info[0] > 2: raise Exception( "Sorry, we're still on Python 2. Version 1.0 of Sylvia will finally move to Python 3." ) from PhonemeDetails import * from LetterDetails import * from PronunciationInferencer import * from PhoneticDictionary import * from Poem import * from SylviaConsole import * from SylviaEpcServer import *
Add meaningful error for runnign with Python3
Add meaningful error for runnign with Python3 If we detect a Python3 interpreter at module init, tell the user to use Python 2. And be sure to apologize because it's 2019...
Python
mit
bgutter/sylvia
python
## Code Before: from PhonemeDetails import * from LetterDetails import * from PronunciationInferencer import * from PhoneticDictionary import * from Poem import * from SylviaConsole import * from SylviaEpcServer import * ## Instruction: Add meaningful error for runnign with Python3 If we detect a Python3 interpreter at module init, tell the user to use Python 2. And be sure to apologize because it's 2019... ## Code After: import sys if sys.version_info[0] > 2: raise Exception( "Sorry, we're still on Python 2. Version 1.0 of Sylvia will finally move to Python 3." ) from PhonemeDetails import * from LetterDetails import * from PronunciationInferencer import * from PhoneticDictionary import * from Poem import * from SylviaConsole import * from SylviaEpcServer import *
// ... existing code ... import sys if sys.version_info[0] > 2: raise Exception( "Sorry, we're still on Python 2. Version 1.0 of Sylvia will finally move to Python 3." ) from PhonemeDetails import * from LetterDetails import * from PronunciationInferencer import * // ... rest of the code ...
8c097f07eca52dc37e8d3d4591bb9ee1c05fa310
calexicon/calendars/tests/test_other.py
calexicon/calendars/tests/test_other.py
from datetime import date as vanilla_date from calendar_testing import CalendarTest from calexicon.calendars.other import JulianDayNumber class TestJulianDayNumber(CalendarTest): def setUp(self): self.calendar = JulianDayNumber() def test_make_date(self): vd = vanilla_date(2010, 8, 1) d = self.calendar.from_date(vd) self.assertIsNotNone(d) def test_first_date(self): vd = vanilla_date(1, 1, 1) d = self.calendar.from_date(vd) self.assertEqual(str(d), 'Day 1721423 (Julian Day Number)')
from datetime import date as vanilla_date from calendar_testing import CalendarTest from calexicon.calendars.other import JulianDayNumber class TestJulianDayNumber(CalendarTest): def setUp(self): self.calendar = JulianDayNumber() def test_make_date(self): vd = vanilla_date(2010, 8, 1) d = self.calendar.from_date(vd) self.assertIsNotNone(d) def test_first_date(self): vd = vanilla_date(1, 1, 1) d = self.calendar.from_date(vd) self.assertEqual(str(d), 'Day 1721423 (Julian Day Number)') def compare_date_and_number(self, year, month, day, number): vd = vanilla_date(year, month, day) d = self.calendar.from_date(vd) self.assertEqual(d.native_representation(), {'day_number': number}) def test_other_date(self): self.compare_date_and_number(2013, 1, 1, 2456293)
Add a new test - on date to day number conversion.
Add a new test - on date to day number conversion.
Python
apache-2.0
jwg4/qual,jwg4/calexicon
python
## Code Before: from datetime import date as vanilla_date from calendar_testing import CalendarTest from calexicon.calendars.other import JulianDayNumber class TestJulianDayNumber(CalendarTest): def setUp(self): self.calendar = JulianDayNumber() def test_make_date(self): vd = vanilla_date(2010, 8, 1) d = self.calendar.from_date(vd) self.assertIsNotNone(d) def test_first_date(self): vd = vanilla_date(1, 1, 1) d = self.calendar.from_date(vd) self.assertEqual(str(d), 'Day 1721423 (Julian Day Number)') ## Instruction: Add a new test - on date to day number conversion. ## Code After: from datetime import date as vanilla_date from calendar_testing import CalendarTest from calexicon.calendars.other import JulianDayNumber class TestJulianDayNumber(CalendarTest): def setUp(self): self.calendar = JulianDayNumber() def test_make_date(self): vd = vanilla_date(2010, 8, 1) d = self.calendar.from_date(vd) self.assertIsNotNone(d) def test_first_date(self): vd = vanilla_date(1, 1, 1) d = self.calendar.from_date(vd) self.assertEqual(str(d), 'Day 1721423 (Julian Day Number)') def compare_date_and_number(self, year, month, day, number): vd = vanilla_date(year, month, day) d = self.calendar.from_date(vd) self.assertEqual(d.native_representation(), {'day_number': number}) def test_other_date(self): self.compare_date_and_number(2013, 1, 1, 2456293)
// ... existing code ... d = self.calendar.from_date(vd) self.assertEqual(str(d), 'Day 1721423 (Julian Day Number)') def compare_date_and_number(self, year, month, day, number): vd = vanilla_date(year, month, day) d = self.calendar.from_date(vd) self.assertEqual(d.native_representation(), {'day_number': number}) def test_other_date(self): self.compare_date_and_number(2013, 1, 1, 2456293) // ... rest of the code ...
f1e1085ced66e5acacdc0c1613826f182f41a6dd
service-authentication/src/main/java/sg/ncl/service/authentication/AppConfig.java
service-authentication/src/main/java/sg/ncl/service/authentication/AppConfig.java
package sg.ncl.service.authentication; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import sg.ncl.common.jwt.JwtConfig; /** * @author Christopher Zhong */ @Configuration @Import({JwtConfig.class}) public class AppConfig {}
package sg.ncl.service.authentication; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import sg.ncl.common.jwt.JwtConfig; /** * @author Christopher Zhong */ @Configuration("sg.ncl.service.authentication.AppConfig") @Import({JwtConfig.class}) public class AppConfig {}
Change configuration name to avoid conflicts (DEV-99)
Change configuration name to avoid conflicts (DEV-99)
Java
apache-2.0
nus-ncl/services-in-one,nus-ncl/services-in-one
java
## Code Before: package sg.ncl.service.authentication; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import sg.ncl.common.jwt.JwtConfig; /** * @author Christopher Zhong */ @Configuration @Import({JwtConfig.class}) public class AppConfig {} ## Instruction: Change configuration name to avoid conflicts (DEV-99) ## Code After: package sg.ncl.service.authentication; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import sg.ncl.common.jwt.JwtConfig; /** * @author Christopher Zhong */ @Configuration("sg.ncl.service.authentication.AppConfig") @Import({JwtConfig.class}) public class AppConfig {}
// ... existing code ... /** * @author Christopher Zhong */ @Configuration("sg.ncl.service.authentication.AppConfig") @Import({JwtConfig.class}) public class AppConfig {} // ... rest of the code ...
d3a24fae87005b7f5c47657851b4341726494383
atest/resources/atest_variables.py
atest/resources/atest_variables.py
from os.path import abspath, dirname, join, normpath import locale import os import subprocess import robot __all__ = ['ROBOTPATH', 'ROBOT_VERSION', 'DATADIR', 'SYSTEM_ENCODING', 'CONSOLE_ENCODING'] ROBOTPATH = dirname(abspath(robot.__file__)) ROBOT_VERSION = robot.version.get_version() DATADIR = normpath(join(dirname(abspath(__file__)), '..', 'testdata')) SYSTEM_ENCODING = locale.getpreferredencoding(False) # Python 3.6+ uses UTF-8 internally on Windows. We want real console encoding. if os.name == 'nt': output = subprocess.check_output('chcp', shell=True, encoding='ASCII') CONSOLE_ENCODING = 'cp' + output.split()[-1] else: CONSOLE_ENCODING = locale.getdefaultlocale()[-1]
from os.path import abspath, dirname, join, normpath import locale import os import subprocess import robot __all__ = ['ROBOTPATH', 'ROBOT_VERSION', 'DATADIR', 'SYSTEM_ENCODING', 'CONSOLE_ENCODING'] ROBOTPATH = dirname(abspath(robot.__file__)) ROBOT_VERSION = robot.version.get_version() DATADIR = normpath(join(dirname(abspath(__file__)), '..', 'testdata')) SYSTEM_ENCODING = locale.getpreferredencoding(False) # Python 3.6+ uses UTF-8 internally on Windows. We want real console encoding. if os.name == 'nt': output = subprocess.check_output('chcp', shell=True, encoding='ASCII', errors='ignore') CONSOLE_ENCODING = 'cp' + output.split()[-1] else: CONSOLE_ENCODING = locale.getdefaultlocale()[-1]
Fix getting Windows system encoding on non-ASCII envs
atests: Fix getting Windows system encoding on non-ASCII envs
Python
apache-2.0
HelioGuilherme66/robotframework,robotframework/robotframework,HelioGuilherme66/robotframework,robotframework/robotframework,HelioGuilherme66/robotframework,robotframework/robotframework
python
## Code Before: from os.path import abspath, dirname, join, normpath import locale import os import subprocess import robot __all__ = ['ROBOTPATH', 'ROBOT_VERSION', 'DATADIR', 'SYSTEM_ENCODING', 'CONSOLE_ENCODING'] ROBOTPATH = dirname(abspath(robot.__file__)) ROBOT_VERSION = robot.version.get_version() DATADIR = normpath(join(dirname(abspath(__file__)), '..', 'testdata')) SYSTEM_ENCODING = locale.getpreferredencoding(False) # Python 3.6+ uses UTF-8 internally on Windows. We want real console encoding. if os.name == 'nt': output = subprocess.check_output('chcp', shell=True, encoding='ASCII') CONSOLE_ENCODING = 'cp' + output.split()[-1] else: CONSOLE_ENCODING = locale.getdefaultlocale()[-1] ## Instruction: atests: Fix getting Windows system encoding on non-ASCII envs ## Code After: from os.path import abspath, dirname, join, normpath import locale import os import subprocess import robot __all__ = ['ROBOTPATH', 'ROBOT_VERSION', 'DATADIR', 'SYSTEM_ENCODING', 'CONSOLE_ENCODING'] ROBOTPATH = dirname(abspath(robot.__file__)) ROBOT_VERSION = robot.version.get_version() DATADIR = normpath(join(dirname(abspath(__file__)), '..', 'testdata')) SYSTEM_ENCODING = locale.getpreferredencoding(False) # Python 3.6+ uses UTF-8 internally on Windows. We want real console encoding. if os.name == 'nt': output = subprocess.check_output('chcp', shell=True, encoding='ASCII', errors='ignore') CONSOLE_ENCODING = 'cp' + output.split()[-1] else: CONSOLE_ENCODING = locale.getdefaultlocale()[-1]
... SYSTEM_ENCODING = locale.getpreferredencoding(False) # Python 3.6+ uses UTF-8 internally on Windows. We want real console encoding. if os.name == 'nt': output = subprocess.check_output('chcp', shell=True, encoding='ASCII', errors='ignore') CONSOLE_ENCODING = 'cp' + output.split()[-1] else: CONSOLE_ENCODING = locale.getdefaultlocale()[-1] ...
5d8555ffc9a4b0549d32161a79aada3857b9d639
webapp/graphite/events/models.py
webapp/graphite/events/models.py
import time import os from django.db import models from django.contrib import admin if os.environ.get('READTHEDOCS'): TagField = lambda *args, **kwargs: None else: from tagging.fields import TagField class Event(models.Model): class Admin: pass when = models.DateTimeField() what = models.CharField(max_length=255) data = models.TextField(blank=True) tags = TagField(default="") def get_tags(self): return Tag.objects.get_for_object(self) def __str__(self): return "%s: %s" % (self.when, self.what) @staticmethod def find_events(time_from=None, time_until=None, tags=None): query = Event.objects.all() if time_from is not None: query = query.filter(when__gte=time_from) if time_until is not None: query = query.filter(when__lte=time_until) if tags is not None: for tag in tags: query = query.filter(tags__iregex=r'\b%s\b' % tag) result = list(query.order_by("when")) return result def as_dict(self): return dict( when=self.when, what=self.what, data=self.data, tags=self.tags, id=self.id, )
import time import os from django.db import models from django.contrib import admin from tagging.managers import ModelTaggedItemManager if os.environ.get('READTHEDOCS'): TagField = lambda *args, **kwargs: None else: from tagging.fields import TagField class Event(models.Model): class Admin: pass when = models.DateTimeField() what = models.CharField(max_length=255) data = models.TextField(blank=True) tags = TagField(default="") def get_tags(self): return Tag.objects.get_for_object(self) def __str__(self): return "%s: %s" % (self.when, self.what) @staticmethod def find_events(time_from=None, time_until=None, tags=None): if tags is not None: query = Event.tagged.with_all(tags) else: query = Event.objects.all() if time_from is not None: query = query.filter(when__gte=time_from) if time_until is not None: query = query.filter(when__lte=time_until) result = list(query.order_by("when")) return result def as_dict(self): return dict( when=self.when, what=self.what, data=self.data, tags=self.tags, id=self.id, ) # We use this rather than tagging.register() so that tags can be exposed # in the admin UI ModelTaggedItemManager().contribute_to_class(Event, 'tagged')
Fix events to work on mysql
Fix events to work on mysql Closes https://bugs.launchpad.net/graphite/+bug/993625
Python
apache-2.0
jssjr/graphite-web,mleinart/graphite-web,DanCech/graphite-web,bruce-lyft/graphite-web,dhtech/graphite-web,cgvarela/graphite-web,ceph/graphite-web,AICIDNN/graphite-web,kkdk5535/graphite-web,axibase/graphite-web,graphite-project/graphite-web,g76r/graphite-web,redice/graphite-web,section-io/graphite-web,cloudant/graphite-web,mcoolive/graphite-web,JeanFred/graphite-web,disqus/graphite-web,dbn/graphite-web,ZelunZhang/graphite-web,johnseekins/graphite-web,blacked/graphite-web,disqus/graphite-web,goir/graphite-web,deniszh/graphite-web,gwaldo/graphite-web,esnet/graphite-web,Krylon360/evernote-graphite-web,cbowman0/graphite-web,redice/graphite-web,nkhuyu/graphite-web,synedge/graphite-web,slackhappy/graphite-web,pu239ppy/graphite-web,Invoca/graphite-web,markolson/graphite-web,cosm0s/graphite-web,cbowman0/graphite-web,piotr1212/graphite-web,section-io/graphite-web,bruce-lyft/graphite-web,Skyscanner/graphite-web,cosm0s/graphite-web,EinsamHauer/graphite-web-iow,deniszh/graphite-web,bpaquet/graphite-web,deniszh/graphite-web,bmhatfield/graphite-web,0x20h/graphite-web,ZelunZhang/graphite-web,SEJeff/graphite-web,zuazo-forks/graphite-web,axibase/graphite-web,redice/graphite-web,afilipovich/graphite-web,DanCech/graphite-web,cgvarela/graphite-web,MjAbuz/graphite-web,cosm0s/graphite-web,criteo-forks/graphite-web,nkhuyu/graphite-web,Krylon360/vimeo-graphite-web,penpen/graphite-web,ceph/graphite-web,afilipovich/graphite-web,Aloomaio/graphite-web,goir/graphite-web,kkdk5535/graphite-web,Invoca/graphite-web,penpen/graphite-web,Krylon360/evernote-graphite-web,bmhatfield/graphite-web,cgvarela/graphite-web,axibase/graphite-web,JeanFred/graphite-web,cgvarela/graphite-web,EinsamHauer/graphite-web-iow,Squarespace/graphite-web,axibase/graphite-web,g76r/graphite-web,Invoca/graphite-web,afilipovich/graphite-web,edwardmlyte/graphite-web,penpen/graphite-web,brutasse/graphite-web,mleinart/graphite-web,kkdk5535/graphite-web,nkhuyu/graphite-web,evernote/graphite-web,bpaquet/graphite-web,zuazo-forks/graphite-web,blacked/graphite-web,bbc/graphite-web,graphite-server/graphite-web,piotr1212/graphite-web,atnak/graphite-web,0x20h/graphite-web,AICIDNN/graphite-web,mcoolive/graphite-web,brutasse/graphite-web,dhtech/graphite-web,evernote/graphite-web,ceph/graphite-web,Krylon360/vimeo-graphite-web,DanCech/graphite-web,deniszh/graphite-web,penpen/graphite-web,cbowman0/graphite-web,graphite-server/graphite-web,krux/graphite-web,synedge/graphite-web,krux/graphite-web,johnseekins/graphite-web,afilipovich/graphite-web,phreakocious/graphite-web,EinsamHauer/graphite-web-iow,goir/graphite-web,bmhatfield/graphite-web,kkdk5535/graphite-web,drax68/graphite-web,SEJeff/graphite-web,johnseekins/graphite-web,JeanFred/graphite-web,atnak/graphite-web,Krylon360/vimeo-graphite-web,SEJeff/graphite-web,synedge/graphite-web,pu239ppy/graphite-web,obfuscurity/graphite-web,JeanFred/graphite-web,Squarespace/graphite-web,graphite-project/graphite-web,evernote/graphite-web,redice/graphite-web,blacked/graphite-web,brutasse/graphite-web,mleinart/graphite-web,markolson/graphite-web,cybem/graphite-web-iow,Squarespace/graphite-web,brutasse/graphite-web,afilipovich/graphite-web,cybem/graphite-web-iow,mcoolive/graphite-web,drax68/graphite-web,bmhatfield/graphite-web,bbc/graphite-web,Krylon360/evernote-graphite-web,zBMNForks/graphite-web,cosm0s/graphite-web,edwardmlyte/graphite-web,dbn/graphite-web,slackhappy/graphite-web,phreakocious/graphite-web,graphite-project/graphite-web,criteo-forks/graphite-web,Skyscanner/graphite-web,Squarespace/graphite-web,gwaldo/graphite-web,edwardmlyte/graphite-web,krux/graphite-web,Krylon360/evernote-graphite-web,mcoolive/graphite-web,Squarespace/graphite-web,zuazo-forks/graphite-web,Invoca/graphite-web,0x20h/graphite-web,atnak/graphite-web,atnak/graphite-web,criteo-forks/graphite-web,Skyscanner/graphite-web,pcn/graphite-web,SEJeff/graphite-web,cosm0s/graphite-web,drax68/graphite-web,atnak/graphite-web,DanCech/graphite-web,Krylon360/vimeo-graphite-web,johnseekins/graphite-web,pcn/graphite-web,esnet/graphite-web,bmhatfield/graphite-web,zBMNForks/graphite-web,markolson/graphite-web,axibase/graphite-web,piotr1212/graphite-web,cbowman0/graphite-web,bbc/graphite-web,markolson/graphite-web,dbn/graphite-web,deniszh/graphite-web,blacked/graphite-web,SEJeff/graphite-web,bruce-lyft/graphite-web,AICIDNN/graphite-web,Aloomaio/graphite-web,bpaquet/graphite-web,dhtech/graphite-web,atnak/graphite-web,section-io/graphite-web,bruce-lyft/graphite-web,cloudant/graphite-web,pcn/graphite-web,DanCech/graphite-web,graphite-project/graphite-web,Skyscanner/graphite-web,JeanFred/graphite-web,disqus/graphite-web,section-io/graphite-web,krux/graphite-web,pu239ppy/graphite-web,jssjr/graphite-web,zBMNForks/graphite-web,lyft/graphite-web,bruce-lyft/graphite-web,Squarespace/graphite-web,graphite-server/graphite-web,pu239ppy/graphite-web,g76r/graphite-web,disqus/graphite-web,lyft/graphite-web,goir/graphite-web,Krylon360/vimeo-graphite-web,nkhuyu/graphite-web,dbn/graphite-web,ZelunZhang/graphite-web,obfuscurity/graphite-web,deniszh/graphite-web,johnseekins/graphite-web,zuazo-forks/graphite-web,graphite-server/graphite-web,mcoolive/graphite-web,Krylon360/evernote-graphite-web,disqus/graphite-web,bruce-lyft/graphite-web,lyft/graphite-web,graphite-server/graphite-web,esnet/graphite-web,johnseekins/graphite-web,zBMNForks/graphite-web,edwardmlyte/graphite-web,cybem/graphite-web-iow,brutasse/graphite-web,lfckop/graphite-web,blacked/graphite-web,Aloomaio/graphite-web,lfckop/graphite-web,bmhatfield/graphite-web,jssjr/graphite-web,Krylon360/evernote-graphite-web,lyft/graphite-web,Talkdesk/graphite-web,g76r/graphite-web,0x20h/graphite-web,slackhappy/graphite-web,cybem/graphite-web-iow,Talkdesk/graphite-web,obfuscurity/graphite-web,cloudant/graphite-web,pcn/graphite-web,mleinart/graphite-web,Aloomaio/graphite-web,evernote/graphite-web,piotr1212/graphite-web,Talkdesk/graphite-web,Talkdesk/graphite-web,obfuscurity/graphite-web,drax68/graphite-web,esnet/graphite-web,dhtech/graphite-web,cloudant/graphite-web,dbn/graphite-web,MjAbuz/graphite-web,jssjr/graphite-web,ZelunZhang/graphite-web,bpaquet/graphite-web,cloudant/graphite-web,g76r/graphite-web,zBMNForks/graphite-web,redice/graphite-web,markolson/graphite-web,mleinart/graphite-web,section-io/graphite-web,cybem/graphite-web-iow,synedge/graphite-web,Aloomaio/graphite-web,axibase/graphite-web,lfckop/graphite-web,kkdk5535/graphite-web,Krylon360/vimeo-graphite-web,gwaldo/graphite-web,penpen/graphite-web,edwardmlyte/graphite-web,section-io/graphite-web,nkhuyu/graphite-web,evernote/graphite-web,lfckop/graphite-web,nkhuyu/graphite-web,dbn/graphite-web,jssjr/graphite-web,lyft/graphite-web,synedge/graphite-web,MjAbuz/graphite-web,Skyscanner/graphite-web,brutasse/graphite-web,Skyscanner/graphite-web,obfuscurity/graphite-web,EinsamHauer/graphite-web-iow,lfckop/graphite-web,zuazo-forks/graphite-web,krux/graphite-web,bbc/graphite-web,0x20h/graphite-web,slackhappy/graphite-web,ZelunZhang/graphite-web,lyft/graphite-web,pu239ppy/graphite-web,Talkdesk/graphite-web,ZelunZhang/graphite-web,phreakocious/graphite-web,zBMNForks/graphite-web,Invoca/graphite-web,EinsamHauer/graphite-web-iow,drax68/graphite-web,criteo-forks/graphite-web,dhtech/graphite-web,graphite-project/graphite-web,cbowman0/graphite-web,gwaldo/graphite-web,kkdk5535/graphite-web,pu239ppy/graphite-web,criteo-forks/graphite-web,gwaldo/graphite-web,edwardmlyte/graphite-web,drax68/graphite-web,goir/graphite-web,graphite-server/graphite-web,jssjr/graphite-web,Aloomaio/graphite-web,esnet/graphite-web,ceph/graphite-web,criteo-forks/graphite-web,MjAbuz/graphite-web,cgvarela/graphite-web,phreakocious/graphite-web,krux/graphite-web,mcoolive/graphite-web,JeanFred/graphite-web,blacked/graphite-web,slackhappy/graphite-web,piotr1212/graphite-web,MjAbuz/graphite-web,AICIDNN/graphite-web,EinsamHauer/graphite-web-iow,AICIDNN/graphite-web,graphite-project/graphite-web,gwaldo/graphite-web,Talkdesk/graphite-web,piotr1212/graphite-web,bpaquet/graphite-web,cosm0s/graphite-web,MjAbuz/graphite-web,penpen/graphite-web,bpaquet/graphite-web,phreakocious/graphite-web,obfuscurity/graphite-web,AICIDNN/graphite-web,ceph/graphite-web,cbowman0/graphite-web,disqus/graphite-web,g76r/graphite-web,DanCech/graphite-web,bbc/graphite-web,phreakocious/graphite-web,redice/graphite-web,synedge/graphite-web,cgvarela/graphite-web,goir/graphite-web,Invoca/graphite-web,lfckop/graphite-web,pcn/graphite-web,cybem/graphite-web-iow
python
## Code Before: import time import os from django.db import models from django.contrib import admin if os.environ.get('READTHEDOCS'): TagField = lambda *args, **kwargs: None else: from tagging.fields import TagField class Event(models.Model): class Admin: pass when = models.DateTimeField() what = models.CharField(max_length=255) data = models.TextField(blank=True) tags = TagField(default="") def get_tags(self): return Tag.objects.get_for_object(self) def __str__(self): return "%s: %s" % (self.when, self.what) @staticmethod def find_events(time_from=None, time_until=None, tags=None): query = Event.objects.all() if time_from is not None: query = query.filter(when__gte=time_from) if time_until is not None: query = query.filter(when__lte=time_until) if tags is not None: for tag in tags: query = query.filter(tags__iregex=r'\b%s\b' % tag) result = list(query.order_by("when")) return result def as_dict(self): return dict( when=self.when, what=self.what, data=self.data, tags=self.tags, id=self.id, ) ## Instruction: Fix events to work on mysql Closes https://bugs.launchpad.net/graphite/+bug/993625 ## Code After: import time import os from django.db import models from django.contrib import admin from tagging.managers import ModelTaggedItemManager if os.environ.get('READTHEDOCS'): TagField = lambda *args, **kwargs: None else: from tagging.fields import TagField class Event(models.Model): class Admin: pass when = models.DateTimeField() what = models.CharField(max_length=255) data = models.TextField(blank=True) tags = TagField(default="") def get_tags(self): return Tag.objects.get_for_object(self) def __str__(self): return "%s: %s" % (self.when, self.what) @staticmethod def find_events(time_from=None, time_until=None, tags=None): if tags is not None: query = Event.tagged.with_all(tags) else: query = Event.objects.all() if time_from is not None: query = query.filter(when__gte=time_from) if time_until is not None: query = query.filter(when__lte=time_until) result = list(query.order_by("when")) return result def as_dict(self): return dict( when=self.when, what=self.what, data=self.data, tags=self.tags, id=self.id, ) # We use this rather than tagging.register() so that tags can be exposed # in the admin UI ModelTaggedItemManager().contribute_to_class(Event, 'tagged')
# ... existing code ... from django.db import models from django.contrib import admin from tagging.managers import ModelTaggedItemManager if os.environ.get('READTHEDOCS'): TagField = lambda *args, **kwargs: None # ... modified code ... @staticmethod def find_events(time_from=None, time_until=None, tags=None): if tags is not None: query = Event.tagged.with_all(tags) else: query = Event.objects.all() if time_from is not None: query = query.filter(when__gte=time_from) ... if time_until is not None: query = query.filter(when__lte=time_until) result = list(query.order_by("when")) return result ... tags=self.tags, id=self.id, ) # We use this rather than tagging.register() so that tags can be exposed # in the admin UI ModelTaggedItemManager().contribute_to_class(Event, 'tagged') # ... rest of the code ...
ca6b64d41dbefa3c379f06032640a846b4606f12
src/main/java/sourcecoded/core/configuration/gui/SourceConfigBaseGui.java
src/main/java/sourcecoded/core/configuration/gui/SourceConfigBaseGui.java
package sourcecoded.core.configuration.gui; import cpw.mods.fml.client.config.GuiConfig; import net.minecraft.client.gui.GuiScreen; import sourcecoded.core.configuration.SCConfigManager; public class SourceConfigBaseGui extends GuiConfig { public SourceConfigBaseGui(GuiScreen parentScreen) { super(parentScreen, SourceConfigGuiFactory.createElements(SCConfigManager.getConfig()), "sourcecodedcore", false, false, "SourceCodedCore"); } }
package sourcecoded.core.configuration.gui; import cpw.mods.fml.client.config.GuiConfig; import net.minecraft.client.gui.GuiScreen; import sourcecoded.core.configuration.SCConfigManager; public class SourceConfigBaseGui extends GuiConfig { static String modid; static String name; static SourceConfig config; static List<IConfigElement> elements; public SourceConfigBaseGui(GuiScreen parentScreen) { super(parentScreen, elements, modid, false, false, modid); } public static void injectGuiContext(SourceConfigGuiFactory factory) { this.modid = factory.modid; this.name = this.modid; this.config = factory.config; this.elements = SourceConfigGuiFactory.createElements(factory.config); } }
Update BaseGui to use contexts
Update BaseGui to use contexts
Java
apache-2.0
MSourceCoded/SourceCodedCore
java
## Code Before: package sourcecoded.core.configuration.gui; import cpw.mods.fml.client.config.GuiConfig; import net.minecraft.client.gui.GuiScreen; import sourcecoded.core.configuration.SCConfigManager; public class SourceConfigBaseGui extends GuiConfig { public SourceConfigBaseGui(GuiScreen parentScreen) { super(parentScreen, SourceConfigGuiFactory.createElements(SCConfigManager.getConfig()), "sourcecodedcore", false, false, "SourceCodedCore"); } } ## Instruction: Update BaseGui to use contexts ## Code After: package sourcecoded.core.configuration.gui; import cpw.mods.fml.client.config.GuiConfig; import net.minecraft.client.gui.GuiScreen; import sourcecoded.core.configuration.SCConfigManager; public class SourceConfigBaseGui extends GuiConfig { static String modid; static String name; static SourceConfig config; static List<IConfigElement> elements; public SourceConfigBaseGui(GuiScreen parentScreen) { super(parentScreen, elements, modid, false, false, modid); } public static void injectGuiContext(SourceConfigGuiFactory factory) { this.modid = factory.modid; this.name = this.modid; this.config = factory.config; this.elements = SourceConfigGuiFactory.createElements(factory.config); } }
// ... existing code ... public class SourceConfigBaseGui extends GuiConfig { static String modid; static String name; static SourceConfig config; static List<IConfigElement> elements; public SourceConfigBaseGui(GuiScreen parentScreen) { super(parentScreen, elements, modid, false, false, modid); } public static void injectGuiContext(SourceConfigGuiFactory factory) { this.modid = factory.modid; this.name = this.modid; this.config = factory.config; this.elements = SourceConfigGuiFactory.createElements(factory.config); } } // ... rest of the code ...
39ce4e74a6b7115a35260fa2722ace1792cb1780
python/count_triplets.py
python/count_triplets.py
import math import os import random import re import sys from collections import Counter def countTriplets(arr, r): potential_triplets_with_middle = Counter() potential_triplets_with_end = Counter() total_triplets = 0 for num in arr: # num completed potential_triplets_with_end[num] triplets if potential_triplets_with_end[num]: total_triplets += potential_triplets_with_end[num] # num can be the middle number in potential_triplets_with_middle[num] triplets if potential_triplets_with_middle[num]: potential_triplets_with_end[num * r] += potential_triplets_with_middle[num] # num can be the begining of a triplet potential_triplets_with_middle[num * r] += 1 print("num", num, " middle", potential_triplets_with_middle, " end", potential_triplets_with_end, " total", total_triplets) return total_triplets if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) ans = countTriplets(arr, r) fptr.write(str(ans) + '\n') fptr.close()
import math import os import random import re import sys from collections import Counter def countTriplets(arr, r): potential_triplets_with_middle = Counter() potential_triplets_with_end = Counter() total_triplets = 0 for num in arr: # num completed potential_triplets_with_end[num] triplets if potential_triplets_with_end[num]: total_triplets += potential_triplets_with_end[num] # num can be the middle number in # potential_triplets_with_middle[num] triplets if potential_triplets_with_middle[num]: potential_triplets_with_end[num * r] += \ potential_triplets_with_middle[num] # num can be the begining of a triplet potential_triplets_with_middle[num * r] += 1 return total_triplets if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) ans = countTriplets(arr, r) fptr.write(str(ans) + '\n') fptr.close()
Remove debug output and pycodestyle
Remove debug output and pycodestyle
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
python
## Code Before: import math import os import random import re import sys from collections import Counter def countTriplets(arr, r): potential_triplets_with_middle = Counter() potential_triplets_with_end = Counter() total_triplets = 0 for num in arr: # num completed potential_triplets_with_end[num] triplets if potential_triplets_with_end[num]: total_triplets += potential_triplets_with_end[num] # num can be the middle number in potential_triplets_with_middle[num] triplets if potential_triplets_with_middle[num]: potential_triplets_with_end[num * r] += potential_triplets_with_middle[num] # num can be the begining of a triplet potential_triplets_with_middle[num * r] += 1 print("num", num, " middle", potential_triplets_with_middle, " end", potential_triplets_with_end, " total", total_triplets) return total_triplets if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) ans = countTriplets(arr, r) fptr.write(str(ans) + '\n') fptr.close() ## Instruction: Remove debug output and pycodestyle ## Code After: import math import os import random import re import sys from collections import Counter def countTriplets(arr, r): potential_triplets_with_middle = Counter() potential_triplets_with_end = Counter() total_triplets = 0 for num in arr: # num completed potential_triplets_with_end[num] triplets if potential_triplets_with_end[num]: total_triplets += potential_triplets_with_end[num] # num can be the middle number in # potential_triplets_with_middle[num] triplets if potential_triplets_with_middle[num]: potential_triplets_with_end[num * r] += \ potential_triplets_with_middle[num] # num can be the begining of a triplet potential_triplets_with_middle[num * r] += 1 return total_triplets if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) ans = countTriplets(arr, r) fptr.write(str(ans) + '\n') fptr.close()
# ... existing code ... import re import sys from collections import Counter def countTriplets(arr, r): potential_triplets_with_middle = Counter() # ... modified code ... if potential_triplets_with_end[num]: total_triplets += potential_triplets_with_end[num] # num can be the middle number in # potential_triplets_with_middle[num] triplets if potential_triplets_with_middle[num]: potential_triplets_with_end[num * r] += \ potential_triplets_with_middle[num] # num can be the begining of a triplet potential_triplets_with_middle[num * r] += 1 return total_triplets # ... rest of the code ...
87cb18e12a296a1e29dbfb692d5c5d528c0f59e3
src/test/java/com/example/activity/MainActivityTest.java
src/test/java/com/example/activity/MainActivityTest.java
package com.example.activity; import android.app.Activity; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import static org.junit.Assert.assertTrue; @RunWith(RobolectricTestRunner.class) public class MainActivityTest { @org.junit.Test public void testSomething() throws Exception { Activity activity = Robolectric.setupActivity(MainActivity.class); assertTrue(activity.getTitle().toString().equals("Deckard")); } }
package com.example.activity; import android.app.Activity; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import static org.junit.Assert.assertTrue; @RunWith(RobolectricTestRunner.class) public class MainActivityTest { @org.junit.Test public void titleIsCorrect() throws Exception { Activity activity = Robolectric.setupActivity(MainActivity.class); assertTrue(activity.getTitle().toString().equals("Deckard")); } }
Rename test to be correct
Rename test to be correct
Java
unlicense
robolectric/deckard-maven,robolectric/deckard-maven
java
## Code Before: package com.example.activity; import android.app.Activity; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import static org.junit.Assert.assertTrue; @RunWith(RobolectricTestRunner.class) public class MainActivityTest { @org.junit.Test public void testSomething() throws Exception { Activity activity = Robolectric.setupActivity(MainActivity.class); assertTrue(activity.getTitle().toString().equals("Deckard")); } } ## Instruction: Rename test to be correct ## Code After: package com.example.activity; import android.app.Activity; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import static org.junit.Assert.assertTrue; @RunWith(RobolectricTestRunner.class) public class MainActivityTest { @org.junit.Test public void titleIsCorrect() throws Exception { Activity activity = Robolectric.setupActivity(MainActivity.class); assertTrue(activity.getTitle().toString().equals("Deckard")); } }
# ... existing code ... public class MainActivityTest { @org.junit.Test public void titleIsCorrect() throws Exception { Activity activity = Robolectric.setupActivity(MainActivity.class); assertTrue(activity.getTitle().toString().equals("Deckard")); } # ... rest of the code ...
261cb5aecc52d07b10d826e8b22d17817d1c3529
web/backend/backend_django/apps/capacity/management/commands/importpath.py
web/backend/backend_django/apps/capacity/management/commands/importpath.py
from __future__ import unicode_literals from optparse import make_option import os from csv import reader from codecs import BOM_UTF8 import pickle from django.utils.six import string_types, PY3 from django.core.management.base import BaseCommand, CommandError from ...models import Path class Command(BaseCommand): help = 'Encode txt files in ascii format' def add_arguments(self, parser): parser.add_argument('--input', '-i', help='input file as pickle') def handle(self, *args, **options): i = options['input'] if not os.path.isfile(i): raise CommandError trips = pickle.load(open(i, "rb")) print(len(trips)) for k, path in trips.items(): trip_id = k[0] stop_id = k[1] try: _, created = Path.objects.get_or_create( trip_id = int(trip_id), stop_id = int(stop_id), path = str(path) ) pass except Exception as e: self.stdout.write("Error with row {} {} : {}".format(k, path, e)) self.stdout.write("Done")
from __future__ import unicode_literals from optparse import make_option import os from csv import reader from codecs import BOM_UTF8 import pickle from django.utils.six import string_types, PY3 from django.core.management.base import BaseCommand, CommandError from ...models import Path class Command(BaseCommand): help = 'Encode txt files in ascii format' def add_arguments(self, parser): parser.add_argument('--input', '-i', help='input file as pickle') def handle(self, *args, **options): i = options['input'] if not os.path.isfile(i): raise CommandError trips = pickle.load(open(i, "rb")) print(len(trips)) i = 0 for k, path in trips.items(): trip_id = k[0] stop_id = k[1] if i%1000==0: print(i) try: _, created = Path.objects.get_or_create( trip_id = int(trip_id), stop_id = int(stop_id), path = str(path) ) pass except Exception as e: self.stdout.write("Error with row {} {} : {}".format(k, path, e)) i = i+1 self.stdout.write("Done")
Update import path method to reflect behaviour
Update import path method to reflect behaviour
Python
apache-2.0
tOverney/ADA-Project,tOverney/ADA-Project,tOverney/ADA-Project
python
## Code Before: from __future__ import unicode_literals from optparse import make_option import os from csv import reader from codecs import BOM_UTF8 import pickle from django.utils.six import string_types, PY3 from django.core.management.base import BaseCommand, CommandError from ...models import Path class Command(BaseCommand): help = 'Encode txt files in ascii format' def add_arguments(self, parser): parser.add_argument('--input', '-i', help='input file as pickle') def handle(self, *args, **options): i = options['input'] if not os.path.isfile(i): raise CommandError trips = pickle.load(open(i, "rb")) print(len(trips)) for k, path in trips.items(): trip_id = k[0] stop_id = k[1] try: _, created = Path.objects.get_or_create( trip_id = int(trip_id), stop_id = int(stop_id), path = str(path) ) pass except Exception as e: self.stdout.write("Error with row {} {} : {}".format(k, path, e)) self.stdout.write("Done") ## Instruction: Update import path method to reflect behaviour ## Code After: from __future__ import unicode_literals from optparse import make_option import os from csv import reader from codecs import BOM_UTF8 import pickle from django.utils.six import string_types, PY3 from django.core.management.base import BaseCommand, CommandError from ...models import Path class Command(BaseCommand): help = 'Encode txt files in ascii format' def add_arguments(self, parser): parser.add_argument('--input', '-i', help='input file as pickle') def handle(self, *args, **options): i = options['input'] if not os.path.isfile(i): raise CommandError trips = pickle.load(open(i, "rb")) print(len(trips)) i = 0 for k, path in trips.items(): trip_id = k[0] stop_id = k[1] if i%1000==0: print(i) try: _, created = Path.objects.get_or_create( trip_id = int(trip_id), stop_id = int(stop_id), path = str(path) ) pass except Exception as e: self.stdout.write("Error with row {} {} : {}".format(k, path, e)) i = i+1 self.stdout.write("Done")
// ... existing code ... trips = pickle.load(open(i, "rb")) print(len(trips)) i = 0 for k, path in trips.items(): trip_id = k[0] stop_id = k[1] if i%1000==0: print(i) try: _, created = Path.objects.get_or_create( // ... modified code ... except Exception as e: self.stdout.write("Error with row {} {} : {}".format(k, path, e)) i = i+1 self.stdout.write("Done") // ... rest of the code ...
55a330149a05c456012f2570c2151a82ac8435b2
images/singleuser/user-config.py
images/singleuser/user-config.py
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable for fam in ( 'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia', 'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity', 'wikidata', 'mediawiki' ): usernames[fam]['*'] = os.environ['USER'] if 'ACCESS_KEY' in os.environ: # If OAuth integration is available, take it authenticate.setdefault(fam, {})['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] ) del fam
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable for fam in ( 'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia', 'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity', 'wikidata', 'mediawiki' ): usernames[fam]['*'] = os.environ['USER'] del fam # If OAuth integration is available, take it if 'CLIENT_ID' in os.environ: authenticate['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] )
Revert to previous way of setting 'authenticate'
Revert to previous way of setting 'authenticate' This reverts commit a055f97a342f670171f30095cabfd4ba1bfdad17. This reverts commit 4cec5250a3f9058fea5af5ef432a5b230ca94963.
Python
mit
yuvipanda/paws,yuvipanda/paws
python
## Code Before: import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable for fam in ( 'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia', 'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity', 'wikidata', 'mediawiki' ): usernames[fam]['*'] = os.environ['USER'] if 'ACCESS_KEY' in os.environ: # If OAuth integration is available, take it authenticate.setdefault(fam, {})['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] ) del fam ## Instruction: Revert to previous way of setting 'authenticate' This reverts commit a055f97a342f670171f30095cabfd4ba1bfdad17. This reverts commit 4cec5250a3f9058fea5af5ef432a5b230ca94963. ## Code After: import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'rb') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) del f # Clean up temp variables, since pwb issues a warning otherwise # to help people catch misspelt config del custom_path # Things that should be non-easily-overridable for fam in ( 'wikipedia', 'commons', 'meta', 'wikiboots', 'wikimedia', 'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity', 'wikidata', 'mediawiki' ): usernames[fam]['*'] = os.environ['USER'] del fam # If OAuth integration is available, take it if 'CLIENT_ID' in os.environ: authenticate['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] )
# ... existing code ... 'wikiquote', 'wikisource', 'wikisource', 'wiktionary', 'wikiversity', 'wikidata', 'mediawiki' ): usernames[fam]['*'] = os.environ['USER'] del fam # If OAuth integration is available, take it if 'CLIENT_ID' in os.environ: authenticate['*'] = ( os.environ['CLIENT_ID'], os.environ['CLIENT_SECRET'], os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRET'] ) # ... rest of the code ...
1d8185ed29d448ae181779913b8a0c4f513a799c
opsimulate/constants.py
opsimulate/constants.py
KEYS_DIR_NAME = './keys' PRIVATE_KEY_FILE = '{}/opsimulate'.format(KEYS_DIR_NAME) PUBLIC_KEY_FILE = '{}/opsimulate.pub'.format(KEYS_DIR_NAME) SERVICE_ACCOUNT_FILE = 'service-account.json' ZONE = 'us-east4-a' MACHINE_TYPE = 'n1-standard-1' UBUNTU_VERSION = 'ubuntu-1404-lts' INSTANCE_NAME = 'opsimulate-gitlab' VM_USERNAME = 'opsimulate'
import os HOME = os.path.expanduser("~") OPSIMULATE_HOME = os.path.join(HOME, '.opsimulate') KEYS_DIR_NAME = os.path.join(OPSIMULATE_HOME, 'keys') PRIVATE_KEY_FILE = os.path.join(KEYS_DIR_NAME, 'opsimulate') PUBLIC_KEY_FILE = os.path.join(KEYS_DIR_NAME, 'opsimulate.pub') SERVICE_ACCOUNT_FILE = os.path.join(OPSIMULATE_HOME, 'service-account.json') ZONE = 'us-east4-a' MACHINE_TYPE = 'n1-standard-1' UBUNTU_VERSION = 'ubuntu-1404-lts' INSTANCE_NAME = 'opsimulate-gitlab' VM_USERNAME = 'opsimulate'
Install keys and service-account.json in ~/.opsimulate directory
Install keys and service-account.json in ~/.opsimulate directory - This ensures that opsimulate can be ran as a regular pip installed CLI tool and not just via pip -e or direct script invocation
Python
mit
RochesterinNYC/opsimulate,RochesterinNYC/opsimulate
python
## Code Before: KEYS_DIR_NAME = './keys' PRIVATE_KEY_FILE = '{}/opsimulate'.format(KEYS_DIR_NAME) PUBLIC_KEY_FILE = '{}/opsimulate.pub'.format(KEYS_DIR_NAME) SERVICE_ACCOUNT_FILE = 'service-account.json' ZONE = 'us-east4-a' MACHINE_TYPE = 'n1-standard-1' UBUNTU_VERSION = 'ubuntu-1404-lts' INSTANCE_NAME = 'opsimulate-gitlab' VM_USERNAME = 'opsimulate' ## Instruction: Install keys and service-account.json in ~/.opsimulate directory - This ensures that opsimulate can be ran as a regular pip installed CLI tool and not just via pip -e or direct script invocation ## Code After: import os HOME = os.path.expanduser("~") OPSIMULATE_HOME = os.path.join(HOME, '.opsimulate') KEYS_DIR_NAME = os.path.join(OPSIMULATE_HOME, 'keys') PRIVATE_KEY_FILE = os.path.join(KEYS_DIR_NAME, 'opsimulate') PUBLIC_KEY_FILE = os.path.join(KEYS_DIR_NAME, 'opsimulate.pub') SERVICE_ACCOUNT_FILE = os.path.join(OPSIMULATE_HOME, 'service-account.json') ZONE = 'us-east4-a' MACHINE_TYPE = 'n1-standard-1' UBUNTU_VERSION = 'ubuntu-1404-lts' INSTANCE_NAME = 'opsimulate-gitlab' VM_USERNAME = 'opsimulate'
# ... existing code ... import os HOME = os.path.expanduser("~") OPSIMULATE_HOME = os.path.join(HOME, '.opsimulate') KEYS_DIR_NAME = os.path.join(OPSIMULATE_HOME, 'keys') PRIVATE_KEY_FILE = os.path.join(KEYS_DIR_NAME, 'opsimulate') PUBLIC_KEY_FILE = os.path.join(KEYS_DIR_NAME, 'opsimulate.pub') SERVICE_ACCOUNT_FILE = os.path.join(OPSIMULATE_HOME, 'service-account.json') ZONE = 'us-east4-a' MACHINE_TYPE = 'n1-standard-1' # ... rest of the code ...
86968b5bc34a0c7f75ff04ad261ee59da8dcf94f
app/soc/models/host.py
app/soc/models/host.py
"""This module contains the Host Model.""" __authors__ = [ '"Todd Larsen" <[email protected]>', '"Sverre Rabbelier" <[email protected]>', ] import soc.models.role import soc.models.sponsor class Host(soc.models.role.Role): """Host details for a specific Program. """ pass
"""This module contains the Model for Host.""" __authors__ = [ '"Madhusudan.C.S" <[email protected]>', ] from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.base class Host(soc.models.base.ModelWithFieldAttributes): """Model containing host specific data. The User entity corresponding to this host will be the parent of this entity. """ notify_slot_transfer = db.BooleanProperty(required=False, default=True, verbose_name=ugettext('Notify of slot transfer updates')) notify_slot_transfer.help_text = ugettext( 'Whether to send an email notification when slot transfer requests ' 'are made or updated.') notify_slot_transfer.group = ugettext("1. Notification settings")
Replace the old Host model with a new one.
Replace the old Host model with a new one. The new Host model doesn't need the host user to have a profile. Instead it will contain the user to whom the Host entity belongs to as the parent of the Host entity to maintain transactionality between User and Host updates. --HG-- extra : rebase_source : cee68153ab1cfdb77cc955f14ae8f7ef02d5157a
Python
apache-2.0
rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son
python
## Code Before: """This module contains the Host Model.""" __authors__ = [ '"Todd Larsen" <[email protected]>', '"Sverre Rabbelier" <[email protected]>', ] import soc.models.role import soc.models.sponsor class Host(soc.models.role.Role): """Host details for a specific Program. """ pass ## Instruction: Replace the old Host model with a new one. The new Host model doesn't need the host user to have a profile. Instead it will contain the user to whom the Host entity belongs to as the parent of the Host entity to maintain transactionality between User and Host updates. --HG-- extra : rebase_source : cee68153ab1cfdb77cc955f14ae8f7ef02d5157a ## Code After: """This module contains the Model for Host.""" __authors__ = [ '"Madhusudan.C.S" <[email protected]>', ] from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.base class Host(soc.models.base.ModelWithFieldAttributes): """Model containing host specific data. The User entity corresponding to this host will be the parent of this entity. """ notify_slot_transfer = db.BooleanProperty(required=False, default=True, verbose_name=ugettext('Notify of slot transfer updates')) notify_slot_transfer.help_text = ugettext( 'Whether to send an email notification when slot transfer requests ' 'are made or updated.') notify_slot_transfer.group = ugettext("1. Notification settings")
# ... existing code ... """This module contains the Model for Host.""" __authors__ = [ '"Madhusudan.C.S" <[email protected]>', ] from google.appengine.ext import db from django.utils.translation import ugettext import soc.models.base class Host(soc.models.base.ModelWithFieldAttributes): """Model containing host specific data. The User entity corresponding to this host will be the parent of this entity. """ notify_slot_transfer = db.BooleanProperty(required=False, default=True, verbose_name=ugettext('Notify of slot transfer updates')) notify_slot_transfer.help_text = ugettext( 'Whether to send an email notification when slot transfer requests ' 'are made or updated.') notify_slot_transfer.group = ugettext("1. Notification settings") # ... rest of the code ...
4bebc9b686b29f2a068dd90b2024960dcf5e19a2
setup.py
setup.py
from codecs import open import os.path as osp from setuptools import setup, find_packages import strumenti here = osp.abspath(osp.dirname(__file__)) with open(osp.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='strumenti', version='1.0.0', description='Common tools universally applicable to Python 3 packages.', author='Timothy Helton', author_email='[email protected]', license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Build Tools', ], keywords='common tools utility', packages=find_packages(exclude=['docs', 'tests*']), install_requires=[ 'matplotlib', 'numpy', 'Pint', 'psycopg2', 'pytest', 'termcolor', 'wrapt', ], package_dir={'strumenti': 'strumenti'}, include_package_data=True, ) if __name__ == '__main__': pass
from codecs import open import os.path as osp from setuptools import setup, find_packages import strumenti here = osp.abspath(osp.dirname(__file__)) with open(osp.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='strumenti', version='1.0.0', description='Common tools universally applicable to Python 3 packages.', author='Timothy Helton', author_email='[email protected]', license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Build Tools', ], keywords='common tools utility', packages=find_packages(exclude=['docs', 'tests*']), install_requires=[ 'matplotlib', 'numpy', 'Pint', 'psycopg2', 'pytest', 'termcolor', 'wrapt', 'wrapt.decorator', ], package_dir={'strumenti': 'strumenti'}, include_package_data=True, ) if __name__ == '__main__': pass
Test wrapt.document for Read the Docs
Test wrapt.document for Read the Docs
Python
bsd-3-clause
TimothyHelton/strumenti
python
## Code Before: from codecs import open import os.path as osp from setuptools import setup, find_packages import strumenti here = osp.abspath(osp.dirname(__file__)) with open(osp.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='strumenti', version='1.0.0', description='Common tools universally applicable to Python 3 packages.', author='Timothy Helton', author_email='[email protected]', license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Build Tools', ], keywords='common tools utility', packages=find_packages(exclude=['docs', 'tests*']), install_requires=[ 'matplotlib', 'numpy', 'Pint', 'psycopg2', 'pytest', 'termcolor', 'wrapt', ], package_dir={'strumenti': 'strumenti'}, include_package_data=True, ) if __name__ == '__main__': pass ## Instruction: Test wrapt.document for Read the Docs ## Code After: from codecs import open import os.path as osp from setuptools import setup, find_packages import strumenti here = osp.abspath(osp.dirname(__file__)) with open(osp.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='strumenti', version='1.0.0', description='Common tools universally applicable to Python 3 packages.', author='Timothy Helton', author_email='[email protected]', license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Build Tools', ], keywords='common tools utility', packages=find_packages(exclude=['docs', 'tests*']), install_requires=[ 'matplotlib', 'numpy', 'Pint', 'psycopg2', 'pytest', 'termcolor', 'wrapt', 'wrapt.decorator', ], package_dir={'strumenti': 'strumenti'}, include_package_data=True, ) if __name__ == '__main__': pass
... 'pytest', 'termcolor', 'wrapt', 'wrapt.decorator', ], package_dir={'strumenti': 'strumenti'}, include_package_data=True, ...
3b09a6a7faae7363ffc90749e041788a17559f0f
src/test/tester.c
src/test/tester.c
static void clean_test_environment(void) { efi_del_variable(TEST_GUID, "small"); efi_del_variable(TEST_GUID, "large"); } #define report_error(str) ({fprintf(stderr, str); goto fail;}) int main(void) { if (!efi_variables_supported()) { printf("UEFI variables not supported on this machine.\n"); return 0; } clean_test_environment(); int ret = 1; char smallvalue[] = "smallvalue"; int rc; rc = efi_set_variable(TEST_GUID, "small", smallvalue, strlen(smallvalue)+1, EFI_VARIABLE_RUNTIME_ACCESS); if (rc < 0) report_error("small value test failed: %m\n"); ret = 0; fail: return ret; }
static void clean_test_environment(void) { efi_del_variable(TEST_GUID, "small"); efi_del_variable(TEST_GUID, "large"); } #define report_error(str) ({fprintf(stderr, str); goto fail;}) int main(void) { if (!efi_variables_supported()) { printf("UEFI variables not supported on this machine.\n"); return 0; } clean_test_environment(); int ret = 1; char smallvalue[] = "smallvalue"; int rc; rc = efi_set_variable(TEST_GUID, "small", smallvalue, strlen(smallvalue)+1, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE); if (rc < 0) report_error("small value test failed: %m\n"); ret = 0; fail: return ret; }
Use flags that will actually work when testing.
Use flags that will actually work when testing.
C
lgpl-2.1
rhboot/efivar,rhinstaller/efivar,android-ia/vendor_intel_external_efivar,rhinstaller/efivar,rhboot/efivar,CyanogenMod/android_vendor_intel_external_efivar,vathpela/efivar-devel
c
## Code Before: static void clean_test_environment(void) { efi_del_variable(TEST_GUID, "small"); efi_del_variable(TEST_GUID, "large"); } #define report_error(str) ({fprintf(stderr, str); goto fail;}) int main(void) { if (!efi_variables_supported()) { printf("UEFI variables not supported on this machine.\n"); return 0; } clean_test_environment(); int ret = 1; char smallvalue[] = "smallvalue"; int rc; rc = efi_set_variable(TEST_GUID, "small", smallvalue, strlen(smallvalue)+1, EFI_VARIABLE_RUNTIME_ACCESS); if (rc < 0) report_error("small value test failed: %m\n"); ret = 0; fail: return ret; } ## Instruction: Use flags that will actually work when testing. ## Code After: static void clean_test_environment(void) { efi_del_variable(TEST_GUID, "small"); efi_del_variable(TEST_GUID, "large"); } #define report_error(str) ({fprintf(stderr, str); goto fail;}) int main(void) { if (!efi_variables_supported()) { printf("UEFI variables not supported on this machine.\n"); return 0; } clean_test_environment(); int ret = 1; char smallvalue[] = "smallvalue"; int rc; rc = efi_set_variable(TEST_GUID, "small", smallvalue, strlen(smallvalue)+1, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE); if (rc < 0) report_error("small value test failed: %m\n"); ret = 0; fail: return ret; }
... int rc; rc = efi_set_variable(TEST_GUID, "small", smallvalue, strlen(smallvalue)+1, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE); if (rc < 0) report_error("small value test failed: %m\n"); ...
2fa1c13c35e1ef5093ca734dae62d89572f06eaf
alura/c/forca.c
alura/c/forca.c
int main() { char palavrasecreta[20]; sprintf(palavrasecreta, "MELANCIA"); int acertou = 0; int enforcou = 0; do { // comecar o nosso jogo!! } while(!acertou && !enforcou); }
int main() { char palavrasecreta[20]; sprintf(palavrasecreta, "MELANCIA"); int acertou = 0; int enforcou = 0; do { char chute; scanf("%c", &chute); for(int i = 0; i < strlen(palavrasecreta); i++) { if(palavrasecreta[i] == chute) { printf("A posição %d tem essa letra!\n", i); } } } while(!acertou && !enforcou); }
Update files, Alura, Introdução a C - Parte 2, Aula 2.4
Update files, Alura, Introdução a C - Parte 2, Aula 2.4
C
mit
fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs
c
## Code Before: int main() { char palavrasecreta[20]; sprintf(palavrasecreta, "MELANCIA"); int acertou = 0; int enforcou = 0; do { // comecar o nosso jogo!! } while(!acertou && !enforcou); } ## Instruction: Update files, Alura, Introdução a C - Parte 2, Aula 2.4 ## Code After: int main() { char palavrasecreta[20]; sprintf(palavrasecreta, "MELANCIA"); int acertou = 0; int enforcou = 0; do { char chute; scanf("%c", &chute); for(int i = 0; i < strlen(palavrasecreta); i++) { if(palavrasecreta[i] == chute) { printf("A posição %d tem essa letra!\n", i); } } } while(!acertou && !enforcou); }
... int enforcou = 0; do { char chute; scanf("%c", &chute); for(int i = 0; i < strlen(palavrasecreta); i++) { if(palavrasecreta[i] == chute) { printf("A posição %d tem essa letra!\n", i); } } } while(!acertou && !enforcou); ...
f2ea241e9bb6e5e927a90c56438bf7883ae3744f
siemstress/__init__.py
siemstress/__init__.py
__version__ = '0.2' __author__ = 'Dan Persons <[email protected]>' __license__ = 'MIT License' __github__ = 'https://github.com/dogoncouch/siemstress' __all__ = ['core', 'querycore', 'query'] import siemstress.query
__version__ = '0.2' __author__ = 'Dan Persons <[email protected]>' __license__ = 'MIT License' __github__ = 'https://github.com/dogoncouch/siemstress' __all__ = ['core', 'querycore', 'query'] import siemstress.query import siemstress.trigger
Add trigger to module import
Add trigger to module import
Python
mit
dogoncouch/siemstress
python
## Code Before: __version__ = '0.2' __author__ = 'Dan Persons <[email protected]>' __license__ = 'MIT License' __github__ = 'https://github.com/dogoncouch/siemstress' __all__ = ['core', 'querycore', 'query'] import siemstress.query ## Instruction: Add trigger to module import ## Code After: __version__ = '0.2' __author__ = 'Dan Persons <[email protected]>' __license__ = 'MIT License' __github__ = 'https://github.com/dogoncouch/siemstress' __all__ = ['core', 'querycore', 'query'] import siemstress.query import siemstress.trigger
// ... existing code ... __all__ = ['core', 'querycore', 'query'] import siemstress.query import siemstress.trigger // ... rest of the code ...
88d1274638e1f4d0341c5e55bdb729ae52c2b607
accounts/models.py
accounts/models.py
from github import Github from django.contrib.auth.models import User from tools.decorators import extend @extend(User) class Profile(object): """Add shortcuts to user""" @property def github(self): """Github api instance with access from user""" token = self.social_auth.get().extra_data['access_token'] return Github(token)
from github import Github from django.contrib.auth.models import User from tools.decorators import extend @extend(User) class Profile(object): """Add shortcuts to user""" @property def github(self): """Github api instance with access from user""" return Github(self.github_token) @property def github_token(self): """Get github api token""" return self.social_auth.get().extra_data['access_token']
Add ability to get github token from user model
Add ability to get github token from user model
Python
mit
nvbn/coviolations_web,nvbn/coviolations_web
python
## Code Before: from github import Github from django.contrib.auth.models import User from tools.decorators import extend @extend(User) class Profile(object): """Add shortcuts to user""" @property def github(self): """Github api instance with access from user""" token = self.social_auth.get().extra_data['access_token'] return Github(token) ## Instruction: Add ability to get github token from user model ## Code After: from github import Github from django.contrib.auth.models import User from tools.decorators import extend @extend(User) class Profile(object): """Add shortcuts to user""" @property def github(self): """Github api instance with access from user""" return Github(self.github_token) @property def github_token(self): """Get github api token""" return self.social_auth.get().extra_data['access_token']
... @property def github(self): """Github api instance with access from user""" return Github(self.github_token) @property def github_token(self): """Get github api token""" return self.social_auth.get().extra_data['access_token'] ...
c262e1d4c1c7422675728298019ee674242b68dd
examples/framework/faren/faren.py
examples/framework/faren/faren.py
import gtk from kiwi.controllers import BaseController from kiwi.ui.views import BaseView from kiwi.ui.gadgets import quit_if_last class FarenControl(BaseController): def on_quitbutton__clicked(self, *args): self.view.hide_and_quit() def after_temperature__changed(self, entry, *args): try: temp = float(entry.get_text()) except ValueError: temp = 0 celsius = (temp - 32) * 5/9.0 farenheit = (temp * 9/5.0) + 32 self.view.celsius.set_text("%.2f" % celsius) self.view.farenheit.set_text("%.2f" % farenheit) widgets = ["quitbutton", "temperature", "celsius", "farenheit"] view = BaseView(gladefile="faren", delete_handler=quit_if_last, widgets=widgets) ctl = FarenControl(view) view.show() gtk.main()
import gtk from kiwi.controllers import BaseController from kiwi.ui.views import BaseView from kiwi.ui.gadgets import quit_if_last class FarenControl(BaseController): def on_quitbutton__clicked(self, *args): self.view.hide_and_quit() def after_temperature__insert_text(self, entry, *args): try: temp = float(entry.get_text()) except ValueError: temp = 0 celsius = (temp - 32) * 5/9.0 farenheit = (temp * 9/5.0) + 32 self.view.celsius.set_text("%.2f" % celsius) self.view.farenheit.set_text("%.2f" % farenheit) widgets = ["quitbutton", "temperature", "celsius", "farenheit"] view = BaseView(gladefile="faren", delete_handler=quit_if_last, widgets=widgets) ctl = FarenControl(view) view.show() gtk.main()
Use insert_text instead of changed
Use insert_text instead of changed
Python
lgpl-2.1
Schevo/kiwi,Schevo/kiwi,Schevo/kiwi
python
## Code Before: import gtk from kiwi.controllers import BaseController from kiwi.ui.views import BaseView from kiwi.ui.gadgets import quit_if_last class FarenControl(BaseController): def on_quitbutton__clicked(self, *args): self.view.hide_and_quit() def after_temperature__changed(self, entry, *args): try: temp = float(entry.get_text()) except ValueError: temp = 0 celsius = (temp - 32) * 5/9.0 farenheit = (temp * 9/5.0) + 32 self.view.celsius.set_text("%.2f" % celsius) self.view.farenheit.set_text("%.2f" % farenheit) widgets = ["quitbutton", "temperature", "celsius", "farenheit"] view = BaseView(gladefile="faren", delete_handler=quit_if_last, widgets=widgets) ctl = FarenControl(view) view.show() gtk.main() ## Instruction: Use insert_text instead of changed ## Code After: import gtk from kiwi.controllers import BaseController from kiwi.ui.views import BaseView from kiwi.ui.gadgets import quit_if_last class FarenControl(BaseController): def on_quitbutton__clicked(self, *args): self.view.hide_and_quit() def after_temperature__insert_text(self, entry, *args): try: temp = float(entry.get_text()) except ValueError: temp = 0 celsius = (temp - 32) * 5/9.0 farenheit = (temp * 9/5.0) + 32 self.view.celsius.set_text("%.2f" % celsius) self.view.farenheit.set_text("%.2f" % farenheit) widgets = ["quitbutton", "temperature", "celsius", "farenheit"] view = BaseView(gladefile="faren", delete_handler=quit_if_last, widgets=widgets) ctl = FarenControl(view) view.show() gtk.main()
// ... existing code ... def on_quitbutton__clicked(self, *args): self.view.hide_and_quit() def after_temperature__insert_text(self, entry, *args): try: temp = float(entry.get_text()) except ValueError: // ... rest of the code ...
b5a8e7b6926bf7224abed6bd335d62b3f1ad1fb1
performance_testing/command_line.py
performance_testing/command_line.py
import os import yaml from performance_testing.errors import ConfigFileError, ConfigKeyError from performance_testing import web from datetime import datetime as date from time import time class Tool: def __init__(self, config='config.yml', result_directory='result'): self.read_config(config_file=config) self.create_result_file(directory=result_directory) def read_config(self, config_file): try: config_stream = open(config_file, 'r') config_data = yaml.load(config_stream) config_stream.close() self.host = config_data['host'] self.requests = config_data['requests'] self.clients = config_data['clients'] self.time = config_data['time'] self.urls = config_data['urls'] except KeyError as ex: raise ConfigKeyError(ex.args[0]) except IOError: raise ConfigFileError(config_file) def create_result_file(self, directory): datetime = date.fromtimestamp(time()) file_name = '%d-%d-%d_%d-%d-%d' % (datetime.year, datetime.month, datetime.day, datetime.hour, datetime.minute, datetime.second) file_path = os.path.join(directory, file_name) if not os.path.exists(directory): os.makedirs(directory) open(file_path, 'a').close() self.result_file = file_path def start_testing(self): pass def run(self): file_stream = open(self.result_file, 'w') print('Start tests ...') for url in self.urls: full_url = self.host + url file_stream.write('URL: %s\n' % url) for i in range(0, self.requests): file_stream.write(' %i - %.3f\n' % (i, web.request(full_url))) print('Finished tests!')
import os import yaml from performance_testing.errors import ConfigFileError, ConfigKeyError from performance_testing import web from performance_testing.config import Config from performance_testing.result import Result class Tool: def __init__(self, config='config.yml', result_directory='result'): self.config = Config(config_path=config) self.result = Result(result_directory) def start_testing(self): pass def run(self): print('Start tests ...') for url in self.config.urls: full_url = self.config.host + url self.result.file.write_line('URL: %s\n' % url) for i in range(0, self.config.requests): self.result.file.write_line(' %i - %.3f\n' % (i, web.request(full_url))) print('Finished tests!')
Use Config and Result class in Tool
Use Config and Result class in Tool
Python
mit
BakeCode/performance-testing,BakeCode/performance-testing
python
## Code Before: import os import yaml from performance_testing.errors import ConfigFileError, ConfigKeyError from performance_testing import web from datetime import datetime as date from time import time class Tool: def __init__(self, config='config.yml', result_directory='result'): self.read_config(config_file=config) self.create_result_file(directory=result_directory) def read_config(self, config_file): try: config_stream = open(config_file, 'r') config_data = yaml.load(config_stream) config_stream.close() self.host = config_data['host'] self.requests = config_data['requests'] self.clients = config_data['clients'] self.time = config_data['time'] self.urls = config_data['urls'] except KeyError as ex: raise ConfigKeyError(ex.args[0]) except IOError: raise ConfigFileError(config_file) def create_result_file(self, directory): datetime = date.fromtimestamp(time()) file_name = '%d-%d-%d_%d-%d-%d' % (datetime.year, datetime.month, datetime.day, datetime.hour, datetime.minute, datetime.second) file_path = os.path.join(directory, file_name) if not os.path.exists(directory): os.makedirs(directory) open(file_path, 'a').close() self.result_file = file_path def start_testing(self): pass def run(self): file_stream = open(self.result_file, 'w') print('Start tests ...') for url in self.urls: full_url = self.host + url file_stream.write('URL: %s\n' % url) for i in range(0, self.requests): file_stream.write(' %i - %.3f\n' % (i, web.request(full_url))) print('Finished tests!') ## Instruction: Use Config and Result class in Tool ## Code After: import os import yaml from performance_testing.errors import ConfigFileError, ConfigKeyError from performance_testing import web from performance_testing.config import Config from performance_testing.result import Result class Tool: def __init__(self, config='config.yml', result_directory='result'): self.config = Config(config_path=config) self.result = Result(result_directory) def start_testing(self): pass def run(self): print('Start tests ...') for url in self.config.urls: full_url = self.config.host + url self.result.file.write_line('URL: %s\n' % url) for i in range(0, self.config.requests): self.result.file.write_line(' %i - %.3f\n' % (i, web.request(full_url))) print('Finished tests!')
# ... existing code ... import yaml from performance_testing.errors import ConfigFileError, ConfigKeyError from performance_testing import web from performance_testing.config import Config from performance_testing.result import Result class Tool: def __init__(self, config='config.yml', result_directory='result'): self.config = Config(config_path=config) self.result = Result(result_directory) def start_testing(self): pass def run(self): print('Start tests ...') for url in self.config.urls: full_url = self.config.host + url self.result.file.write_line('URL: %s\n' % url) for i in range(0, self.config.requests): self.result.file.write_line(' %i - %.3f\n' % (i, web.request(full_url))) print('Finished tests!') # ... rest of the code ...
fb9c56381d259de7d1765ca0e058f82d61e4e975
examples/ellipses_FreeCAD.py
examples/ellipses_FreeCAD.py
from __future__ import division import numpy as np import FreeCAD as FC import Part import Draft import os doc = FC.newDocument("ellipses") folder = os.path.dirname(__file__) + ".\.." fname = folder + "/vor_ellipses.txt" data = np.loadtxt(fname) shapes = [] area = 0 for ellipse in data: cx, cy, b, a, ang = ellipse ang = ang*np.pi/180 place = FC.Placement() place.Rotation = (0, 0, np.sin(ang/2), np.cos(ang/2)) place.Base = FC.Vector(100*cx, 100*cy, 0) ellipse = Draft.makeEllipse(100*a, 100*b, placement=place) shapes.append(ellipse) area = area + np.pi*a*b*100*100 print area, " ", area/500/70 part = Part.makeCompound(shapes)
from __future__ import division import numpy as np import FreeCAD as FC import Part import Draft import os doc = FC.newDocument("ellipses") folder = os.path.dirname(__file__) #+ "/.." fname = folder + "/vor_ellipses.txt" data = np.loadtxt(fname) shapes = [] area = 0 radii = [] for ellipse in data: cx, cy, b, a, ang = ellipse ang = ang*np.pi/180 place = FC.Placement() place.Rotation = (0, 0, np.sin(ang/2), np.cos(ang/2)) place.Base = FC.Vector(100*cx, 100*cy, 0) ellipse = Draft.makeEllipse(100*a, 100*b, placement=place) radii.append([100*a, 100*b]) shapes.append(ellipse) area = area + np.pi*a*b*100*100 print "area: %g " % (area/500/70) print "radius: %g +/- %g" % (np.mean(radii), np.std(radii)) part = Part.makeCompound(shapes)
Add radii mean and standard deviation
Add radii mean and standard deviation
Python
mit
nicoguaro/ellipse_packing
python
## Code Before: from __future__ import division import numpy as np import FreeCAD as FC import Part import Draft import os doc = FC.newDocument("ellipses") folder = os.path.dirname(__file__) + ".\.." fname = folder + "/vor_ellipses.txt" data = np.loadtxt(fname) shapes = [] area = 0 for ellipse in data: cx, cy, b, a, ang = ellipse ang = ang*np.pi/180 place = FC.Placement() place.Rotation = (0, 0, np.sin(ang/2), np.cos(ang/2)) place.Base = FC.Vector(100*cx, 100*cy, 0) ellipse = Draft.makeEllipse(100*a, 100*b, placement=place) shapes.append(ellipse) area = area + np.pi*a*b*100*100 print area, " ", area/500/70 part = Part.makeCompound(shapes) ## Instruction: Add radii mean and standard deviation ## Code After: from __future__ import division import numpy as np import FreeCAD as FC import Part import Draft import os doc = FC.newDocument("ellipses") folder = os.path.dirname(__file__) #+ "/.." fname = folder + "/vor_ellipses.txt" data = np.loadtxt(fname) shapes = [] area = 0 radii = [] for ellipse in data: cx, cy, b, a, ang = ellipse ang = ang*np.pi/180 place = FC.Placement() place.Rotation = (0, 0, np.sin(ang/2), np.cos(ang/2)) place.Base = FC.Vector(100*cx, 100*cy, 0) ellipse = Draft.makeEllipse(100*a, 100*b, placement=place) radii.append([100*a, 100*b]) shapes.append(ellipse) area = area + np.pi*a*b*100*100 print "area: %g " % (area/500/70) print "radius: %g +/- %g" % (np.mean(radii), np.std(radii)) part = Part.makeCompound(shapes)
# ... existing code ... doc = FC.newDocument("ellipses") folder = os.path.dirname(__file__) #+ "/.." fname = folder + "/vor_ellipses.txt" data = np.loadtxt(fname) shapes = [] area = 0 radii = [] for ellipse in data: cx, cy, b, a, ang = ellipse ang = ang*np.pi/180 # ... modified code ... place.Rotation = (0, 0, np.sin(ang/2), np.cos(ang/2)) place.Base = FC.Vector(100*cx, 100*cy, 0) ellipse = Draft.makeEllipse(100*a, 100*b, placement=place) radii.append([100*a, 100*b]) shapes.append(ellipse) area = area + np.pi*a*b*100*100 print "area: %g " % (area/500/70) print "radius: %g +/- %g" % (np.mean(radii), np.std(radii)) part = Part.makeCompound(shapes) # ... rest of the code ...
a696e9740920018d726c0c54987f6dc6ba2128d6
eppread.py
eppread.py
import sys import eppformat as epp if __name__ == "__main__": if (len(sys.argv) > 1): p = epp.epp_file.parse_stream(open(sys.argv[1], "rb")) print("signature =", p.signature) print("version =", p.version) print(p.header) if (len(sys.argv) > 2): limit=int(sys.argv[2]) else: limit=None for v in p.data[:limit]: print(v) else: print("usage: eppread <file> [limit]") sys.exit(1);
from __future__ import print_function import sys import eppformat as epp if __name__ == "__main__": if (len(sys.argv) > 1): p = epp.epp_file.parse_stream(open(sys.argv[1], "rb")) print("signature =", p.signature) print("version =", p.version) print(p.header) if (len(sys.argv) > 2): limit=int(sys.argv[2]) else: limit=None for v in p.data[:limit]: print(v) else: print("usage: eppread <file> [limit]") sys.exit(1);
Improve printing of signature and version
Improve printing of signature and version
Python
isc
ra1fh/eppconvert
python
## Code Before: import sys import eppformat as epp if __name__ == "__main__": if (len(sys.argv) > 1): p = epp.epp_file.parse_stream(open(sys.argv[1], "rb")) print("signature =", p.signature) print("version =", p.version) print(p.header) if (len(sys.argv) > 2): limit=int(sys.argv[2]) else: limit=None for v in p.data[:limit]: print(v) else: print("usage: eppread <file> [limit]") sys.exit(1); ## Instruction: Improve printing of signature and version ## Code After: from __future__ import print_function import sys import eppformat as epp if __name__ == "__main__": if (len(sys.argv) > 1): p = epp.epp_file.parse_stream(open(sys.argv[1], "rb")) print("signature =", p.signature) print("version =", p.version) print(p.header) if (len(sys.argv) > 2): limit=int(sys.argv[2]) else: limit=None for v in p.data[:limit]: print(v) else: print("usage: eppread <file> [limit]") sys.exit(1);
... from __future__ import print_function import sys import eppformat as epp ...
a7919b78c96128cc5bcfda759da11f6b067d0041
tests/__init__.py
tests/__init__.py
import base64 import unittest def setup_package(self): pass def teardown_package(self): pass class BaseS3EncryptTest(unittest.TestCase): def decode64(self, data): return base64.b64decode(data) def encode64(self, data): return base64.b64encode(data)
import base64 import codecs import unittest def setup_package(self): pass def teardown_package(self): pass class BaseS3EncryptTest(unittest.TestCase): def decode64(self, data): return base64.b64decode(codecs.decode(data, 'utf-8')) def encode64(self, data): return codecs.encode(base64.b64encode(data), 'utf-8')
Make test helpers py 3 compatable
Make test helpers py 3 compatable
Python
bsd-3-clause
boldfield/s3-encryption
python
## Code Before: import base64 import unittest def setup_package(self): pass def teardown_package(self): pass class BaseS3EncryptTest(unittest.TestCase): def decode64(self, data): return base64.b64decode(data) def encode64(self, data): return base64.b64encode(data) ## Instruction: Make test helpers py 3 compatable ## Code After: import base64 import codecs import unittest def setup_package(self): pass def teardown_package(self): pass class BaseS3EncryptTest(unittest.TestCase): def decode64(self, data): return base64.b64decode(codecs.decode(data, 'utf-8')) def encode64(self, data): return codecs.encode(base64.b64encode(data), 'utf-8')
... import base64 import codecs import unittest ... class BaseS3EncryptTest(unittest.TestCase): def decode64(self, data): return base64.b64decode(codecs.decode(data, 'utf-8')) def encode64(self, data): return codecs.encode(base64.b64encode(data), 'utf-8') ...
0c753e644068439376493e4b23a1060d742770ae
tests/__main__.py
tests/__main__.py
import unittest if __name__ == '__main__': all_tests = unittest.TestLoader().discover('./', pattern='*_tests.py') unittest.TextTestRunner().run(all_tests)
import sys import unittest if __name__ == '__main__': all_tests = unittest.TestLoader().discover('./', pattern='*_tests.py') ret = unittest.TextTestRunner().run(all_tests).wasSuccessful() sys.exit(ret)
Fix an issue when unit tests always return 0 status.
Fix an issue when unit tests always return 0 status.
Python
mit
sergeymironov0001/twitch-chat-bot
python
## Code Before: import unittest if __name__ == '__main__': all_tests = unittest.TestLoader().discover('./', pattern='*_tests.py') unittest.TextTestRunner().run(all_tests) ## Instruction: Fix an issue when unit tests always return 0 status. ## Code After: import sys import unittest if __name__ == '__main__': all_tests = unittest.TestLoader().discover('./', pattern='*_tests.py') ret = unittest.TextTestRunner().run(all_tests).wasSuccessful() sys.exit(ret)
# ... existing code ... import sys import unittest if __name__ == '__main__': all_tests = unittest.TestLoader().discover('./', pattern='*_tests.py') ret = unittest.TextTestRunner().run(all_tests).wasSuccessful() sys.exit(ret) # ... rest of the code ...
beb8f12e4a8290d4107cdb91a321a6618a038ef9
rose_trellis/util.py
rose_trellis/util.py
from urllib.parse import urljoin import time import asyncio from typing import Any from typing import Callable TRELLO_URL_BASE = 'https://api.trello.com/1/' def join_url(part: str) -> str: """ Adds `part` to API base url. Always returns url without trailing slash. :param part: :return: url """ part = part.strip('/') newpath = urljoin(TRELLO_URL_BASE, part) while newpath.endswith('/'): newpath = newpath[:-1] return newpath def easy_run(func: Callable[Any], *args, **kwargs) -> Any: el = asyncio.get_event_loop() return el.run_until_complete(func(*args, **kwargs))
from urllib.parse import urljoin import time import asyncio from typing import Any from typing import Callable TRELLO_URL_BASE = 'https://api.trello.com/1/' def join_url(part: str) -> str: """ Adds `part` to API base url. Always returns url without trailing slash. :param part: :return: url """ part = part.strip('/') newpath = urljoin(TRELLO_URL_BASE, part) while newpath.endswith('/'): newpath = newpath[:-1] return newpath def easy_run(gen) -> Any: el = asyncio.get_event_loop() return el.run_until_complete(gen)
Make easy_run better by taking the generator from coroutines
Make easy_run better by taking the generator from coroutines
Python
mit
dmwyatt/rose_trellis
python
## Code Before: from urllib.parse import urljoin import time import asyncio from typing import Any from typing import Callable TRELLO_URL_BASE = 'https://api.trello.com/1/' def join_url(part: str) -> str: """ Adds `part` to API base url. Always returns url without trailing slash. :param part: :return: url """ part = part.strip('/') newpath = urljoin(TRELLO_URL_BASE, part) while newpath.endswith('/'): newpath = newpath[:-1] return newpath def easy_run(func: Callable[Any], *args, **kwargs) -> Any: el = asyncio.get_event_loop() return el.run_until_complete(func(*args, **kwargs)) ## Instruction: Make easy_run better by taking the generator from coroutines ## Code After: from urllib.parse import urljoin import time import asyncio from typing import Any from typing import Callable TRELLO_URL_BASE = 'https://api.trello.com/1/' def join_url(part: str) -> str: """ Adds `part` to API base url. Always returns url without trailing slash. :param part: :return: url """ part = part.strip('/') newpath = urljoin(TRELLO_URL_BASE, part) while newpath.endswith('/'): newpath = newpath[:-1] return newpath def easy_run(gen) -> Any: el = asyncio.get_event_loop() return el.run_until_complete(gen)
... return newpath def easy_run(gen) -> Any: el = asyncio.get_event_loop() return el.run_until_complete(gen) ...
b30d4301d58766471f435536cf804f7a63448ac5
qotr/tests/test_server.py
qotr/tests/test_server.py
from tornado import testing from qotr.server import make_application from qotr.config import config class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): return make_application() def test_index(self): response = self.fetch('/') self.assertEqual(200, response.code) def test_channel(self): response = self.fetch('/c/foo') self.assertEqual(200, response.code) def test_arbitrary(self): response = self.fetch('/arbitrary-page') self.assertEqual(404, response.code) def test_https_redirect(self): _old_cfg = config.redirect_to_https config.redirect_to_https = True response = self.fetch('/c/foo', follow_redirects=False) config.redirect_to_https = _old_cfg self.assertEqual(301, response.code)
from tornado import testing from qotr.server import make_application from qotr.config import config class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): return make_application() # def test_index(self): # response = self.fetch('/') # self.assertEqual(200, response.code) # def test_channel(self): # response = self.fetch('/c/foo') # self.assertEqual(200, response.code) # def test_arbitrary(self): # response = self.fetch('/arbitrary-page') # self.assertEqual(404, response.code) def test_https_redirect(self): _old_cfg = config.redirect_to_https config.redirect_to_https = True response = self.fetch('/c/foo', follow_redirects=False) config.redirect_to_https = _old_cfg self.assertEqual(301, response.code)
Disable testing for index.html, needs ember build
Disable testing for index.html, needs ember build Signed-off-by: Rohan Jain <[email protected]>
Python
agpl-3.0
rmoorman/qotr,rmoorman/qotr,sbuss/qotr,rmoorman/qotr,crodjer/qotr,sbuss/qotr,crodjer/qotr,sbuss/qotr,curtiszimmerman/qotr,curtiszimmerman/qotr,rmoorman/qotr,crodjer/qotr,curtiszimmerman/qotr,curtiszimmerman/qotr,sbuss/qotr,crodjer/qotr
python
## Code Before: from tornado import testing from qotr.server import make_application from qotr.config import config class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): return make_application() def test_index(self): response = self.fetch('/') self.assertEqual(200, response.code) def test_channel(self): response = self.fetch('/c/foo') self.assertEqual(200, response.code) def test_arbitrary(self): response = self.fetch('/arbitrary-page') self.assertEqual(404, response.code) def test_https_redirect(self): _old_cfg = config.redirect_to_https config.redirect_to_https = True response = self.fetch('/c/foo', follow_redirects=False) config.redirect_to_https = _old_cfg self.assertEqual(301, response.code) ## Instruction: Disable testing for index.html, needs ember build Signed-off-by: Rohan Jain <[email protected]> ## Code After: from tornado import testing from qotr.server import make_application from qotr.config import config class TestChannelHandler(testing.AsyncHTTPTestCase): ''' Test the channel creation handler. ''' port = None application = None def get_app(self): return make_application() # def test_index(self): # response = self.fetch('/') # self.assertEqual(200, response.code) # def test_channel(self): # response = self.fetch('/c/foo') # self.assertEqual(200, response.code) # def test_arbitrary(self): # response = self.fetch('/arbitrary-page') # self.assertEqual(404, response.code) def test_https_redirect(self): _old_cfg = config.redirect_to_https config.redirect_to_https = True response = self.fetch('/c/foo', follow_redirects=False) config.redirect_to_https = _old_cfg self.assertEqual(301, response.code)
... def get_app(self): return make_application() # def test_index(self): # response = self.fetch('/') # self.assertEqual(200, response.code) # def test_channel(self): # response = self.fetch('/c/foo') # self.assertEqual(200, response.code) # def test_arbitrary(self): # response = self.fetch('/arbitrary-page') # self.assertEqual(404, response.code) def test_https_redirect(self): _old_cfg = config.redirect_to_https ...
e0852c3587878239c825fabeaee00d56ebb29f84
src/test/java/com/example/activity/DeckardActivityTest.java
src/test/java/com/example/activity/DeckardActivityTest.java
package com.example.activity; import com.example.BuildConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import static org.junit.Assert.assertTrue; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = 18) public class DeckardActivityTest { @Test public void testSomething() throws Exception { assertTrue(Robolectric.buildActivity(DeckardActivity.class).create().get() != null); } }
package com.example.activity; import com.example.BuildConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import static org.junit.Assert.assertTrue; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = 18) public class DeckardActivityTest { @Test public void testSomething() throws Exception { assertTrue(Robolectric.setupActivity(DeckardActivity.class) != null); } }
Use setup instead of build for activity test
Use setup instead of build for activity test
Java
unlicense
Mounika-Chirukuri/deckard,0359xiaodong/deckard,seadowg/deckard-gradle,robolectric/deckard
java
## Code Before: package com.example.activity; import com.example.BuildConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import static org.junit.Assert.assertTrue; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = 18) public class DeckardActivityTest { @Test public void testSomething() throws Exception { assertTrue(Robolectric.buildActivity(DeckardActivity.class).create().get() != null); } } ## Instruction: Use setup instead of build for activity test ## Code After: package com.example.activity; import com.example.BuildConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import static org.junit.Assert.assertTrue; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = 18) public class DeckardActivityTest { @Test public void testSomething() throws Exception { assertTrue(Robolectric.setupActivity(DeckardActivity.class) != null); } }
... @Test public void testSomething() throws Exception { assertTrue(Robolectric.setupActivity(DeckardActivity.class) != null); } } ...
81b77e7c17f9e43a6cc9f1acd46cde85fd0a126f
src/test/java/net/folab/fo/runtime/GeneratedCodeTest.java
src/test/java/net/folab/fo/runtime/GeneratedCodeTest.java
package net.folab.fo.runtime; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import java.lang.reflect.Field; import org.junit.Test; import org.junit.Before; public class GeneratedCodeTest { private Class<?> genClass; @Before public void setUp() throws ClassNotFoundException { genClass = Class.forName("net.folab.fo.runtime._"); } @Test public void test() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { test("_a", "1"); test("_b", "2"); test("_c", "3"); test("_d", "4"); test("_e", "5"); test("_f", "false"); test("_t", "true"); } public void test(String name, String string) throws NoSuchFieldException, IllegalAccessException { Field field = genClass.getField(name); Evaluable<?> value = (Evaluable<?>) field.get(null); assertThat(value.evaluate().toString(), is(string)); } }
package net.folab.fo.runtime; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import java.lang.reflect.Field; import net.folab.fo.runtime._fo._lang.Boolean; import net.folab.fo.runtime._fo._lang.Integer; import org.junit.Test; import org.junit.Before; public class GeneratedCodeTest { private Class<?> genClass; @Before public void setUp() throws ClassNotFoundException { genClass = Class.forName("net.folab.fo.runtime._"); } @Test public void test() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { test("_a", Integer.valueOf(1)); test("_b", Integer.valueOf(2)); test("_c", Integer.valueOf(3)); test("_d", Integer.valueOf(4)); test("_e", Integer.valueOf(5)); test("_f", Boolean.FALSE); test("_t", Boolean.TRUE); } public <T extends Evaluable<T>> void test(String name, Evaluable<T> expected) throws NoSuchFieldException, IllegalAccessException { Field field = genClass.getField(name); @SuppressWarnings("unchecked") Evaluable<T> value = (Evaluable<T>) field.get(null); assertThat(value.evaluate(), is(expected)); } }
Update test code to compare with real type rather than string value.
Update test code to compare with real type rather than string value.
Java
mit
leafriend/fo,leafriend/metaj
java
## Code Before: package net.folab.fo.runtime; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import java.lang.reflect.Field; import org.junit.Test; import org.junit.Before; public class GeneratedCodeTest { private Class<?> genClass; @Before public void setUp() throws ClassNotFoundException { genClass = Class.forName("net.folab.fo.runtime._"); } @Test public void test() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { test("_a", "1"); test("_b", "2"); test("_c", "3"); test("_d", "4"); test("_e", "5"); test("_f", "false"); test("_t", "true"); } public void test(String name, String string) throws NoSuchFieldException, IllegalAccessException { Field field = genClass.getField(name); Evaluable<?> value = (Evaluable<?>) field.get(null); assertThat(value.evaluate().toString(), is(string)); } } ## Instruction: Update test code to compare with real type rather than string value. ## Code After: package net.folab.fo.runtime; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import java.lang.reflect.Field; import net.folab.fo.runtime._fo._lang.Boolean; import net.folab.fo.runtime._fo._lang.Integer; import org.junit.Test; import org.junit.Before; public class GeneratedCodeTest { private Class<?> genClass; @Before public void setUp() throws ClassNotFoundException { genClass = Class.forName("net.folab.fo.runtime._"); } @Test public void test() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { test("_a", Integer.valueOf(1)); test("_b", Integer.valueOf(2)); test("_c", Integer.valueOf(3)); test("_d", Integer.valueOf(4)); test("_e", Integer.valueOf(5)); test("_f", Boolean.FALSE); test("_t", Boolean.TRUE); } public <T extends Evaluable<T>> void test(String name, Evaluable<T> expected) throws NoSuchFieldException, IllegalAccessException { Field field = genClass.getField(name); @SuppressWarnings("unchecked") Evaluable<T> value = (Evaluable<T>) field.get(null); assertThat(value.evaluate(), is(expected)); } }
... import static org.hamcrest.CoreMatchers.*; import java.lang.reflect.Field; import net.folab.fo.runtime._fo._lang.Boolean; import net.folab.fo.runtime._fo._lang.Integer; import org.junit.Test; import org.junit.Before; ... public void test() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { test("_a", Integer.valueOf(1)); test("_b", Integer.valueOf(2)); test("_c", Integer.valueOf(3)); test("_d", Integer.valueOf(4)); test("_e", Integer.valueOf(5)); test("_f", Boolean.FALSE); test("_t", Boolean.TRUE); } public <T extends Evaluable<T>> void test(String name, Evaluable<T> expected) throws NoSuchFieldException, IllegalAccessException { Field field = genClass.getField(name); @SuppressWarnings("unchecked") Evaluable<T> value = (Evaluable<T>) field.get(null); assertThat(value.evaluate(), is(expected)); } } ...
b69db7ff67abe185bcf7e8e7badfa868a9ec882c
script/update-frameworks.py
script/update-frameworks.py
import sys import os from lib.util import safe_mkdir, extract_zip, tempdir, download SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) FRAMEWORKS_URL = 'http://atom-alpha.s3.amazonaws.com' def main(): os.chdir(SOURCE_ROOT) safe_mkdir('frameworks') download_and_unzip('Mantle') download_and_unzip('ReactiveCocoa') download_and_unzip('Squirrel') def download_and_unzip(framework): zip_path = download_framework(framework) if zip_path: extract_zip(zip_path, 'frameworks') def download_framework(framework): framework_path = os.path.join('frameworks', framework) + '.framework' if os.path.exists(framework_path): return filename = framework + '.framework.zip' url = FRAMEWORKS_URL + '/' + filename download_dir = tempdir(prefix='atom-shell-') path = os.path.join(download_dir, filename) download('Download ' + framework, url, path) return path if __name__ == '__main__': sys.exit(main())
import sys import os from lib.util import safe_mkdir, extract_zip, tempdir, download SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) FRAMEWORKS_URL = 'https://github.com/atom/atom-shell/releases/download/v0.11.10' def main(): os.chdir(SOURCE_ROOT) safe_mkdir('frameworks') download_and_unzip('Mantle') download_and_unzip('ReactiveCocoa') download_and_unzip('Squirrel') def download_and_unzip(framework): zip_path = download_framework(framework) if zip_path: extract_zip(zip_path, 'frameworks') def download_framework(framework): framework_path = os.path.join('frameworks', framework) + '.framework' if os.path.exists(framework_path): return filename = framework + '.framework.zip' url = FRAMEWORKS_URL + '/' + filename download_dir = tempdir(prefix='atom-shell-') path = os.path.join(download_dir, filename) download('Download ' + framework, url, path) return path if __name__ == '__main__': sys.exit(main())
Move framework downloads to github release
Move framework downloads to github release
Python
mit
bpasero/electron,fomojola/electron,simonfork/electron,micalan/electron,neutrous/electron,stevemao/electron,jtburke/electron,medixdev/electron,Andrey-Pavlov/electron,yalexx/electron,synaptek/electron,Neron-X5/electron,stevekinney/electron,christian-bromann/electron,benweissmann/electron,mirrh/electron,leftstick/electron,shockone/electron,aecca/electron,adcentury/electron,cqqccqc/electron,brave/electron,jannishuebl/electron,deed02392/electron,christian-bromann/electron,jlhbaseball15/electron,smczk/electron,evgenyzinoviev/electron,gbn972/electron,fabien-d/electron,gamedevsam/electron,jlhbaseball15/electron,fireball-x/atom-shell,tomashanacek/electron,JussMee15/electron,destan/electron,egoist/electron,jjz/electron,Floato/electron,eric-seekas/electron,mrwizard82d1/electron,micalan/electron,brave/electron,micalan/electron,micalan/electron,digideskio/electron,eriser/electron,mjaniszew/electron,gabrielPeart/electron,benweissmann/electron,ervinb/electron,aichingm/electron,cos2004/electron,trankmichael/electron,kikong/electron,timruffles/electron,shaundunne/electron,ankitaggarwal011/electron,zhakui/electron,Jacobichou/electron,felixrieseberg/electron,lrlna/electron,eriser/electron,adcentury/electron,destan/electron,twolfson/electron,systembugtj/electron,aliib/electron,minggo/electron,davazp/electron,mattdesl/electron,jacksondc/electron,eric-seekas/electron,Ivshti/electron,preco21/electron,miniak/electron,yan-foto/electron,sircharleswatson/electron,anko/electron,greyhwndz/electron,benweissmann/electron,dongjoon-hyun/electron,fritx/electron,baiwyc119/electron,Gerhut/electron,matiasinsaurralde/electron,yan-foto/electron,tomashanacek/electron,nicholasess/electron,darwin/electron,joneit/electron,Rokt33r/electron,twolfson/electron,kazupon/electron,subblue/electron,gabriel/electron,sky7sea/electron,fffej/electron,xfstudio/electron,vipulroxx/electron,sshiting/electron,vHanda/electron,seanchas116/electron,nicholasess/electron,leolujuyi/electron,trigrass2/electron,JussMee15/electron,mrwizard82d1/electron,beni55/electron,Neron-X5/electron,webmechanicx/electron,shockone/electron,icattlecoder/electron,vaginessa/electron,simonfork/electron,saronwei/electron,leftstick/electron,minggo/electron,MaxWhere/electron,Evercoder/electron,leolujuyi/electron,chrisswk/electron,lrlna/electron,farmisen/electron,aaron-goshine/electron,mhkeller/electron,roadev/electron,Zagorakiss/electron,etiktin/electron,thingsinjars/electron,joaomoreno/atom-shell,BionicClick/electron,jannishuebl/electron,xiruibing/electron,John-Lin/electron,lrlna/electron,icattlecoder/electron,meowlab/electron,twolfson/electron,LadyNaggaga/electron,pirafrank/electron,maxogden/atom-shell,webmechanicx/electron,Jonekee/electron,brave/electron,stevemao/electron,iftekeriba/electron,cos2004/electron,gstack/infinium-shell,bitemyapp/electron,BionicClick/electron,setzer777/electron,Jonekee/electron,iftekeriba/electron,xfstudio/electron,cqqccqc/electron,evgenyzinoviev/electron,jsutcodes/electron,RobertJGabriel/electron,bobwol/electron,pandoraui/electron,xfstudio/electron,ankitaggarwal011/electron,systembugtj/electron,simongregory/electron,coderhaoxin/electron,shockone/electron,MaxGraey/electron,iftekeriba/electron,trankmichael/electron,JussMee15/electron,trankmichael/electron,fomojola/electron,pandoraui/electron,dongjoon-hyun/electron,felixrieseberg/electron,dahal/electron,DivyaKMenon/electron,SufianHassan/electron,tonyganch/electron,Gerhut/electron,Ivshti/electron,posix4e/electron,arusakov/electron,jtburke/electron,the-ress/electron,faizalpribadi/electron,pandoraui/electron,thomsonreuters/electron,hokein/atom-shell,faizalpribadi/electron,michaelchiche/electron,d-salas/electron,jacksondc/electron,leolujuyi/electron,michaelchiche/electron,faizalpribadi/electron,sky7sea/electron,bright-sparks/electron,deepak1556/atom-shell,IonicaBizauKitchen/electron,pandoraui/electron,ianscrivener/electron,seanchas116/electron,benweissmann/electron,matiasinsaurralde/electron,yalexx/electron,ervinb/electron,systembugtj/electron,medixdev/electron,Evercoder/electron,gabriel/electron,stevemao/electron,John-Lin/electron,rajatsingla28/electron,d-salas/electron,Zagorakiss/electron,wan-qy/electron,fireball-x/atom-shell,icattlecoder/electron,dahal/electron,rprichard/electron,mhkeller/electron,bruce/electron,Andrey-Pavlov/electron,darwin/electron,christian-bromann/electron,robinvandernoord/electron,MaxGraey/electron,renaesop/electron,medixdev/electron,mattdesl/electron,etiktin/electron,matiasinsaurralde/electron,bobwol/electron,deed02392/electron,saronwei/electron,natgolov/electron,jhen0409/electron,stevemao/electron,Faiz7412/electron,tincan24/electron,kikong/electron,Floato/electron,micalan/electron,jannishuebl/electron,takashi/electron,Andrey-Pavlov/electron,aliib/electron,leolujuyi/electron,simonfork/electron,vaginessa/electron,GoooIce/electron,michaelchiche/electron,takashi/electron,destan/electron,michaelchiche/electron,carsonmcdonald/electron,gamedevsam/electron,aecca/electron,SufianHassan/electron,nicobot/electron,coderhaoxin/electron,michaelchiche/electron,abhishekgahlot/electron,gamedevsam/electron,miniak/electron,pombredanne/electron,cos2004/electron,faizalpribadi/electron,adamjgray/electron,pandoraui/electron,mrwizard82d1/electron,meowlab/electron,rhencke/electron,christian-bromann/electron,IonicaBizauKitchen/electron,biblerule/UMCTelnetHub,mrwizard82d1/electron,jaanus/electron,jiaz/electron,yalexx/electron,thomsonreuters/electron,brenca/electron,rreimann/electron,tomashanacek/electron,arturts/electron,nicholasess/electron,evgenyzinoviev/electron,RIAEvangelist/electron,thompsonemerson/electron,Evercoder/electron,vHanda/electron,renaesop/electron,bwiggs/electron,JesselJohn/electron,gamedevsam/electron,vHanda/electron,wan-qy/electron,stevekinney/electron,matiasinsaurralde/electron,MaxWhere/electron,jjz/electron,rsvip/electron,darwin/electron,gabrielPeart/electron,SufianHassan/electron,gamedevsam/electron,beni55/electron,kazupon/electron,ervinb/electron,John-Lin/electron,brave/electron,fireball-x/atom-shell,pirafrank/electron,renaesop/electron,gstack/infinium-shell,eriser/electron,neutrous/electron,lzpfmh/electron,fabien-d/electron,thompsonemerson/electron,minggo/electron,aichingm/electron,eric-seekas/electron,GoooIce/electron,gerhardberger/electron,voidbridge/electron,Zagorakiss/electron,astoilkov/electron,dkfiresky/electron,preco21/electron,carsonmcdonald/electron,eric-seekas/electron,bpasero/electron,thingsinjars/electron,tylergibson/electron,fomojola/electron,noikiy/electron,icattlecoder/electron,pirafrank/electron,trigrass2/electron,Jacobichou/electron,roadev/electron,Evercoder/electron,Jacobichou/electron,deed02392/electron,mirrh/electron,JesselJohn/electron,jannishuebl/electron,farmisen/electron,davazp/electron,IonicaBizauKitchen/electron,bbondy/electron,jlhbaseball15/electron,electron/electron,Jacobichou/electron,gabrielPeart/electron,oiledCode/electron,zhakui/electron,kenmozi/electron,michaelchiche/electron,benweissmann/electron,mjaniszew/electron,simongregory/electron,chriskdon/electron,davazp/electron,maxogden/atom-shell,LadyNaggaga/electron,pombredanne/electron,carsonmcdonald/electron,meowlab/electron,Jacobichou/electron,rprichard/electron,christian-bromann/electron,electron/electron,pirafrank/electron,seanchas116/electron,trankmichael/electron,kcrt/electron,jiaz/electron,dkfiresky/electron,fabien-d/electron,chriskdon/electron,fritx/electron,mattdesl/electron,rhencke/electron,christian-bromann/electron,Gerhut/electron,howmuchcomputer/electron,JussMee15/electron,kikong/electron,jcblw/electron,tylergibson/electron,JussMee15/electron,neutrous/electron,kazupon/electron,tinydew4/electron,wolfflow/electron,tomashanacek/electron,subblue/electron,renaesop/electron,chrisswk/electron,leftstick/electron,jhen0409/electron,noikiy/electron,shennushi/electron,vipulroxx/electron,sircharleswatson/electron,oiledCode/electron,yan-foto/electron,cos2004/electron,fomojola/electron,jtburke/electron,RobertJGabriel/electron,coderhaoxin/electron,sshiting/electron,kostia/electron,saronwei/electron,biblerule/UMCTelnetHub,shiftkey/electron,RIAEvangelist/electron,bpasero/electron,dongjoon-hyun/electron,arusakov/electron,chriskdon/electron,the-ress/electron,dkfiresky/electron,webmechanicx/electron,astoilkov/electron,fireball-x/atom-shell,leethomas/electron,Floato/electron,Rokt33r/electron,joaomoreno/atom-shell,the-ress/electron,edulan/electron,fritx/electron,RobertJGabriel/electron,jiaz/electron,webmechanicx/electron,d-salas/electron,ianscrivener/electron,jcblw/electron,kazupon/electron,sky7sea/electron,leftstick/electron,the-ress/electron,RIAEvangelist/electron,faizalpribadi/electron,smczk/electron,simonfork/electron,brave/muon,tonyganch/electron,minggo/electron,shennushi/electron,jiaz/electron,leftstick/electron,DivyaKMenon/electron,jlord/electron,kostia/electron,Gerhut/electron,electron/electron,arturts/electron,rprichard/electron,timruffles/electron,lzpfmh/electron,anko/electron,thomsonreuters/electron,tomashanacek/electron,jannishuebl/electron,kostia/electron,pombredanne/electron,rsvip/electron,tinydew4/electron,aaron-goshine/electron,joneit/electron,jacksondc/electron,faizalpribadi/electron,brenca/electron,arturts/electron,zhakui/electron,MaxWhere/electron,adamjgray/electron,edulan/electron,bitemyapp/electron,brave/muon,sircharleswatson/electron,jcblw/electron,gbn972/electron,davazp/electron,astoilkov/electron,aichingm/electron,evgenyzinoviev/electron,jonatasfreitasv/electron,MaxGraey/electron,brave/muon,d-salas/electron,nagyistoce/electron-atom-shell,vipulroxx/electron,Rokt33r/electron,subblue/electron,maxogden/atom-shell,setzer777/electron,jhen0409/electron,jlhbaseball15/electron,rajatsingla28/electron,greyhwndz/electron,hokein/atom-shell,evgenyzinoviev/electron,mubassirhayat/electron,destan/electron,jiaz/electron,edulan/electron,ianscrivener/electron,kokdemo/electron,xfstudio/electron,vaginessa/electron,LadyNaggaga/electron,electron/electron,noikiy/electron,posix4e/electron,the-ress/electron,twolfson/electron,matiasinsaurralde/electron,trankmichael/electron,RobertJGabriel/electron,rsvip/electron,nicobot/electron,wolfflow/electron,aaron-goshine/electron,brenca/electron,mjaniszew/electron,pandoraui/electron,IonicaBizauKitchen/electron,saronwei/electron,jtburke/electron,dongjoon-hyun/electron,mirrh/electron,miniak/electron,kcrt/electron,roadev/electron,arturts/electron,ianscrivener/electron,synaptek/electron,neutrous/electron,kokdemo/electron,howmuchcomputer/electron,micalan/electron,bitemyapp/electron,thompsonemerson/electron,bbondy/electron,bright-sparks/electron,leethomas/electron,miniak/electron,kokdemo/electron,timruffles/electron,howmuchcomputer/electron,joaomoreno/atom-shell,sircharleswatson/electron,Faiz7412/electron,etiktin/electron,Floato/electron,kenmozi/electron,rreimann/electron,gstack/infinium-shell,nicholasess/electron,MaxWhere/electron,mrwizard82d1/electron,eriser/electron,thingsinjars/electron,shiftkey/electron,aaron-goshine/electron,thompsonemerson/electron,John-Lin/electron,tonyganch/electron,John-Lin/electron,leolujuyi/electron,bpasero/electron,vHanda/electron,jlord/electron,GoooIce/electron,medixdev/electron,gabrielPeart/electron,tinydew4/electron,yan-foto/electron,preco21/electron,jhen0409/electron,biblerule/UMCTelnetHub,LadyNaggaga/electron,jonatasfreitasv/electron,nicobot/electron,Rokt33r/electron,roadev/electron,natgolov/electron,carsonmcdonald/electron,aliib/electron,ankitaggarwal011/electron,adamjgray/electron,brave/muon,jcblw/electron,bobwol/electron,shaundunne/electron,natgolov/electron,BionicClick/electron,digideskio/electron,kcrt/electron,bruce/electron,miniak/electron,noikiy/electron,setzer777/electron,aecca/electron,Neron-X5/electron,iftekeriba/electron,robinvandernoord/electron,bruce/electron,arturts/electron,MaxWhere/electron,tincan24/electron,wan-qy/electron,shennushi/electron,gerhardberger/electron,coderhaoxin/electron,oiledCode/electron,simongregory/electron,nagyistoce/electron-atom-shell,setzer777/electron,fomojola/electron,posix4e/electron,dkfiresky/electron,simongregory/electron,yan-foto/electron,beni55/electron,chrisswk/electron,pombredanne/electron,anko/electron,mubassirhayat/electron,DivyaKMenon/electron,jjz/electron,jaanus/electron,adcentury/electron,tylergibson/electron,jsutcodes/electron,dongjoon-hyun/electron,thompsonemerson/electron,joneit/electron,deepak1556/atom-shell,mrwizard82d1/electron,tomashanacek/electron,aecca/electron,vipulroxx/electron,nagyistoce/electron-atom-shell,Gerhut/electron,sshiting/electron,Andrey-Pavlov/electron,jsutcodes/electron,synaptek/electron,astoilkov/electron,digideskio/electron,eriser/electron,trigrass2/electron,xiruibing/electron,mattotodd/electron,kenmozi/electron,nicobot/electron,yalexx/electron,shaundunne/electron,rhencke/electron,chrisswk/electron,mhkeller/electron,egoist/electron,zhakui/electron,fffej/electron,jsutcodes/electron,soulteary/electron,ervinb/electron,bbondy/electron,brenca/electron,bruce/electron,joneit/electron,Gerhut/electron,meowlab/electron,gabriel/electron,shiftkey/electron,aecca/electron,thingsinjars/electron,xiruibing/electron,rreimann/electron,yalexx/electron,Neron-X5/electron,meowlab/electron,mubassirhayat/electron,chriskdon/electron,RobertJGabriel/electron,rajatsingla28/electron,arturts/electron,maxogden/atom-shell,fritx/electron,nicobot/electron,zhakui/electron,rsvip/electron,Faiz7412/electron,abhishekgahlot/electron,Faiz7412/electron,leethomas/electron,soulteary/electron,renaesop/electron,voidbridge/electron,gerhardberger/electron,kostia/electron,leftstick/electron,tincan24/electron,jonatasfreitasv/electron,dahal/electron,d-salas/electron,rajatsingla28/electron,thomsonreuters/electron,pombredanne/electron,wan-qy/electron,benweissmann/electron,abhishekgahlot/electron,systembugtj/electron,vipulroxx/electron,mirrh/electron,tonyganch/electron,deepak1556/atom-shell,thingsinjars/electron,saronwei/electron,mattdesl/electron,lzpfmh/electron,yan-foto/electron,shockone/electron,fritx/electron,zhakui/electron,aichingm/electron,oiledCode/electron,jonatasfreitasv/electron,rajatsingla28/electron,jaanus/electron,fffej/electron,smczk/electron,bright-sparks/electron,adcentury/electron,BionicClick/electron,John-Lin/electron,rajatsingla28/electron,ervinb/electron,farmisen/electron,hokein/atom-shell,JesselJohn/electron,vipulroxx/electron,noikiy/electron,bwiggs/electron,Jonekee/electron,seanchas116/electron,tinydew4/electron,bwiggs/electron,lzpfmh/electron,trankmichael/electron,jlord/electron,abhishekgahlot/electron,biblerule/UMCTelnetHub,DivyaKMenon/electron,thompsonemerson/electron,GoooIce/electron,Zagorakiss/electron,jiaz/electron,systembugtj/electron,Neron-X5/electron,shennushi/electron,evgenyzinoviev/electron,pirafrank/electron,aaron-goshine/electron,baiwyc119/electron,jlord/electron,etiktin/electron,tylergibson/electron,stevekinney/electron,kcrt/electron,vaginessa/electron,tinydew4/electron,baiwyc119/electron,electron/electron,bbondy/electron,LadyNaggaga/electron,Zagorakiss/electron,nekuz0r/electron,sshiting/electron,voidbridge/electron,jtburke/electron,jonatasfreitasv/electron,mjaniszew/electron,dkfiresky/electron,electron/electron,bitemyapp/electron,destan/electron,Jacobichou/electron,JesselJohn/electron,synaptek/electron,aaron-goshine/electron,mattotodd/electron,trigrass2/electron,cos2004/electron,medixdev/electron,Floato/electron,dahal/electron,stevemao/electron,arusakov/electron,baiwyc119/electron,gabriel/electron,stevekinney/electron,etiktin/electron,joaomoreno/atom-shell,JesselJohn/electron,posix4e/electron,aecca/electron,fffej/electron,simongregory/electron,felixrieseberg/electron,bbondy/electron,cos2004/electron,rhencke/electron,Ivshti/electron,soulteary/electron,edulan/electron,xiruibing/electron,RIAEvangelist/electron,IonicaBizauKitchen/electron,stevemao/electron,fffej/electron,davazp/electron,ankitaggarwal011/electron,bpasero/electron,farmisen/electron,edulan/electron,deed02392/electron,takashi/electron,howmuchcomputer/electron,digideskio/electron,tincan24/electron,medixdev/electron,deed02392/electron,pombredanne/electron,jcblw/electron,rprichard/electron,howmuchcomputer/electron,kostia/electron,aichingm/electron,greyhwndz/electron,smczk/electron,deepak1556/atom-shell,takashi/electron,meowlab/electron,brenca/electron,thomsonreuters/electron,adcentury/electron,bwiggs/electron,ankitaggarwal011/electron,kokdemo/electron,sky7sea/electron,aichingm/electron,wolfflow/electron,JussMee15/electron,anko/electron,coderhaoxin/electron,natgolov/electron,joaomoreno/atom-shell,gbn972/electron,Neron-X5/electron,jaanus/electron,nicholasess/electron,timruffles/electron,simonfork/electron,lrlna/electron,bwiggs/electron,jsutcodes/electron,nekuz0r/electron,shockone/electron,jcblw/electron,digideskio/electron,dahal/electron,mattdesl/electron,jacksondc/electron,rhencke/electron,shennushi/electron,the-ress/electron,oiledCode/electron,subblue/electron,shiftkey/electron,preco21/electron,rreimann/electron,d-salas/electron,miniak/electron,bpasero/electron,cqqccqc/electron,xfstudio/electron,mhkeller/electron,trigrass2/electron,Evercoder/electron,systembugtj/electron,gstack/infinium-shell,felixrieseberg/electron,electron/electron,kostia/electron,fabien-d/electron,MaxGraey/electron,neutrous/electron,nicobot/electron,rsvip/electron,Ivshti/electron,tylergibson/electron,beni55/electron,xiruibing/electron,simonfork/electron,shiftkey/electron,kenmozi/electron,mhkeller/electron,aliib/electron,astoilkov/electron,fffej/electron,jacksondc/electron,natgolov/electron,vHanda/electron,kokdemo/electron,gabriel/electron,minggo/electron,tincan24/electron,farmisen/electron,kikong/electron,dkfiresky/electron,leethomas/electron,xfstudio/electron,greyhwndz/electron,joaomoreno/atom-shell,bwiggs/electron,SufianHassan/electron,kcrt/electron,Evercoder/electron,lzpfmh/electron,baiwyc119/electron,bpasero/electron,gerhardberger/electron,seanchas116/electron,subblue/electron,biblerule/UMCTelnetHub,wolfflow/electron,bright-sparks/electron,bbondy/electron,jhen0409/electron,jacksondc/electron,beni55/electron,joneit/electron,SufianHassan/electron,adcentury/electron,ianscrivener/electron,renaesop/electron,carsonmcdonald/electron,jlord/electron,felixrieseberg/electron,DivyaKMenon/electron,eric-seekas/electron,setzer777/electron,tinydew4/electron,SufianHassan/electron,vaginessa/electron,Ivshti/electron,dahal/electron,GoooIce/electron,chriskdon/electron,fritx/electron,roadev/electron,arusakov/electron,gamedevsam/electron,aliib/electron,davazp/electron,egoist/electron,synaptek/electron,vaginessa/electron,anko/electron,tylergibson/electron,shiftkey/electron,Andrey-Pavlov/electron,smczk/electron,astoilkov/electron,egoist/electron,lrlna/electron,Jonekee/electron,farmisen/electron,mattotodd/electron,howmuchcomputer/electron,egoist/electron,posix4e/electron,edulan/electron,fireball-x/atom-shell,greyhwndz/electron,destan/electron,jjz/electron,darwin/electron,robinvandernoord/electron,webmechanicx/electron,etiktin/electron,yalexx/electron,seanchas116/electron,shaundunne/electron,jsutcodes/electron,saronwei/electron,JesselJohn/electron,gabrielPeart/electron,abhishekgahlot/electron,bright-sparks/electron,twolfson/electron,mirrh/electron,Andrey-Pavlov/electron,Floato/electron,iftekeriba/electron,digideskio/electron,thomsonreuters/electron,nekuz0r/electron,tonyganch/electron,leolujuyi/electron,kenmozi/electron,brave/muon,Jonekee/electron,ankitaggarwal011/electron,beni55/electron,voidbridge/electron,ervinb/electron,jannishuebl/electron,BionicClick/electron,matiasinsaurralde/electron,voidbridge/electron,kikong/electron,stevekinney/electron,preco21/electron,shennushi/electron,cqqccqc/electron,baiwyc119/electron,kokdemo/electron,mirrh/electron,soulteary/electron,soulteary/electron,chrisswk/electron,RIAEvangelist/electron,carsonmcdonald/electron,Zagorakiss/electron,Faiz7412/electron,jjz/electron,jhen0409/electron,mattotodd/electron,robinvandernoord/electron,maxogden/atom-shell,lrlna/electron,IonicaBizauKitchen/electron,jaanus/electron,nekuz0r/electron,mubassirhayat/electron,robinvandernoord/electron,wan-qy/electron,cqqccqc/electron,gabriel/electron,mhkeller/electron,soulteary/electron,subblue/electron,gbn972/electron,icattlecoder/electron,smczk/electron,posix4e/electron,oiledCode/electron,synaptek/electron,preco21/electron,deepak1556/atom-shell,sky7sea/electron,bitemyapp/electron,Rokt33r/electron,brenca/electron,gerhardberger/electron,nagyistoce/electron-atom-shell,jonatasfreitasv/electron,thingsinjars/electron,joneit/electron,trigrass2/electron,brave/electron,bobwol/electron,arusakov/electron,hokein/atom-shell,takashi/electron,nagyistoce/electron-atom-shell,gstack/infinium-shell,kenmozi/electron,gabrielPeart/electron,leethomas/electron,wolfflow/electron,brave/electron,lzpfmh/electron,mubassirhayat/electron,DivyaKMenon/electron,mattotodd/electron,RIAEvangelist/electron,timruffles/electron,jlhbaseball15/electron,bruce/electron,RobertJGabriel/electron,gerhardberger/electron,setzer777/electron,biblerule/UMCTelnetHub,wan-qy/electron,sky7sea/electron,GoooIce/electron,gbn972/electron,jjz/electron,bitemyapp/electron,eric-seekas/electron,kazupon/electron,mattdesl/electron,roadev/electron,hokein/atom-shell,jaanus/electron,sshiting/electron,LadyNaggaga/electron,Jonekee/electron,deed02392/electron,pirafrank/electron,kazupon/electron,takashi/electron,coderhaoxin/electron,icattlecoder/electron,mattotodd/electron,Rokt33r/electron,jtburke/electron,arusakov/electron,cqqccqc/electron,wolfflow/electron,sircharleswatson/electron,bobwol/electron,rhencke/electron,brave/muon,nekuz0r/electron,simongregory/electron,darwin/electron,adamjgray/electron,mjaniszew/electron,gerhardberger/electron,stevekinney/electron,abhishekgahlot/electron,bruce/electron,shaundunne/electron,rreimann/electron,natgolov/electron,fomojola/electron,xiruibing/electron,dongjoon-hyun/electron,aliib/electron,shaundunne/electron,chriskdon/electron,rreimann/electron,nekuz0r/electron,MaxGraey/electron,kcrt/electron,BionicClick/electron,sshiting/electron,eriser/electron,nicholasess/electron,tincan24/electron,voidbridge/electron,neutrous/electron,sircharleswatson/electron,MaxWhere/electron,felixrieseberg/electron,adamjgray/electron,minggo/electron,twolfson/electron,adamjgray/electron,anko/electron,shockone/electron,gbn972/electron,robinvandernoord/electron,the-ress/electron,fabien-d/electron,greyhwndz/electron,iftekeriba/electron,egoist/electron,leethomas/electron,jlhbaseball15/electron,vHanda/electron,mjaniszew/electron,tonyganch/electron,bright-sparks/electron,bobwol/electron,webmechanicx/electron,ianscrivener/electron,noikiy/electron
python
## Code Before: import sys import os from lib.util import safe_mkdir, extract_zip, tempdir, download SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) FRAMEWORKS_URL = 'http://atom-alpha.s3.amazonaws.com' def main(): os.chdir(SOURCE_ROOT) safe_mkdir('frameworks') download_and_unzip('Mantle') download_and_unzip('ReactiveCocoa') download_and_unzip('Squirrel') def download_and_unzip(framework): zip_path = download_framework(framework) if zip_path: extract_zip(zip_path, 'frameworks') def download_framework(framework): framework_path = os.path.join('frameworks', framework) + '.framework' if os.path.exists(framework_path): return filename = framework + '.framework.zip' url = FRAMEWORKS_URL + '/' + filename download_dir = tempdir(prefix='atom-shell-') path = os.path.join(download_dir, filename) download('Download ' + framework, url, path) return path if __name__ == '__main__': sys.exit(main()) ## Instruction: Move framework downloads to github release ## Code After: import sys import os from lib.util import safe_mkdir, extract_zip, tempdir, download SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) FRAMEWORKS_URL = 'https://github.com/atom/atom-shell/releases/download/v0.11.10' def main(): os.chdir(SOURCE_ROOT) safe_mkdir('frameworks') download_and_unzip('Mantle') download_and_unzip('ReactiveCocoa') download_and_unzip('Squirrel') def download_and_unzip(framework): zip_path = download_framework(framework) if zip_path: extract_zip(zip_path, 'frameworks') def download_framework(framework): framework_path = os.path.join('frameworks', framework) + '.framework' if os.path.exists(framework_path): return filename = framework + '.framework.zip' url = FRAMEWORKS_URL + '/' + filename download_dir = tempdir(prefix='atom-shell-') path = os.path.join(download_dir, filename) download('Download ' + framework, url, path) return path if __name__ == '__main__': sys.exit(main())
# ... existing code ... SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) FRAMEWORKS_URL = 'https://github.com/atom/atom-shell/releases/download/v0.11.10' def main(): os.chdir(SOURCE_ROOT) # ... rest of the code ...
526b09b014c8219cfe3747170c6021fe92fb65d5
firmware/lm32/config.h
firmware/lm32/config.h
enum { CONFIG_KEY_RESOLUTION = 0, CONFIG_KEY_BLEND_USER1, CONFIG_KEY_BLEND_USER2, CONFIG_KEY_BLEND_USER3, CONFIG_KEY_BLEND_USER4, CONFIG_KEY_COUNT }; #define CONFIG_DEFAULTS { 9, 1, 2, 3, 4 } void config_init(void); void config_write_all(void); unsigned char config_get(unsigned char key); void config_set(unsigned char key, unsigned char value); #endif /* __CONFIG_H */
enum { CONFIG_KEY_RESOLUTION = 0, CONFIG_KEY_BLEND_USER1, CONFIG_KEY_BLEND_USER2, CONFIG_KEY_BLEND_USER3, CONFIG_KEY_BLEND_USER4, CONFIG_KEY_COUNT }; #ifdef BOARD_MINISPARTAN6 #define CONFIG_DEFAULTS { 5, 1, 2, 3, 4 } #else #define CONFIG_DEFAULTS { 9, 1, 2, 3, 4 } #endif void config_init(void); void config_write_all(void); unsigned char config_get(unsigned char key); void config_set(unsigned char key, unsigned char value); #endif /* __CONFIG_H */
Make 800x600 the default mode for the minispartan6+
firmware/lm32: Make 800x600 the default mode for the minispartan6+
C
bsd-2-clause
mithro/HDMI2USB-litex-firmware,mithro/HDMI2USB-litex-firmware,cr1901/HDMI2USB-litex-firmware,cr1901/HDMI2USB-litex-firmware,mithro/HDMI2USB-litex-firmware,cr1901/HDMI2USB-litex-firmware,cr1901/HDMI2USB-litex-firmware,mithro/HDMI2USB-litex-firmware
c
## Code Before: enum { CONFIG_KEY_RESOLUTION = 0, CONFIG_KEY_BLEND_USER1, CONFIG_KEY_BLEND_USER2, CONFIG_KEY_BLEND_USER3, CONFIG_KEY_BLEND_USER4, CONFIG_KEY_COUNT }; #define CONFIG_DEFAULTS { 9, 1, 2, 3, 4 } void config_init(void); void config_write_all(void); unsigned char config_get(unsigned char key); void config_set(unsigned char key, unsigned char value); #endif /* __CONFIG_H */ ## Instruction: firmware/lm32: Make 800x600 the default mode for the minispartan6+ ## Code After: enum { CONFIG_KEY_RESOLUTION = 0, CONFIG_KEY_BLEND_USER1, CONFIG_KEY_BLEND_USER2, CONFIG_KEY_BLEND_USER3, CONFIG_KEY_BLEND_USER4, CONFIG_KEY_COUNT }; #ifdef BOARD_MINISPARTAN6 #define CONFIG_DEFAULTS { 5, 1, 2, 3, 4 } #else #define CONFIG_DEFAULTS { 9, 1, 2, 3, 4 } #endif void config_init(void); void config_write_all(void); unsigned char config_get(unsigned char key); void config_set(unsigned char key, unsigned char value); #endif /* __CONFIG_H */
// ... existing code ... CONFIG_KEY_COUNT }; #ifdef BOARD_MINISPARTAN6 #define CONFIG_DEFAULTS { 5, 1, 2, 3, 4 } #else #define CONFIG_DEFAULTS { 9, 1, 2, 3, 4 } #endif void config_init(void); void config_write_all(void); // ... rest of the code ...
3a06f01a9440b05b87bebc33d1342cd71fbeefbb
samples/admin.py
samples/admin.py
from django.contrib import admin from .models import Patient, PatientRegister, FluVaccine, Sample, CollectionType class FluVaccineInline(admin.StackedInline): model = FluVaccine extra = 1 class SampleInline(admin.StackedInline): model = Sample extra = 1 class PatientRegisterAdmin(admin.ModelAdmin): fieldsets = [ ('Informações do Paciente', {'fields': ['patient']}), ('Dados institucionais', {'fields': ['id_gal_origin']}), ] inlines = [ SampleInline, FluVaccineInline, ] admin.site.register(Patient) admin.site.register(Sample) admin.site.register(CollectionType) admin.site.register(PatientRegister, PatientRegisterAdmin)
from django.contrib import admin from .models import ( Patient, PatientRegister, FluVaccine, Sample, CollectionType, Symptom, ObservedSymptom ) class FluVaccineInline(admin.StackedInline): model = FluVaccine extra = 1 class SampleInline(admin.StackedInline): model = Sample extra = 1 class ObservedSymptomInline(admin.StackedInline): model = ObservedSymptom extra = 2 class PatientRegisterAdmin(admin.ModelAdmin): fieldsets = [ ('Informações do Paciente', {'fields': ['patient']}), ('Dados institucionais', {'fields': ['id_gal_origin']}), ] inlines = [ SampleInline, FluVaccineInline, ObservedSymptomInline, ] admin.site.register(Patient) admin.site.register(PatientRegister, PatientRegisterAdmin) admin.site.register(Sample) admin.site.register(CollectionType) admin.site.register(Symptom)
Add Symptoms and ObservedSymptoms to Admin
:rocket: Add Symptoms and ObservedSymptoms to Admin
Python
mit
gems-uff/labsys,gems-uff/labsys,gcrsaldanha/fiocruz,gcrsaldanha/fiocruz,gems-uff/labsys
python
## Code Before: from django.contrib import admin from .models import Patient, PatientRegister, FluVaccine, Sample, CollectionType class FluVaccineInline(admin.StackedInline): model = FluVaccine extra = 1 class SampleInline(admin.StackedInline): model = Sample extra = 1 class PatientRegisterAdmin(admin.ModelAdmin): fieldsets = [ ('Informações do Paciente', {'fields': ['patient']}), ('Dados institucionais', {'fields': ['id_gal_origin']}), ] inlines = [ SampleInline, FluVaccineInline, ] admin.site.register(Patient) admin.site.register(Sample) admin.site.register(CollectionType) admin.site.register(PatientRegister, PatientRegisterAdmin) ## Instruction: :rocket: Add Symptoms and ObservedSymptoms to Admin ## Code After: from django.contrib import admin from .models import ( Patient, PatientRegister, FluVaccine, Sample, CollectionType, Symptom, ObservedSymptom ) class FluVaccineInline(admin.StackedInline): model = FluVaccine extra = 1 class SampleInline(admin.StackedInline): model = Sample extra = 1 class ObservedSymptomInline(admin.StackedInline): model = ObservedSymptom extra = 2 class PatientRegisterAdmin(admin.ModelAdmin): fieldsets = [ ('Informações do Paciente', {'fields': ['patient']}), ('Dados institucionais', {'fields': ['id_gal_origin']}), ] inlines = [ SampleInline, FluVaccineInline, ObservedSymptomInline, ] admin.site.register(Patient) admin.site.register(PatientRegister, PatientRegisterAdmin) admin.site.register(Sample) admin.site.register(CollectionType) admin.site.register(Symptom)
... from django.contrib import admin from .models import ( Patient, PatientRegister, FluVaccine, Sample, CollectionType, Symptom, ObservedSymptom ) class FluVaccineInline(admin.StackedInline): ... extra = 1 class ObservedSymptomInline(admin.StackedInline): model = ObservedSymptom extra = 2 class PatientRegisterAdmin(admin.ModelAdmin): fieldsets = [ ('Informações do Paciente', {'fields': ['patient']}), ... inlines = [ SampleInline, FluVaccineInline, ObservedSymptomInline, ] admin.site.register(Patient) admin.site.register(PatientRegister, PatientRegisterAdmin) admin.site.register(Sample) admin.site.register(CollectionType) admin.site.register(Symptom) ...
d95d4da272915ad6a581260679df756bf24a6f4c
app/utils/db/__init__.py
app/utils/db/__init__.py
import logging from app import db logger = logging.getLogger(__name__) def save_data(data): try: db.session.add(data) db.session.commit() except Exception as err: logger.error(err)
import logging from app import db logger = logging.getLogger(__name__) def save_record(record): try: db.session.add(record) db.session.commit() except Exception as err: logger.error(err) def delete_record(record): try: db.session.delete(record) db.session.commit() except Exception as err: logger.error(err)
Rename save method for database to a more descriptive name
[FIX] Rename save method for database to a more descriptive name
Python
mit
brayoh/bucket-list-api
python
## Code Before: import logging from app import db logger = logging.getLogger(__name__) def save_data(data): try: db.session.add(data) db.session.commit() except Exception as err: logger.error(err) ## Instruction: [FIX] Rename save method for database to a more descriptive name ## Code After: import logging from app import db logger = logging.getLogger(__name__) def save_record(record): try: db.session.add(record) db.session.commit() except Exception as err: logger.error(err) def delete_record(record): try: db.session.delete(record) db.session.commit() except Exception as err: logger.error(err)
... logger = logging.getLogger(__name__) def save_record(record): try: db.session.add(record) db.session.commit() except Exception as err: logger.error(err) def delete_record(record): try: db.session.delete(record) db.session.commit() except Exception as err: logger.error(err) ...
d6782066e3ed3f00e3c8dcffe2ffd0b9bad18d17
slave/skia_slave_scripts/render_pdfs.py
slave/skia_slave_scripts/render_pdfs.py
""" Run the Skia render_pdfs executable. """ from build_step import BuildStep, BuildStepWarning import sys class RenderPdfs(BuildStep): def _Run(self): # Skip this step for now, since the new SKPs are causing it to crash. raise BuildStepWarning('Skipping this step since it is crashing.') #self.RunFlavoredCmd('render_pdfs', [self._device_dirs.SKPDir()]) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(RenderPdfs))
""" Run the Skia render_pdfs executable. """ from build_step import BuildStep import sys class RenderPdfs(BuildStep): def _Run(self): self.RunFlavoredCmd('render_pdfs', [self._device_dirs.SKPDir()]) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(RenderPdfs))
Revert "Skip RenderPdfs until the crash is fixed"
Revert "Skip RenderPdfs until the crash is fixed" This reverts commit fd03af0fbcb5f1b3656bcc78d934c560816d6810. https://codereview.chromium.org/15002002/ fixes the crash. [email protected] Review URL: https://codereview.chromium.org/14577010 git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9019 2bbb7eff-a529-9590-31e7-b0007b416f81
Python
bsd-3-clause
Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot
python
## Code Before: """ Run the Skia render_pdfs executable. """ from build_step import BuildStep, BuildStepWarning import sys class RenderPdfs(BuildStep): def _Run(self): # Skip this step for now, since the new SKPs are causing it to crash. raise BuildStepWarning('Skipping this step since it is crashing.') #self.RunFlavoredCmd('render_pdfs', [self._device_dirs.SKPDir()]) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(RenderPdfs)) ## Instruction: Revert "Skip RenderPdfs until the crash is fixed" This reverts commit fd03af0fbcb5f1b3656bcc78d934c560816d6810. https://codereview.chromium.org/15002002/ fixes the crash. [email protected] Review URL: https://codereview.chromium.org/14577010 git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9019 2bbb7eff-a529-9590-31e7-b0007b416f81 ## Code After: """ Run the Skia render_pdfs executable. """ from build_step import BuildStep import sys class RenderPdfs(BuildStep): def _Run(self): self.RunFlavoredCmd('render_pdfs', [self._device_dirs.SKPDir()]) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(RenderPdfs))
... """ Run the Skia render_pdfs executable. """ from build_step import BuildStep import sys class RenderPdfs(BuildStep): def _Run(self): self.RunFlavoredCmd('render_pdfs', [self._device_dirs.SKPDir()]) if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(RenderPdfs)) ...
b7ba8230802b1db4906f3d3f7489b60458b51ad5
examples/wc_mock.h
examples/wc_mock.h
// Copyright 2015. All Rights Reserved. // Author: [email protected] (Xiaotian Pei) #ifndef EXAMPLES_COREUTILS_WC_MOCK_H_ #define EXAMPLES_COREUTILS_WC_MOCK_H_ #include "examples/coreutils/wc.h" #include "third_party/gmock/gmock.h" namespace coreutils { class MockFile : public File { public: MOCK_METHOD2(Open, bool(const char* filename, const char* mode)); MOCK_METHOD0(Close, bool()); MOCK_METHOD2(Read, int(char* buffer, int buf_size)); MOCK_METHOD0(Eof, bool()); }; } // namespace coreutils #endif // EXAMPLES_COREUTILS_WC_MOCK_H_
// Copyright 2015. All Rights Reserved. // Author: [email protected] (Xiaotian Pei) #ifndef EXAMPLES_COREUTILS_WC_MOCK_H_ #define EXAMPLES_COREUTILS_WC_MOCK_H_ #include "examples/wc.h" #include "third_party/gmock/gmock.h" namespace coreutils { class MockFile : public File { public: MOCK_METHOD2(Open, bool(const char* filename, const char* mode)); MOCK_METHOD0(Close, bool()); MOCK_METHOD2(Read, int(char* buffer, int buf_size)); MOCK_METHOD0(Eof, bool()); }; } // namespace coreutils #endif // EXAMPLES_COREUTILS_WC_MOCK_H_
Fix path in header file
Fix path in header file
C
mit
skyshaw/skynet3,skyshaw/skynet3,skyshaw/skynet3,skyshaw/skynet3
c
## Code Before: // Copyright 2015. All Rights Reserved. // Author: [email protected] (Xiaotian Pei) #ifndef EXAMPLES_COREUTILS_WC_MOCK_H_ #define EXAMPLES_COREUTILS_WC_MOCK_H_ #include "examples/coreutils/wc.h" #include "third_party/gmock/gmock.h" namespace coreutils { class MockFile : public File { public: MOCK_METHOD2(Open, bool(const char* filename, const char* mode)); MOCK_METHOD0(Close, bool()); MOCK_METHOD2(Read, int(char* buffer, int buf_size)); MOCK_METHOD0(Eof, bool()); }; } // namespace coreutils #endif // EXAMPLES_COREUTILS_WC_MOCK_H_ ## Instruction: Fix path in header file ## Code After: // Copyright 2015. All Rights Reserved. // Author: [email protected] (Xiaotian Pei) #ifndef EXAMPLES_COREUTILS_WC_MOCK_H_ #define EXAMPLES_COREUTILS_WC_MOCK_H_ #include "examples/wc.h" #include "third_party/gmock/gmock.h" namespace coreutils { class MockFile : public File { public: MOCK_METHOD2(Open, bool(const char* filename, const char* mode)); MOCK_METHOD0(Close, bool()); MOCK_METHOD2(Read, int(char* buffer, int buf_size)); MOCK_METHOD0(Eof, bool()); }; } // namespace coreutils #endif // EXAMPLES_COREUTILS_WC_MOCK_H_
# ... existing code ... #ifndef EXAMPLES_COREUTILS_WC_MOCK_H_ #define EXAMPLES_COREUTILS_WC_MOCK_H_ #include "examples/wc.h" #include "third_party/gmock/gmock.h" namespace coreutils { # ... rest of the code ...
29ecb6f6bac85aeecba6b2602744f178735c0adc
pyautoupdate/_move_glob.py
pyautoupdate/_move_glob.py
import glob import shutil import os if os.name == "nt": from .ntcommonpath import commonpath else: from .posixcommonpath import commonpath def move_glob(src,dst): """Moves files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): shutil.move(obj,dst) def copy_glob(src,dst): """Copies files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): if os.path.isdir(obj): start_part=commonpath([src,obj]) end_part=os.path.relpath(obj,start_part) shutil.copytree(obj,os.path.join(dst,end_part)) else: shutil.copy2(obj,dst)
import glob import shutil import os if os.name == "nt": from .ntcommonpath import commonpath else: from .posixcommonpath import commonpath def move_glob(src,dst): """Moves files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): shutil.move(obj,dst) def copy_glob(src,dst): """Copies files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): if os.path.isdir(obj): start_part=commonpath([src,obj]) end_part=os.path.relpath(obj,start_part) ctree_dst=os.path.join(dst,end_part) if not os.path.isdir(ctree_dst): shutil.copytree(obj,ctree_dst) else: copy_glob(os.path.join(obj,"*"),ctree_dst) else: shutil.copy2(obj,dst)
Fix bug in copy_glob when destination directory already has files
Fix bug in copy_glob when destination directory already has files
Python
lgpl-2.1
rlee287/pyautoupdate,rlee287/pyautoupdate
python
## Code Before: import glob import shutil import os if os.name == "nt": from .ntcommonpath import commonpath else: from .posixcommonpath import commonpath def move_glob(src,dst): """Moves files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): shutil.move(obj,dst) def copy_glob(src,dst): """Copies files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): if os.path.isdir(obj): start_part=commonpath([src,obj]) end_part=os.path.relpath(obj,start_part) shutil.copytree(obj,os.path.join(dst,end_part)) else: shutil.copy2(obj,dst) ## Instruction: Fix bug in copy_glob when destination directory already has files ## Code After: import glob import shutil import os if os.name == "nt": from .ntcommonpath import commonpath else: from .posixcommonpath import commonpath def move_glob(src,dst): """Moves files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): shutil.move(obj,dst) def copy_glob(src,dst): """Copies files from src to dest. src may be any glob to recognize files. dst must be a folder.""" for obj in glob.iglob(src): if os.path.isdir(obj): start_part=commonpath([src,obj]) end_part=os.path.relpath(obj,start_part) ctree_dst=os.path.join(dst,end_part) if not os.path.isdir(ctree_dst): shutil.copytree(obj,ctree_dst) else: copy_glob(os.path.join(obj,"*"),ctree_dst) else: shutil.copy2(obj,dst)
# ... existing code ... if os.path.isdir(obj): start_part=commonpath([src,obj]) end_part=os.path.relpath(obj,start_part) ctree_dst=os.path.join(dst,end_part) if not os.path.isdir(ctree_dst): shutil.copytree(obj,ctree_dst) else: copy_glob(os.path.join(obj,"*"),ctree_dst) else: shutil.copy2(obj,dst) # ... rest of the code ...
ddeabd76c4277c35d1e583d1a2034ba2c047d128
spacy/__init__.py
spacy/__init__.py
import pathlib from .util import set_lang_class, get_lang_class from . import en from . import de from . import zh try: basestring except NameError: basestring = str set_lang_class(en.English.lang, en.English) set_lang_class(de.German.lang, de.German) set_lang_class(zh.Chinese.lang, zh.Chinese) def load(name, **overrides): target_name, target_version = util.split_data_name(name) path = overrides.get('path', util.get_data_path()) path = util.match_best_version(target_name, target_version, path) if isinstance(overrides.get('vectors'), basestring): vectors = util.match_best_version(overrides.get('vectors'), None, path) cls = get_lang_class(target_name) return cls(path=path, **overrides)
import pathlib from .util import set_lang_class, get_lang_class from . import en from . import de from . import zh try: basestring except NameError: basestring = str set_lang_class(en.English.lang, en.English) set_lang_class(de.German.lang, de.German) set_lang_class(zh.Chinese.lang, zh.Chinese) def load(name, **overrides): target_name, target_version = util.split_data_name(name) path = overrides.get('path', util.get_data_path()) path = util.match_best_version(target_name, target_version, path) if isinstance(overrides.get('vectors'), basestring): vectors_path = util.match_best_version(overrides.get('vectors'), None, path) overrides['vectors'] = lambda nlp: nlp.vocab.load_vectors_from_bin_loc( vectors_path / 'vocab' / 'vec.bin') cls = get_lang_class(target_name) return cls(path=path, **overrides)
Fix mistake loading GloVe vectors. GloVe vectors now loaded by default if present, as promised.
Fix mistake loading GloVe vectors. GloVe vectors now loaded by default if present, as promised.
Python
mit
spacy-io/spaCy,raphael0202/spaCy,raphael0202/spaCy,explosion/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,oroszgy/spaCy.hu,honnibal/spaCy,banglakit/spaCy,recognai/spaCy,raphael0202/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,banglakit/spaCy,explosion/spaCy,Gregory-Howard/spaCy,recognai/spaCy,banglakit/spaCy,explosion/spaCy,raphael0202/spaCy,raphael0202/spaCy,aikramer2/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,recognai/spaCy,recognai/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,Gregory-Howard/spaCy,aikramer2/spaCy,recognai/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,recognai/spaCy,aikramer2/spaCy,banglakit/spaCy,banglakit/spaCy,raphael0202/spaCy
python
## Code Before: import pathlib from .util import set_lang_class, get_lang_class from . import en from . import de from . import zh try: basestring except NameError: basestring = str set_lang_class(en.English.lang, en.English) set_lang_class(de.German.lang, de.German) set_lang_class(zh.Chinese.lang, zh.Chinese) def load(name, **overrides): target_name, target_version = util.split_data_name(name) path = overrides.get('path', util.get_data_path()) path = util.match_best_version(target_name, target_version, path) if isinstance(overrides.get('vectors'), basestring): vectors = util.match_best_version(overrides.get('vectors'), None, path) cls = get_lang_class(target_name) return cls(path=path, **overrides) ## Instruction: Fix mistake loading GloVe vectors. GloVe vectors now loaded by default if present, as promised. ## Code After: import pathlib from .util import set_lang_class, get_lang_class from . import en from . import de from . import zh try: basestring except NameError: basestring = str set_lang_class(en.English.lang, en.English) set_lang_class(de.German.lang, de.German) set_lang_class(zh.Chinese.lang, zh.Chinese) def load(name, **overrides): target_name, target_version = util.split_data_name(name) path = overrides.get('path', util.get_data_path()) path = util.match_best_version(target_name, target_version, path) if isinstance(overrides.get('vectors'), basestring): vectors_path = util.match_best_version(overrides.get('vectors'), None, path) overrides['vectors'] = lambda nlp: nlp.vocab.load_vectors_from_bin_loc( vectors_path / 'vocab' / 'vec.bin') cls = get_lang_class(target_name) return cls(path=path, **overrides)
... path = util.match_best_version(target_name, target_version, path) if isinstance(overrides.get('vectors'), basestring): vectors_path = util.match_best_version(overrides.get('vectors'), None, path) overrides['vectors'] = lambda nlp: nlp.vocab.load_vectors_from_bin_loc( vectors_path / 'vocab' / 'vec.bin') cls = get_lang_class(target_name) return cls(path=path, **overrides) ...
de69c4048fe8533185a4eca6f98c7d74967618bf
opentreemap/opentreemap/util.py
opentreemap/opentreemap/util.py
from django.views.decorators.csrf import csrf_exempt import json def route(**kwargs): @csrf_exempt def routed(request, *args2, **kwargs2): method = request.method req_method = kwargs[method] return req_method(request, *args2, **kwargs2) return routed def json_from_request(request): body = request.body if body: return json.loads(body) else: return None def merge_view_contexts(viewfns): def wrapped(*args, **kwargs): context = {} for viewfn in viewfns: context.update(viewfn(*args, **kwargs)) return context return wrapped
from __future__ import print_function from __future__ import unicode_literals from __future__ import division import json from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, HttpResponseRedirect, Http404 def route(**kwargs): @csrf_exempt def routed(request, *args2, **kwargs2): method = request.method if method not in kwargs: raise Http404() else: req_method = kwargs[method] return req_method(request, *args2, **kwargs2) return routed def json_from_request(request): body = request.body if body: return json.loads(body) else: return None def merge_view_contexts(viewfns): def wrapped(*args, **kwargs): context = {} for viewfn in viewfns: context.update(viewfn(*args, **kwargs)) return context return wrapped
Return a 404, not a 500 on a verb mismatch
Return a 404, not a 500 on a verb mismatch Fixes #1101
Python
agpl-3.0
maurizi/otm-core,maurizi/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,RickMohr/otm-core,recklessromeo/otm-core,recklessromeo/otm-core,maurizi/otm-core,RickMohr/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,maurizi/otm-core
python
## Code Before: from django.views.decorators.csrf import csrf_exempt import json def route(**kwargs): @csrf_exempt def routed(request, *args2, **kwargs2): method = request.method req_method = kwargs[method] return req_method(request, *args2, **kwargs2) return routed def json_from_request(request): body = request.body if body: return json.loads(body) else: return None def merge_view_contexts(viewfns): def wrapped(*args, **kwargs): context = {} for viewfn in viewfns: context.update(viewfn(*args, **kwargs)) return context return wrapped ## Instruction: Return a 404, not a 500 on a verb mismatch Fixes #1101 ## Code After: from __future__ import print_function from __future__ import unicode_literals from __future__ import division import json from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, HttpResponseRedirect, Http404 def route(**kwargs): @csrf_exempt def routed(request, *args2, **kwargs2): method = request.method if method not in kwargs: raise Http404() else: req_method = kwargs[method] return req_method(request, *args2, **kwargs2) return routed def json_from_request(request): body = request.body if body: return json.loads(body) else: return None def merge_view_contexts(viewfns): def wrapped(*args, **kwargs): context = {} for viewfn in viewfns: context.update(viewfn(*args, **kwargs)) return context return wrapped
# ... existing code ... from __future__ import print_function from __future__ import unicode_literals from __future__ import division import json from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, HttpResponseRedirect, Http404 def route(**kwargs): # ... modified code ... @csrf_exempt def routed(request, *args2, **kwargs2): method = request.method if method not in kwargs: raise Http404() else: req_method = kwargs[method] return req_method(request, *args2, **kwargs2) return routed # ... rest of the code ...
a0adfab8c2fdac2f2b8bad8b1f036bd35b27a06c
setup.py
setup.py
import re import setuptools import sys if not sys.version_info >= (3, 5): exit("Sorry, Python must be later than 3.5.") setuptools.setup( name="tensorflow-qnd", version=re.search(r'__version__ *= *"([0-9]+\.[0-9]+\.[0-9]+)" *\n', open("qnd/__init__.py").read()).group(1), description="Quick and Dirty TensorFlow command framework", long_description=open("README.md").read(), license="Public Domain", author="Yota Toyama", author_email="[email protected]", url="https://github.com/raviqqe/tensorflow-qnd/", packages=["qnd"], install_requires=["gargparse"], classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: Public Domain", "Programming Language :: Python :: 3.5", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: System :: Networking", ], )
import re import setuptools import sys if not sys.version_info >= (3, 5): exit("Sorry, Python must be later than 3.5.") setuptools.setup( name="tensorflow-qnd", version=re.search(r'__version__ *= *"([0-9]+\.[0-9]+\.[0-9]+)" *\n', open("qnd/__init__.py").read()).group(1), description="Quick and Dirty TensorFlow command framework", long_description=open("README.md").read(), license="Public Domain", author="Yota Toyama", author_email="[email protected]", url="https://github.com/raviqqe/tensorflow-qnd/", packages=["qnd"], install_requires=["gargparse"], classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: Public Domain", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: System :: Networking", ], )
Add Python 3.6 to topics
Add Python 3.6 to topics
Python
unlicense
raviqqe/tensorflow-qnd,raviqqe/tensorflow-qnd
python
## Code Before: import re import setuptools import sys if not sys.version_info >= (3, 5): exit("Sorry, Python must be later than 3.5.") setuptools.setup( name="tensorflow-qnd", version=re.search(r'__version__ *= *"([0-9]+\.[0-9]+\.[0-9]+)" *\n', open("qnd/__init__.py").read()).group(1), description="Quick and Dirty TensorFlow command framework", long_description=open("README.md").read(), license="Public Domain", author="Yota Toyama", author_email="[email protected]", url="https://github.com/raviqqe/tensorflow-qnd/", packages=["qnd"], install_requires=["gargparse"], classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: Public Domain", "Programming Language :: Python :: 3.5", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: System :: Networking", ], ) ## Instruction: Add Python 3.6 to topics ## Code After: import re import setuptools import sys if not sys.version_info >= (3, 5): exit("Sorry, Python must be later than 3.5.") setuptools.setup( name="tensorflow-qnd", version=re.search(r'__version__ *= *"([0-9]+\.[0-9]+\.[0-9]+)" *\n', open("qnd/__init__.py").read()).group(1), description="Quick and Dirty TensorFlow command framework", long_description=open("README.md").read(), license="Public Domain", author="Yota Toyama", author_email="[email protected]", url="https://github.com/raviqqe/tensorflow-qnd/", packages=["qnd"], install_requires=["gargparse"], classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "License :: Public Domain", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: System :: Networking", ], )
// ... existing code ... "Intended Audience :: Developers", "License :: Public Domain", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: System :: Networking", ], // ... rest of the code ...
96300cfe78916e7ddc65a48d85cece55ef34ea01
scrapers/examples/test.py
scrapers/examples/test.py
scheduler = globals()['scheduler'] # Write everything inside one giant function so that function can be scheduled # for later execution. def scrape_test(): """ This scraper illustrates the following: * How to access Narcissa's config * How to store and access local config variables * How to schedule a scraper * How to run a scraper immediately """ # Config usually comes first so the user sees it right away. MY_NAME = 'Lil B the Based God' # Imports usually come next. import config from datetime import datetime # Program logic goes here. Whatever you use in a normal Python script will # work as long as it's inside this function. class MyClass: def __init__(self): self.greeting = 'Hello!' def get_my_name(): return MY_NAME c = MyClass() print(c.greeting + ' My name is ' + get_my_name()) print('DB_URI: %s' % config.DB_URI) print('Right now: %s' % datetime.now()) # Schedule this task to run every 3 seconds. # It will run immediately as well. scheduler.every(3).seconds.do(scrape_test)
scheduler = globals()['scheduler'] # Write everything inside one giant function so that function can be scheduled # for later execution. # This function MUST be named uniquely so it doesn't interfere with other # scrapers or Narcissa functions. One safe way to name functions is to use the # scrape_ prefix with the filename of the scraper. def scrape_test(): """ This scraper illustrates the following: * How to access Narcissa's config * How to store and access local config variables * How to schedule a scraper * How to run a scraper immediately """ # Config usually comes first so the user sees it right away. MY_NAME = 'Lil B the Based God' # Imports usually come next. import config from datetime import datetime # Program logic goes here. Whatever you use in a normal Python script will # work as long as it's inside this function. class MyClass: def __init__(self): self.greeting = 'Hello!' def get_my_name(): return MY_NAME c = MyClass() print(c.greeting + ' My name is ' + get_my_name()) print('DB_URI: %s' % config.DB_URI) print('Right now: %s' % datetime.now()) # Schedule this task to run every 3 seconds. # It will run immediately as well. scheduler.every(3).seconds.do(scrape_test)
Add note about naming functions uniquely
Add note about naming functions uniquely
Python
mit
mplewis/narcissa
python
## Code Before: scheduler = globals()['scheduler'] # Write everything inside one giant function so that function can be scheduled # for later execution. def scrape_test(): """ This scraper illustrates the following: * How to access Narcissa's config * How to store and access local config variables * How to schedule a scraper * How to run a scraper immediately """ # Config usually comes first so the user sees it right away. MY_NAME = 'Lil B the Based God' # Imports usually come next. import config from datetime import datetime # Program logic goes here. Whatever you use in a normal Python script will # work as long as it's inside this function. class MyClass: def __init__(self): self.greeting = 'Hello!' def get_my_name(): return MY_NAME c = MyClass() print(c.greeting + ' My name is ' + get_my_name()) print('DB_URI: %s' % config.DB_URI) print('Right now: %s' % datetime.now()) # Schedule this task to run every 3 seconds. # It will run immediately as well. scheduler.every(3).seconds.do(scrape_test) ## Instruction: Add note about naming functions uniquely ## Code After: scheduler = globals()['scheduler'] # Write everything inside one giant function so that function can be scheduled # for later execution. # This function MUST be named uniquely so it doesn't interfere with other # scrapers or Narcissa functions. One safe way to name functions is to use the # scrape_ prefix with the filename of the scraper. def scrape_test(): """ This scraper illustrates the following: * How to access Narcissa's config * How to store and access local config variables * How to schedule a scraper * How to run a scraper immediately """ # Config usually comes first so the user sees it right away. MY_NAME = 'Lil B the Based God' # Imports usually come next. import config from datetime import datetime # Program logic goes here. Whatever you use in a normal Python script will # work as long as it's inside this function. class MyClass: def __init__(self): self.greeting = 'Hello!' def get_my_name(): return MY_NAME c = MyClass() print(c.greeting + ' My name is ' + get_my_name()) print('DB_URI: %s' % config.DB_URI) print('Right now: %s' % datetime.now()) # Schedule this task to run every 3 seconds. # It will run immediately as well. scheduler.every(3).seconds.do(scrape_test)
// ... existing code ... # Write everything inside one giant function so that function can be scheduled # for later execution. # This function MUST be named uniquely so it doesn't interfere with other # scrapers or Narcissa functions. One safe way to name functions is to use the # scrape_ prefix with the filename of the scraper. def scrape_test(): """ This scraper illustrates the following: // ... rest of the code ...
e3634e4bf0ae1dde74de422dfd0f977f3d525467
utility/src/main/java/org/lemurproject/galago/utility/buffer/DataStream.java
utility/src/main/java/org/lemurproject/galago/utility/buffer/DataStream.java
// BSD License (http://www.galagosearch.org/license) package org.lemurproject.galago.utility.buffer; import java.io.DataInput; import java.io.IOException; import java.io.InputStream; /** * * @author trevor */ public abstract class DataStream extends InputStream implements DataInput { public abstract DataStream subStream(long start, long length) throws IOException; public abstract long getPosition(); public abstract boolean isDone(); public abstract long length(); @Override public int read() throws IOException { if(isDone()) { return -1; } return readUnsignedByte(); } /** * Seeks forward into the stream to a particular byte offset (reverse * seeks are not allowed). The offset is relative to the start position of * this data stream, not the beginning of the file. */ public abstract void seek(long offset); }
// BSD License (http://www.galagosearch.org/license) package org.lemurproject.galago.utility.buffer; import java.io.DataInput; import java.io.IOException; import java.io.InputStream; /** * * @author trevor */ public abstract class DataStream extends InputStream implements DataInput { public abstract DataStream subStream(long start, long length) throws IOException; public abstract long getPosition(); public abstract boolean isDone(); public abstract long length(); @Override public int read() throws IOException { if(isDone()) { return -1; } return readUnsignedByte(); } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { int read; for(read=0; read<len && !isDone(); read++) { b[off+read] = (byte) readUnsignedByte(); } return read; } /** * Seeks forward into the stream to a particular byte offset (reverse * seeks are not allowed). The offset is relative to the start position of * this data stream, not the beginning of the file. */ public abstract void seek(long offset); }
Speed up the InputStream interface on Galago's cached stream class.
Speed up the InputStream interface on Galago's cached stream class.
Java
bsd-3-clause
jjfiv/galago-git,hzhao/galago-git,jjfiv/galago-git,jjfiv/galago-git,hzhao/galago-git,hzhao/galago-git
java
## Code Before: // BSD License (http://www.galagosearch.org/license) package org.lemurproject.galago.utility.buffer; import java.io.DataInput; import java.io.IOException; import java.io.InputStream; /** * * @author trevor */ public abstract class DataStream extends InputStream implements DataInput { public abstract DataStream subStream(long start, long length) throws IOException; public abstract long getPosition(); public abstract boolean isDone(); public abstract long length(); @Override public int read() throws IOException { if(isDone()) { return -1; } return readUnsignedByte(); } /** * Seeks forward into the stream to a particular byte offset (reverse * seeks are not allowed). The offset is relative to the start position of * this data stream, not the beginning of the file. */ public abstract void seek(long offset); } ## Instruction: Speed up the InputStream interface on Galago's cached stream class. ## Code After: // BSD License (http://www.galagosearch.org/license) package org.lemurproject.galago.utility.buffer; import java.io.DataInput; import java.io.IOException; import java.io.InputStream; /** * * @author trevor */ public abstract class DataStream extends InputStream implements DataInput { public abstract DataStream subStream(long start, long length) throws IOException; public abstract long getPosition(); public abstract boolean isDone(); public abstract long length(); @Override public int read() throws IOException { if(isDone()) { return -1; } return readUnsignedByte(); } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { int read; for(read=0; read<len && !isDone(); read++) { b[off+read] = (byte) readUnsignedByte(); } return read; } /** * Seeks forward into the stream to a particular byte offset (reverse * seeks are not allowed). The offset is relative to the start position of * this data stream, not the beginning of the file. */ public abstract void seek(long offset); }
# ... existing code ... return readUnsignedByte(); } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { int read; for(read=0; read<len && !isDone(); read++) { b[off+read] = (byte) readUnsignedByte(); } return read; } /** * Seeks forward into the stream to a particular byte offset (reverse * seeks are not allowed). The offset is relative to the start position of # ... rest of the code ...
9e2a69cb631623ae004dff094ff0fbc9e952984f
src/main/java/org/cyclops/integratedtunnels/part/PartStatePlayerSimulator.java
src/main/java/org/cyclops/integratedtunnels/part/PartStatePlayerSimulator.java
package org.cyclops.integratedtunnels.part; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import org.cyclops.integrateddynamics.api.part.PartTarget; import org.cyclops.integrateddynamics.core.part.write.PartStateWriterBase; import org.cyclops.integratedtunnels.core.ExtendedFakePlayer; import org.cyclops.integratedtunnels.core.ItemHandlerPlayerWrapper; /** * A part state for holding a temporary player inventory. * @author rubensworks */ public class PartStatePlayerSimulator extends PartStateWriterBase<PartTypePlayerSimulator> { private ExtendedFakePlayer player = null; public PartStatePlayerSimulator(int inventorySize) { super(inventorySize); } public ExtendedFakePlayer getPlayer() { return player; } public void update(PartTarget target) { World world = target.getTarget().getPos().getWorld(); if (!world.isRemote) { if (player == null) { player = new ExtendedFakePlayer((WorldServer) world); } ItemHandlerPlayerWrapper.cancelDestroyingBlock(player); } } }
package org.cyclops.integratedtunnels.part; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import org.cyclops.integrateddynamics.api.part.PartTarget; import org.cyclops.integrateddynamics.core.part.write.PartStateWriterBase; import org.cyclops.integratedtunnels.core.ExtendedFakePlayer; import org.cyclops.integratedtunnels.core.ItemHandlerPlayerWrapper; /** * A part state for holding a temporary player inventory. * @author rubensworks */ public class PartStatePlayerSimulator extends PartStateWriterBase<PartTypePlayerSimulator> { private ExtendedFakePlayer player = null; public PartStatePlayerSimulator(int inventorySize) { super(inventorySize); } public ExtendedFakePlayer getPlayer() { return player; } public void update(PartTarget target) { World world = target.getTarget().getPos().getWorld(); if (!world.isRemote) { if (player == null) { player = new ExtendedFakePlayer((WorldServer) world); } ItemHandlerPlayerWrapper.cancelDestroyingBlock(player); } } @Override protected int getDefaultUpdateInterval() { return 10; } }
Set default player simulator tickrate to 10 ticks
Set default player simulator tickrate to 10 ticks
Java
mit
CyclopsMC/IntegratedTunnels
java
## Code Before: package org.cyclops.integratedtunnels.part; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import org.cyclops.integrateddynamics.api.part.PartTarget; import org.cyclops.integrateddynamics.core.part.write.PartStateWriterBase; import org.cyclops.integratedtunnels.core.ExtendedFakePlayer; import org.cyclops.integratedtunnels.core.ItemHandlerPlayerWrapper; /** * A part state for holding a temporary player inventory. * @author rubensworks */ public class PartStatePlayerSimulator extends PartStateWriterBase<PartTypePlayerSimulator> { private ExtendedFakePlayer player = null; public PartStatePlayerSimulator(int inventorySize) { super(inventorySize); } public ExtendedFakePlayer getPlayer() { return player; } public void update(PartTarget target) { World world = target.getTarget().getPos().getWorld(); if (!world.isRemote) { if (player == null) { player = new ExtendedFakePlayer((WorldServer) world); } ItemHandlerPlayerWrapper.cancelDestroyingBlock(player); } } } ## Instruction: Set default player simulator tickrate to 10 ticks ## Code After: package org.cyclops.integratedtunnels.part; import net.minecraft.world.World; import net.minecraft.world.WorldServer; import org.cyclops.integrateddynamics.api.part.PartTarget; import org.cyclops.integrateddynamics.core.part.write.PartStateWriterBase; import org.cyclops.integratedtunnels.core.ExtendedFakePlayer; import org.cyclops.integratedtunnels.core.ItemHandlerPlayerWrapper; /** * A part state for holding a temporary player inventory. * @author rubensworks */ public class PartStatePlayerSimulator extends PartStateWriterBase<PartTypePlayerSimulator> { private ExtendedFakePlayer player = null; public PartStatePlayerSimulator(int inventorySize) { super(inventorySize); } public ExtendedFakePlayer getPlayer() { return player; } public void update(PartTarget target) { World world = target.getTarget().getPos().getWorld(); if (!world.isRemote) { if (player == null) { player = new ExtendedFakePlayer((WorldServer) world); } ItemHandlerPlayerWrapper.cancelDestroyingBlock(player); } } @Override protected int getDefaultUpdateInterval() { return 10; } }
// ... existing code ... ItemHandlerPlayerWrapper.cancelDestroyingBlock(player); } } @Override protected int getDefaultUpdateInterval() { return 10; } } // ... rest of the code ...
ce2aa429b587714faaec43f13b345a8be80765d5
dev/multiple_renderer_separate_schema/renderman/RendermanTypes.h
dev/multiple_renderer_separate_schema/renderman/RendermanTypes.h
typedef std::vector<RtInt> RtIntContainer; typedef std::vector<RtFloat> RtFloatContainer; /*! * \remark Alembic does not support "holes" but to be safe, we are targeting * RiPointsGeneralPolygons to future proof our code * * RtVoid RiPointsGeneralPolygons(RtInt npolys, RtInt nloops[], * RtInt nvertices[], * RtInt vertices[], ...); * */ struct RendermanMeshData { V3fSamplingArray2D _P_data_array; // Assumes topological stability RtInt _npolys; RtIntContainer _nloops_data; RtIntContainer _nvertices_data; RtIntContainer _vertices_data; }; struct RendermanPointsData { V3fSamplingArray2D _P_data_array; // Assumes topological stability RtFloat _constantwidth; RtIntContainer _ids_data; RtFloatContainer _width_data; }; // == Emacs ================ // ------------------------- // Local variables: // tab-width: 4 // indent-tabs-mode: t // c-basic-offset: 4 // end: // // == vi =================== // ------------------------- // Format block // ex:ts=4:sw=4:expandtab // -------------------------
typedef std::vector<RtInt> RtIntContainer; typedef std::vector<RtFloat> RtFloatContainer; /*! * \remark Alembic does not support "holes" but to be safe, we are targeting * RiPointsGeneralPolygons to future proof our code * * RtVoid RiPointsGeneralPolygons(RtInt npolys, RtInt nloops[], * RtInt nvertices[], * RtInt vertices[], ...); * */ struct RendermanMeshData { V3fSamplingArray2D _P_data_array; // Assumes topological stability RtInt _npolys; RtIntContainer _nloops_data; RtIntContainer _nvertices_data; RtIntContainer _vertices_data; }; struct RendermanPointsData { V3fSamplingArray2D _P_data_array; // Assumes topological stability RtIntContainer _ids_data; RtFloatContainer _width_data; }; // == Emacs ================ // ------------------------- // Local variables: // tab-width: 4 // indent-tabs-mode: t // c-basic-offset: 4 // end: // // == vi =================== // ------------------------- // Format block // ex:ts=4:sw=4:expandtab // -------------------------
Remove _constantwidth as there are other was to determine that via the length of the _width_data vector
Remove _constantwidth as there are other was to determine that via the length of the _width_data vector
C
apache-2.0
nyue/SegmentedInterpolativeMotionBlurAlembic,nyue/SegmentedInterpolativeMotionBlurAlembic
c
## Code Before: typedef std::vector<RtInt> RtIntContainer; typedef std::vector<RtFloat> RtFloatContainer; /*! * \remark Alembic does not support "holes" but to be safe, we are targeting * RiPointsGeneralPolygons to future proof our code * * RtVoid RiPointsGeneralPolygons(RtInt npolys, RtInt nloops[], * RtInt nvertices[], * RtInt vertices[], ...); * */ struct RendermanMeshData { V3fSamplingArray2D _P_data_array; // Assumes topological stability RtInt _npolys; RtIntContainer _nloops_data; RtIntContainer _nvertices_data; RtIntContainer _vertices_data; }; struct RendermanPointsData { V3fSamplingArray2D _P_data_array; // Assumes topological stability RtFloat _constantwidth; RtIntContainer _ids_data; RtFloatContainer _width_data; }; // == Emacs ================ // ------------------------- // Local variables: // tab-width: 4 // indent-tabs-mode: t // c-basic-offset: 4 // end: // // == vi =================== // ------------------------- // Format block // ex:ts=4:sw=4:expandtab // ------------------------- ## Instruction: Remove _constantwidth as there are other was to determine that via the length of the _width_data vector ## Code After: typedef std::vector<RtInt> RtIntContainer; typedef std::vector<RtFloat> RtFloatContainer; /*! * \remark Alembic does not support "holes" but to be safe, we are targeting * RiPointsGeneralPolygons to future proof our code * * RtVoid RiPointsGeneralPolygons(RtInt npolys, RtInt nloops[], * RtInt nvertices[], * RtInt vertices[], ...); * */ struct RendermanMeshData { V3fSamplingArray2D _P_data_array; // Assumes topological stability RtInt _npolys; RtIntContainer _nloops_data; RtIntContainer _nvertices_data; RtIntContainer _vertices_data; }; struct RendermanPointsData { V3fSamplingArray2D _P_data_array; // Assumes topological stability RtIntContainer _ids_data; RtFloatContainer _width_data; }; // == Emacs ================ // ------------------------- // Local variables: // tab-width: 4 // indent-tabs-mode: t // c-basic-offset: 4 // end: // // == vi =================== // ------------------------- // Format block // ex:ts=4:sw=4:expandtab // -------------------------
# ... existing code ... { V3fSamplingArray2D _P_data_array; // Assumes topological stability RtIntContainer _ids_data; RtFloatContainer _width_data; }; # ... rest of the code ...
5fffb9f49cd7b1237a0bfed0faebf16ef5cdeec1
lib/sanitizer_common/sanitizer_platform_interceptors.h
lib/sanitizer_common/sanitizer_platform_interceptors.h
//===-- sanitizer_platform_interceptors.h -----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines macro telling whether sanitizer tools can/should intercept // given library functions on a given platform. // //===----------------------------------------------------------------------===// #include "sanitizer_internal_defs.h" #if !defined(_WIN32) # define SI_NOT_WINDOWS 1 #else # define SI_NOT_WINDOWS 0 #endif #if defined(__linux__) && !defined(ANDROID) # define SI_LINUX_NOT_ANDROID 1 #else # define SI_LINUX_NOT_ANDROID 0 #endif # define SANITIZER_INTERCEPT_READ SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_PREAD SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_WRITE SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_PWRITE SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_PREAD64 SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_PWRITE64 SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_PRCTL SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_SCANF 1
//===-- sanitizer_platform_interceptors.h -----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines macro telling whether sanitizer tools can/should intercept // given library functions on a given platform. // //===----------------------------------------------------------------------===// #include "sanitizer_internal_defs.h" #if !defined(_WIN32) # define SI_NOT_WINDOWS 1 #else # define SI_NOT_WINDOWS 0 #endif #if defined(__linux__) && !defined(ANDROID) # define SI_LINUX_NOT_ANDROID 1 #else # define SI_LINUX_NOT_ANDROID 0 #endif # define SANITIZER_INTERCEPT_READ SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_PREAD SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_WRITE SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_PWRITE SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_PREAD64 SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_PWRITE64 SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_PRCTL SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_SCANF SI_NOT_WINDOWS
Disable scanf interceptor on windows.
[sanitizer] Disable scanf interceptor on windows. git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@173037 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
c
## Code Before: //===-- sanitizer_platform_interceptors.h -----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines macro telling whether sanitizer tools can/should intercept // given library functions on a given platform. // //===----------------------------------------------------------------------===// #include "sanitizer_internal_defs.h" #if !defined(_WIN32) # define SI_NOT_WINDOWS 1 #else # define SI_NOT_WINDOWS 0 #endif #if defined(__linux__) && !defined(ANDROID) # define SI_LINUX_NOT_ANDROID 1 #else # define SI_LINUX_NOT_ANDROID 0 #endif # define SANITIZER_INTERCEPT_READ SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_PREAD SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_WRITE SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_PWRITE SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_PREAD64 SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_PWRITE64 SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_PRCTL SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_SCANF 1 ## Instruction: [sanitizer] Disable scanf interceptor on windows. git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@173037 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: //===-- sanitizer_platform_interceptors.h -----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines macro telling whether sanitizer tools can/should intercept // given library functions on a given platform. // //===----------------------------------------------------------------------===// #include "sanitizer_internal_defs.h" #if !defined(_WIN32) # define SI_NOT_WINDOWS 1 #else # define SI_NOT_WINDOWS 0 #endif #if defined(__linux__) && !defined(ANDROID) # define SI_LINUX_NOT_ANDROID 1 #else # define SI_LINUX_NOT_ANDROID 0 #endif # define SANITIZER_INTERCEPT_READ SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_PREAD SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_WRITE SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_PWRITE SI_NOT_WINDOWS # define SANITIZER_INTERCEPT_PREAD64 SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_PWRITE64 SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_PRCTL SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_SCANF SI_NOT_WINDOWS
// ... existing code ... # define SANITIZER_INTERCEPT_PWRITE64 SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_PRCTL SI_LINUX_NOT_ANDROID # define SANITIZER_INTERCEPT_SCANF SI_NOT_WINDOWS // ... rest of the code ...
0056d2e4667810af45a820e6b8893c49e2f1cf49
salt/utils/verify.py
salt/utils/verify.py
''' A few checks to make sure the environment is sane ''' # Original Author: Jeff Schroeder <[email protected]> import logging log = logging.getLogger(__name__) __all__ = ('zmq_version', 'run') def zmq_version(): '''ZeroMQ python bindings >= 2.1.9 are required''' import zmq ver = zmq.__version__ ver_int = int(ver.replace('.', '')) if not ver_int >= 219: log.critical("ZeroMQ python bindings >= 2.1.9 are required") return False return True def check_root(): ''' Most of the salt scripts need to run as root, this function will simply verify that root is the user before the application discovers it. ''' if os.getuid(): print ('Sorry, the salt must run as root, it needs to operate ' 'in a privileged environment to do what it does.\n' 'http://xkcd.com/838/') sys.exit(1) def run(): for func in __all__: if func == "run": continue if not locals().get(func)(): sys.exit(1)
''' A few checks to make sure the environment is sane ''' # Original Author: Jeff Schroeder <[email protected]> import logging log = logging.getLogger(__name__) __all__ = ('zmq_version', 'check_root', 'run') def zmq_version(): '''ZeroMQ python bindings >= 2.1.9 are required''' import zmq ver = zmq.__version__ ver_int = int(ver.replace('.', '')) if not ver_int >= 219: log.critical("ZeroMQ python bindings >= 2.1.9 are required") return False return True def check_root(): ''' Most of the salt scripts need to run as root, this function will simply verify that root is the user before the application discovers it. ''' if os.getuid(): log.critical('Sorry, the salt must run as root. It needs to operate in a privileged environment to do what it does. http://xkcd.com/838/') return False return True def run(): for func in __all__: if func == "run": continue if not locals().get(func)(): sys.exit(1)
Make check_root use proper logging and exit cleanly
Make check_root use proper logging and exit cleanly
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
python
## Code Before: ''' A few checks to make sure the environment is sane ''' # Original Author: Jeff Schroeder <[email protected]> import logging log = logging.getLogger(__name__) __all__ = ('zmq_version', 'run') def zmq_version(): '''ZeroMQ python bindings >= 2.1.9 are required''' import zmq ver = zmq.__version__ ver_int = int(ver.replace('.', '')) if not ver_int >= 219: log.critical("ZeroMQ python bindings >= 2.1.9 are required") return False return True def check_root(): ''' Most of the salt scripts need to run as root, this function will simply verify that root is the user before the application discovers it. ''' if os.getuid(): print ('Sorry, the salt must run as root, it needs to operate ' 'in a privileged environment to do what it does.\n' 'http://xkcd.com/838/') sys.exit(1) def run(): for func in __all__: if func == "run": continue if not locals().get(func)(): sys.exit(1) ## Instruction: Make check_root use proper logging and exit cleanly ## Code After: ''' A few checks to make sure the environment is sane ''' # Original Author: Jeff Schroeder <[email protected]> import logging log = logging.getLogger(__name__) __all__ = ('zmq_version', 'check_root', 'run') def zmq_version(): '''ZeroMQ python bindings >= 2.1.9 are required''' import zmq ver = zmq.__version__ ver_int = int(ver.replace('.', '')) if not ver_int >= 219: log.critical("ZeroMQ python bindings >= 2.1.9 are required") return False return True def check_root(): ''' Most of the salt scripts need to run as root, this function will simply verify that root is the user before the application discovers it. ''' if os.getuid(): log.critical('Sorry, the salt must run as root. It needs to operate in a privileged environment to do what it does. http://xkcd.com/838/') return False return True def run(): for func in __all__: if func == "run": continue if not locals().get(func)(): sys.exit(1)
... import logging log = logging.getLogger(__name__) __all__ = ('zmq_version', 'check_root', 'run') def zmq_version(): '''ZeroMQ python bindings >= 2.1.9 are required''' ... verify that root is the user before the application discovers it. ''' if os.getuid(): log.critical('Sorry, the salt must run as root. It needs to operate in a privileged environment to do what it does. http://xkcd.com/838/') return False return True def run(): for func in __all__: ...
65be9926d1e6d769fcf6d88a6a9788791beef187
id3lab/__init__.py
id3lab/__init__.py
import IPython import ts_charting.lab.lab as tslab import ipycli.standalone as sa from workbench import sharedx class ID3Lab(tslab.Lab): def get_varname(self): """ Try to get the variable that this lab is bound to in the IPython kernel """ inst = IPython.InteractiveShell._instance for k,v in inst.user_ns.iteritems(): if v is self and not k.startswith('_'): return k def link(self): name = self.get_varname() return sa.link(name) def _repr_javascript_(self): """ Output: stations: AAPL IBM <link> Note: Uses Javascript because sa.link() returns javascript. This is because sa.link needs to use the location.href to get the notebook_id since we cannot grab that from within the notebook kernel. """ js = """ element.append('{0}'); container.show(); """ station_text = '<strong>stations:</strong> <br />' station_text += '<br />'.join(self.stations.keys()) out = js.format(station_text) link = self.link().data out += 'element.append("<br />");' + link return out @property def html_obj(self): # for now default to sharedx return sharedx def __str__(self): return
import IPython import ts_charting.lab.lab as tslab import ipycli.standalone as sa from workbench import sharedx class ID3Lab(tslab.Lab): _html_obj = None def __init__(self, draw=False, html_obj=None): super(ID3Lab, self).__init__(draw=draw) if html_obj is None: html_obj = sharedx self._html_obj = html_obj def get_varname(self): """ Try to get the variable that this lab is bound to in the IPython kernel """ inst = IPython.InteractiveShell._instance for k,v in inst.user_ns.iteritems(): if v is self and not k.startswith('_'): return k def link(self): name = self.get_varname() return sa.link(name) def _repr_javascript_(self): """ Output: stations: AAPL IBM <link> Note: Uses Javascript because sa.link() returns javascript. This is because sa.link needs to use the location.href to get the notebook_id since we cannot grab that from within the notebook kernel. """ js = """ element.append('{0}'); container.show(); """ station_text = '<strong>stations:</strong> <br />' station_text += '<br />'.join(self.stations.keys()) out = js.format(station_text) link = self.link().data out += 'element.append("<br />");' + link return out @property def html_obj(self): return self._html_obj def __str__(self): return
Make ID3Lab allow attr to be pluggable
ENH: Make ID3Lab allow attr to be pluggable
Python
apache-2.0
dalejung/id3lab,dalejung/id3lab
python
## Code Before: import IPython import ts_charting.lab.lab as tslab import ipycli.standalone as sa from workbench import sharedx class ID3Lab(tslab.Lab): def get_varname(self): """ Try to get the variable that this lab is bound to in the IPython kernel """ inst = IPython.InteractiveShell._instance for k,v in inst.user_ns.iteritems(): if v is self and not k.startswith('_'): return k def link(self): name = self.get_varname() return sa.link(name) def _repr_javascript_(self): """ Output: stations: AAPL IBM <link> Note: Uses Javascript because sa.link() returns javascript. This is because sa.link needs to use the location.href to get the notebook_id since we cannot grab that from within the notebook kernel. """ js = """ element.append('{0}'); container.show(); """ station_text = '<strong>stations:</strong> <br />' station_text += '<br />'.join(self.stations.keys()) out = js.format(station_text) link = self.link().data out += 'element.append("<br />");' + link return out @property def html_obj(self): # for now default to sharedx return sharedx def __str__(self): return ## Instruction: ENH: Make ID3Lab allow attr to be pluggable ## Code After: import IPython import ts_charting.lab.lab as tslab import ipycli.standalone as sa from workbench import sharedx class ID3Lab(tslab.Lab): _html_obj = None def __init__(self, draw=False, html_obj=None): super(ID3Lab, self).__init__(draw=draw) if html_obj is None: html_obj = sharedx self._html_obj = html_obj def get_varname(self): """ Try to get the variable that this lab is bound to in the IPython kernel """ inst = IPython.InteractiveShell._instance for k,v in inst.user_ns.iteritems(): if v is self and not k.startswith('_'): return k def link(self): name = self.get_varname() return sa.link(name) def _repr_javascript_(self): """ Output: stations: AAPL IBM <link> Note: Uses Javascript because sa.link() returns javascript. This is because sa.link needs to use the location.href to get the notebook_id since we cannot grab that from within the notebook kernel. """ js = """ element.append('{0}'); container.show(); """ station_text = '<strong>stations:</strong> <br />' station_text += '<br />'.join(self.stations.keys()) out = js.format(station_text) link = self.link().data out += 'element.append("<br />");' + link return out @property def html_obj(self): return self._html_obj def __str__(self): return
... from workbench import sharedx class ID3Lab(tslab.Lab): _html_obj = None def __init__(self, draw=False, html_obj=None): super(ID3Lab, self).__init__(draw=draw) if html_obj is None: html_obj = sharedx self._html_obj = html_obj def get_varname(self): """ Try to get the variable that this lab is ... def _repr_javascript_(self): """ Output: stations: AAPL IBM ... <link> Note: Uses Javascript because sa.link() returns javascript. This is because sa.link needs to use the location.href to get the notebook_id since we cannot grab that from within the notebook kernel. """ js = """ element.append('{0}'); container.show(); """ ... @property def html_obj(self): return self._html_obj def __str__(self): return ...
3171e7e355536f41a6c517ca7128a152c2577829
anndata/tests/test_uns.py
anndata/tests/test_uns.py
import numpy as np import pandas as pd from anndata import AnnData def test_uns_color_subset(): # Tests for https://github.com/theislab/anndata/issues/257 obs = pd.DataFrame(index=[f"cell{i}" for i in range(5)]) obs["cat1"] = pd.Series(list("aabcd"), index=obs.index, dtype="category") obs["cat2"] = pd.Series(list("aabbb"), index=obs.index, dtype="category") uns = dict( cat1_colors=["red", "green", "blue"], cat2_colors=["red", "green", "blue"], ) adata = AnnData(np.ones((5, 5)), obs=obs, uns=uns) # If number of categories does not match number of colors, # they should be reset v = adata[:, [0, 1]] assert "cat1_colors" not in v.uns assert "cat2_colors" not in v.uns # Otherwise the colors should still match after reseting adata.uns["cat1_colors"] = ["red", "green", "blue", "yellow"] v = adata[[0, 1], :] assert len(v.uns["cat1_colors"]) == 1 assert v.uns["cat1_colors"][0] == "red"
import numpy as np import pandas as pd from anndata import AnnData def test_uns_color_subset(): # Tests for https://github.com/theislab/anndata/issues/257 obs = pd.DataFrame(index=[f"cell{i}" for i in range(5)]) obs["cat1"] = pd.Series(list("aabcd"), index=obs.index, dtype="category") obs["cat2"] = pd.Series(list("aabbb"), index=obs.index, dtype="category") uns = dict( cat1_colors=["red", "green", "blue"], cat2_colors=["red", "green", "blue"], ) adata = AnnData(np.ones((5, 5)), obs=obs, uns=uns) # If number of categories does not match number of colors, # they should be reset v = adata[:, [0, 1]] assert "cat1_colors" not in v.uns assert "cat2_colors" not in v.uns # Otherwise the colors should still match after reseting cat1_colors = ["red", "green", "blue", "yellow"] adata.uns["cat1_colors"] = cat1_colors.copy() v = adata[[0, 1], :] assert len(v.uns["cat1_colors"]) == 1 assert v.uns["cat1_colors"][0] == "red" # But original object should not change assert list(adata.uns["cat1_colors"]) == cat1_colors
Add test for categorical colors staying around after subsetting
Add test for categorical colors staying around after subsetting
Python
bsd-3-clause
theislab/anndata
python
## Code Before: import numpy as np import pandas as pd from anndata import AnnData def test_uns_color_subset(): # Tests for https://github.com/theislab/anndata/issues/257 obs = pd.DataFrame(index=[f"cell{i}" for i in range(5)]) obs["cat1"] = pd.Series(list("aabcd"), index=obs.index, dtype="category") obs["cat2"] = pd.Series(list("aabbb"), index=obs.index, dtype="category") uns = dict( cat1_colors=["red", "green", "blue"], cat2_colors=["red", "green", "blue"], ) adata = AnnData(np.ones((5, 5)), obs=obs, uns=uns) # If number of categories does not match number of colors, # they should be reset v = adata[:, [0, 1]] assert "cat1_colors" not in v.uns assert "cat2_colors" not in v.uns # Otherwise the colors should still match after reseting adata.uns["cat1_colors"] = ["red", "green", "blue", "yellow"] v = adata[[0, 1], :] assert len(v.uns["cat1_colors"]) == 1 assert v.uns["cat1_colors"][0] == "red" ## Instruction: Add test for categorical colors staying around after subsetting ## Code After: import numpy as np import pandas as pd from anndata import AnnData def test_uns_color_subset(): # Tests for https://github.com/theislab/anndata/issues/257 obs = pd.DataFrame(index=[f"cell{i}" for i in range(5)]) obs["cat1"] = pd.Series(list("aabcd"), index=obs.index, dtype="category") obs["cat2"] = pd.Series(list("aabbb"), index=obs.index, dtype="category") uns = dict( cat1_colors=["red", "green", "blue"], cat2_colors=["red", "green", "blue"], ) adata = AnnData(np.ones((5, 5)), obs=obs, uns=uns) # If number of categories does not match number of colors, # they should be reset v = adata[:, [0, 1]] assert "cat1_colors" not in v.uns assert "cat2_colors" not in v.uns # Otherwise the colors should still match after reseting cat1_colors = ["red", "green", "blue", "yellow"] adata.uns["cat1_colors"] = cat1_colors.copy() v = adata[[0, 1], :] assert len(v.uns["cat1_colors"]) == 1 assert v.uns["cat1_colors"][0] == "red" # But original object should not change assert list(adata.uns["cat1_colors"]) == cat1_colors
... assert "cat2_colors" not in v.uns # Otherwise the colors should still match after reseting cat1_colors = ["red", "green", "blue", "yellow"] adata.uns["cat1_colors"] = cat1_colors.copy() v = adata[[0, 1], :] assert len(v.uns["cat1_colors"]) == 1 assert v.uns["cat1_colors"][0] == "red" # But original object should not change assert list(adata.uns["cat1_colors"]) == cat1_colors ...
5f945f5335cd5d989401fe99b0752e98595748c0
chainer/functions/evaluation/binary_accuracy.py
chainer/functions/evaluation/binary_accuracy.py
import numpy from chainer import cuda from chainer import function from chainer.utils import type_check class BinaryAccuracy(function.Function): ignore_label = -1 def check_type_forward(self, in_types): type_check.expect(in_types.size() == 2) x_type, t_type = in_types type_check.expect( x_type.dtype == numpy.float32, t_type.dtype == numpy.int32, t_type.shape == x_type.shape, ) def forward(self, inputs): xp = cuda.get_array_module(*inputs) y, t = inputs # flatten y = y.ravel() t = t.ravel() c = (y >= 0) count = (t != self.ignore_label).sum() if int(count) == 0: count = 1 return xp.asarray((c == t).sum(dtype='f') / count, dtype='f'), def binary_accuracy(y, t): """Computes binary classification accuracy of the minibatch. Args: y (Variable): Variable holding a matrix whose i-th element indicates the score of positive at the i-th example. t (Variable): Variable holding an int32 vector of groundtruth labels. If ``t[i] == -1``, correspondig ``x[i]`` is ignored. Accuracy is zero if all groundtruth labels are ``-1``. Returns: Variable: A variable holding a scalar array of the accuracy. .. note:: This function is non-differentiable. """ return BinaryAccuracy()(y, t)
import numpy from chainer import cuda from chainer import function from chainer.utils import type_check class BinaryAccuracy(function.Function): ignore_label = -1 def check_type_forward(self, in_types): type_check.expect(in_types.size() == 2) x_type, t_type = in_types type_check.expect( x_type.dtype == numpy.float32, t_type.dtype == numpy.int32, t_type.shape == x_type.shape, ) def forward(self, inputs): xp = cuda.get_array_module(*inputs) y, t = inputs # flatten y = y.ravel() t = t.ravel() c = (y >= 0) count = xp.maximum(1, (t != self.ignore_label).sum()) return xp.asarray((c == t).sum(dtype='f') / count, dtype='f'), def binary_accuracy(y, t): """Computes binary classification accuracy of the minibatch. Args: y (Variable): Variable holding a matrix whose i-th element indicates the score of positive at the i-th example. t (Variable): Variable holding an int32 vector of groundtruth labels. If ``t[i] == -1``, correspondig ``x[i]`` is ignored. Accuracy is zero if all groundtruth labels are ``-1``. Returns: Variable: A variable holding a scalar array of the accuracy. .. note:: This function is non-differentiable. """ return BinaryAccuracy()(y, t)
Use maximum instead of if-statement
Use maximum instead of if-statement
Python
mit
cupy/cupy,keisuke-umezawa/chainer,benob/chainer,ktnyt/chainer,anaruse/chainer,AlpacaDB/chainer,ktnyt/chainer,rezoo/chainer,niboshi/chainer,ysekky/chainer,jnishi/chainer,keisuke-umezawa/chainer,jnishi/chainer,niboshi/chainer,hvy/chainer,chainer/chainer,okuta/chainer,okuta/chainer,wkentaro/chainer,keisuke-umezawa/chainer,ktnyt/chainer,niboshi/chainer,pfnet/chainer,wkentaro/chainer,aonotas/chainer,cupy/cupy,wkentaro/chainer,kashif/chainer,tkerola/chainer,delta2323/chainer,benob/chainer,AlpacaDB/chainer,hvy/chainer,hvy/chainer,kikusu/chainer,niboshi/chainer,kikusu/chainer,okuta/chainer,jnishi/chainer,cupy/cupy,chainer/chainer,wkentaro/chainer,kiyukuta/chainer,ktnyt/chainer,hvy/chainer,chainer/chainer,jnishi/chainer,cupy/cupy,chainer/chainer,okuta/chainer,ronekko/chainer,cemoody/chainer,keisuke-umezawa/chainer
python
## Code Before: import numpy from chainer import cuda from chainer import function from chainer.utils import type_check class BinaryAccuracy(function.Function): ignore_label = -1 def check_type_forward(self, in_types): type_check.expect(in_types.size() == 2) x_type, t_type = in_types type_check.expect( x_type.dtype == numpy.float32, t_type.dtype == numpy.int32, t_type.shape == x_type.shape, ) def forward(self, inputs): xp = cuda.get_array_module(*inputs) y, t = inputs # flatten y = y.ravel() t = t.ravel() c = (y >= 0) count = (t != self.ignore_label).sum() if int(count) == 0: count = 1 return xp.asarray((c == t).sum(dtype='f') / count, dtype='f'), def binary_accuracy(y, t): """Computes binary classification accuracy of the minibatch. Args: y (Variable): Variable holding a matrix whose i-th element indicates the score of positive at the i-th example. t (Variable): Variable holding an int32 vector of groundtruth labels. If ``t[i] == -1``, correspondig ``x[i]`` is ignored. Accuracy is zero if all groundtruth labels are ``-1``. Returns: Variable: A variable holding a scalar array of the accuracy. .. note:: This function is non-differentiable. """ return BinaryAccuracy()(y, t) ## Instruction: Use maximum instead of if-statement ## Code After: import numpy from chainer import cuda from chainer import function from chainer.utils import type_check class BinaryAccuracy(function.Function): ignore_label = -1 def check_type_forward(self, in_types): type_check.expect(in_types.size() == 2) x_type, t_type = in_types type_check.expect( x_type.dtype == numpy.float32, t_type.dtype == numpy.int32, t_type.shape == x_type.shape, ) def forward(self, inputs): xp = cuda.get_array_module(*inputs) y, t = inputs # flatten y = y.ravel() t = t.ravel() c = (y >= 0) count = xp.maximum(1, (t != self.ignore_label).sum()) return xp.asarray((c == t).sum(dtype='f') / count, dtype='f'), def binary_accuracy(y, t): """Computes binary classification accuracy of the minibatch. Args: y (Variable): Variable holding a matrix whose i-th element indicates the score of positive at the i-th example. t (Variable): Variable holding an int32 vector of groundtruth labels. If ``t[i] == -1``, correspondig ``x[i]`` is ignored. Accuracy is zero if all groundtruth labels are ``-1``. Returns: Variable: A variable holding a scalar array of the accuracy. .. note:: This function is non-differentiable. """ return BinaryAccuracy()(y, t)
... y = y.ravel() t = t.ravel() c = (y >= 0) count = xp.maximum(1, (t != self.ignore_label).sum()) return xp.asarray((c == t).sum(dtype='f') / count, dtype='f'), ...
ace54e86e9462b25acd1636e0e9905ba6decfe9b
admin_tools/dashboard/views.py
admin_tools/dashboard/views.py
from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from django.contrib import messages try: from django.views.decorators.csrf import csrf_exempt except ImportError: from django.contrib.csrf.middleware import csrf_exempt from .forms import DashboardPreferencesForm from .models import DashboardPreferences @login_required @csrf_exempt def set_preferences(request, dashboard_id): """ This view serves and validates a preferences form. """ try: preferences = DashboardPreferences.objects.get( user=request.user, dashboard_id=dashboard_id ) except DashboardPreferences.DoesNotExist: preferences = None if request.method == "POST": form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, data=request.POST, instance=preferences ) if form.is_valid(): preferences = form.save() if request.is_ajax(): return HttpResponse('true') messages.success(request, 'Preferences saved') elif request.is_ajax(): return HttpResponse('false') else: form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, instance=preferences ) return render_to_response('admin_tools/dashboard/preferences_form.html', RequestContext(request, {'form': form}))
from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from django.contrib import messages try: from django.views.decorators.csrf import csrf_exempt except ImportError: from django.contrib.csrf.middleware import csrf_exempt from .forms import DashboardPreferencesForm from .models import DashboardPreferences @staff_member_required @csrf_exempt def set_preferences(request, dashboard_id): """ This view serves and validates a preferences form. """ try: preferences = DashboardPreferences.objects.get( user=request.user, dashboard_id=dashboard_id ) except DashboardPreferences.DoesNotExist: preferences = None if request.method == "POST": form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, data=request.POST, instance=preferences ) if form.is_valid(): preferences = form.save() if request.is_ajax(): return HttpResponse('true') messages.success(request, 'Preferences saved') elif request.is_ajax(): return HttpResponse('false') else: form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, instance=preferences ) return render_to_response('admin_tools/dashboard/preferences_form.html', RequestContext(request, {'form': form}))
Use @staff_member_required decorator for the dashboard view as well
Use @staff_member_required decorator for the dashboard view as well
Python
mit
django-admin-tools/django-admin-tools,django-admin-tools/django-admin-tools,django-admin-tools/django-admin-tools
python
## Code Before: from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from django.contrib import messages try: from django.views.decorators.csrf import csrf_exempt except ImportError: from django.contrib.csrf.middleware import csrf_exempt from .forms import DashboardPreferencesForm from .models import DashboardPreferences @login_required @csrf_exempt def set_preferences(request, dashboard_id): """ This view serves and validates a preferences form. """ try: preferences = DashboardPreferences.objects.get( user=request.user, dashboard_id=dashboard_id ) except DashboardPreferences.DoesNotExist: preferences = None if request.method == "POST": form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, data=request.POST, instance=preferences ) if form.is_valid(): preferences = form.save() if request.is_ajax(): return HttpResponse('true') messages.success(request, 'Preferences saved') elif request.is_ajax(): return HttpResponse('false') else: form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, instance=preferences ) return render_to_response('admin_tools/dashboard/preferences_form.html', RequestContext(request, {'form': form})) ## Instruction: Use @staff_member_required decorator for the dashboard view as well ## Code After: from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from django.contrib import messages try: from django.views.decorators.csrf import csrf_exempt except ImportError: from django.contrib.csrf.middleware import csrf_exempt from .forms import DashboardPreferencesForm from .models import DashboardPreferences @staff_member_required @csrf_exempt def set_preferences(request, dashboard_id): """ This view serves and validates a preferences form. """ try: preferences = DashboardPreferences.objects.get( user=request.user, dashboard_id=dashboard_id ) except DashboardPreferences.DoesNotExist: preferences = None if request.method == "POST": form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, data=request.POST, instance=preferences ) if form.is_valid(): preferences = form.save() if request.is_ajax(): return HttpResponse('true') messages.success(request, 'Preferences saved') elif request.is_ajax(): return HttpResponse('false') else: form = DashboardPreferencesForm( user=request.user, dashboard_id=dashboard_id, instance=preferences ) return render_to_response('admin_tools/dashboard/preferences_form.html', RequestContext(request, {'form': form}))
# ... existing code ... from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response # ... modified code ... from .models import DashboardPreferences @staff_member_required @csrf_exempt def set_preferences(request, dashboard_id): """ # ... rest of the code ...
ed5f7ac5b6583c1e88e51f87bb73d6d50717b2f6
test/test_parameters.py
test/test_parameters.py
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher import pytest def test_check_urlslash(): launch = Launcher('not here', r'http://rlee287.github.io/pyautoupdate/testing/') launch2 = Launcher('why do I need to do this', r'http://rlee287.github.io/pyautoupdate/testing') assert launch.url == launch2.url def test_check_emptyfilepath(): with pytest.raises(ValueError): Launcher('','a url') def test_check_emptyURL(): with pytest.raises(ValueError): Launcher('a filepath','')
from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher import os import pytest def test_check_urlslash(): launch = Launcher('not here', r'http://rlee287.github.io/pyautoupdate/testing/') launch2 = Launcher('why do I need to do this', r'http://rlee287.github.io/pyautoupdate/testing') assert launch.url == launch2.url def test_check_emptyfilepath(): with pytest.raises(ValueError): Launcher('','a url') def test_check_emptyURL(): with pytest.raises(ValueError): Launcher('a filepath','') @pytest.fixture(scope="function") def fixture_corrupt_log(request): with open("version_history.log","w") as log: log.write("invalid!gibberish") def teardown(): if os.path.isfile("version_history.log"): os.remove("version_history.log") request.addfinalizer(teardown) return fixture_corrupt_log @pytest.fixture(scope="function") def fixture_corrupt_vers(request): with open("version.txt","w") as vers_file: vers_file.write("invalid?version") def teardown(): if os.path.isfile("version.txt"): os.remove("version.txt") request.addfinalizer(teardown) return fixture_corrupt_vers def test_check_corrupted_log(fixture_corrupt_log): launch=Launcher("123","456") def test_check_corrupted_vers(fixture_corrupt_vers): launch=Launcher("123","456")
Write test for error checks
Write test for error checks
Python
lgpl-2.1
rlee287/pyautoupdate,rlee287/pyautoupdate
python
## Code Before: from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher import pytest def test_check_urlslash(): launch = Launcher('not here', r'http://rlee287.github.io/pyautoupdate/testing/') launch2 = Launcher('why do I need to do this', r'http://rlee287.github.io/pyautoupdate/testing') assert launch.url == launch2.url def test_check_emptyfilepath(): with pytest.raises(ValueError): Launcher('','a url') def test_check_emptyURL(): with pytest.raises(ValueError): Launcher('a filepath','') ## Instruction: Write test for error checks ## Code After: from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher import os import pytest def test_check_urlslash(): launch = Launcher('not here', r'http://rlee287.github.io/pyautoupdate/testing/') launch2 = Launcher('why do I need to do this', r'http://rlee287.github.io/pyautoupdate/testing') assert launch.url == launch2.url def test_check_emptyfilepath(): with pytest.raises(ValueError): Launcher('','a url') def test_check_emptyURL(): with pytest.raises(ValueError): Launcher('a filepath','') @pytest.fixture(scope="function") def fixture_corrupt_log(request): with open("version_history.log","w") as log: log.write("invalid!gibberish") def teardown(): if os.path.isfile("version_history.log"): os.remove("version_history.log") request.addfinalizer(teardown) return fixture_corrupt_log @pytest.fixture(scope="function") def fixture_corrupt_vers(request): with open("version.txt","w") as vers_file: vers_file.write("invalid?version") def teardown(): if os.path.isfile("version.txt"): os.remove("version.txt") request.addfinalizer(teardown) return fixture_corrupt_vers def test_check_corrupted_log(fixture_corrupt_log): launch=Launcher("123","456") def test_check_corrupted_vers(fixture_corrupt_vers): launch=Launcher("123","456")
# ... existing code ... from __future__ import absolute_import, print_function from ..pyautoupdate.launcher import Launcher import os import pytest # ... modified code ... def test_check_emptyURL(): with pytest.raises(ValueError): Launcher('a filepath','') @pytest.fixture(scope="function") def fixture_corrupt_log(request): with open("version_history.log","w") as log: log.write("invalid!gibberish") def teardown(): if os.path.isfile("version_history.log"): os.remove("version_history.log") request.addfinalizer(teardown) return fixture_corrupt_log @pytest.fixture(scope="function") def fixture_corrupt_vers(request): with open("version.txt","w") as vers_file: vers_file.write("invalid?version") def teardown(): if os.path.isfile("version.txt"): os.remove("version.txt") request.addfinalizer(teardown) return fixture_corrupt_vers def test_check_corrupted_log(fixture_corrupt_log): launch=Launcher("123","456") def test_check_corrupted_vers(fixture_corrupt_vers): launch=Launcher("123","456") # ... rest of the code ...
a97317ae6fe022f32b195072d50924faa0d9e7bf
src/main/java/com/blamejared/mcbot/commands/CommandLMGTFY.java
src/main/java/com/blamejared/mcbot/commands/CommandLMGTFY.java
package com.blamejared.mcbot.commands; import com.blamejared.mcbot.commands.api.Command; import com.blamejared.mcbot.commands.api.CommandBase; import com.blamejared.mcbot.commands.api.CommandContext; import com.blamejared.mcbot.commands.api.CommandException; import com.blamejared.mcbot.commands.api.Flag; import com.google.common.base.Joiner; import com.google.common.collect.Lists; @Command public class CommandLMGTFY extends CommandBase { private static final Flag FLAG_IE = new SimpleFlag("ie", false); public CommandLMGTFY() { super("lmgtfy", false, Lists.newArrayList(FLAG_IE)); } @Override public void process(CommandContext ctx) throws CommandException { if (ctx.getArgs().size() < 1) { throw new CommandException("Not enough arguments."); } int iie = ctx.getFlags().containsKey(FLAG_IE) ? 1 : 0; StringBuilder arg = new StringBuilder("http://lmgtfy.com/?iie=").append(iie).append("&q="); arg.append(Joiner.on('+').join(ctx.getArgs())); ctx.reply(arg.toString()); } public String getUsage() { return "<question>"; } }
package com.blamejared.mcbot.commands; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import com.blamejared.mcbot.commands.api.Command; import com.blamejared.mcbot.commands.api.CommandBase; import com.blamejared.mcbot.commands.api.CommandContext; import com.blamejared.mcbot.commands.api.CommandException; import com.blamejared.mcbot.commands.api.Flag; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.collect.Lists; @Command public class CommandLMGTFY extends CommandBase { private static final Flag FLAG_IE = new SimpleFlag("ie", false); public CommandLMGTFY() { super("lmgtfy", false, Lists.newArrayList(FLAG_IE)); } @Override public void process(CommandContext ctx) throws CommandException { if (ctx.getArgs().size() < 1) { throw new CommandException("Not enough arguments."); } int iie = ctx.getFlags().containsKey(FLAG_IE) ? 1 : 0; StringBuilder url = new StringBuilder("<http://lmgtfy.com/?iie=").append(iie).append("&q="); String arg = Joiner.on(' ').join(ctx.getArgs()); try { ctx.reply(url.append(URLEncoder.encode(ctx.sanitize(arg), Charsets.UTF_8.name())).append(">").toString()); } catch (UnsupportedEncodingException e) { throw new CommandException(e); } } public String getUsage() { return "<question>"; } }
Fix URL encoding of lmgtfy output
Fix URL encoding of lmgtfy output
Java
mit
jaredlll08/MCBot
java
## Code Before: package com.blamejared.mcbot.commands; import com.blamejared.mcbot.commands.api.Command; import com.blamejared.mcbot.commands.api.CommandBase; import com.blamejared.mcbot.commands.api.CommandContext; import com.blamejared.mcbot.commands.api.CommandException; import com.blamejared.mcbot.commands.api.Flag; import com.google.common.base.Joiner; import com.google.common.collect.Lists; @Command public class CommandLMGTFY extends CommandBase { private static final Flag FLAG_IE = new SimpleFlag("ie", false); public CommandLMGTFY() { super("lmgtfy", false, Lists.newArrayList(FLAG_IE)); } @Override public void process(CommandContext ctx) throws CommandException { if (ctx.getArgs().size() < 1) { throw new CommandException("Not enough arguments."); } int iie = ctx.getFlags().containsKey(FLAG_IE) ? 1 : 0; StringBuilder arg = new StringBuilder("http://lmgtfy.com/?iie=").append(iie).append("&q="); arg.append(Joiner.on('+').join(ctx.getArgs())); ctx.reply(arg.toString()); } public String getUsage() { return "<question>"; } } ## Instruction: Fix URL encoding of lmgtfy output ## Code After: package com.blamejared.mcbot.commands; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import com.blamejared.mcbot.commands.api.Command; import com.blamejared.mcbot.commands.api.CommandBase; import com.blamejared.mcbot.commands.api.CommandContext; import com.blamejared.mcbot.commands.api.CommandException; import com.blamejared.mcbot.commands.api.Flag; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.collect.Lists; @Command public class CommandLMGTFY extends CommandBase { private static final Flag FLAG_IE = new SimpleFlag("ie", false); public CommandLMGTFY() { super("lmgtfy", false, Lists.newArrayList(FLAG_IE)); } @Override public void process(CommandContext ctx) throws CommandException { if (ctx.getArgs().size() < 1) { throw new CommandException("Not enough arguments."); } int iie = ctx.getFlags().containsKey(FLAG_IE) ? 1 : 0; StringBuilder url = new StringBuilder("<http://lmgtfy.com/?iie=").append(iie).append("&q="); String arg = Joiner.on(' ').join(ctx.getArgs()); try { ctx.reply(url.append(URLEncoder.encode(ctx.sanitize(arg), Charsets.UTF_8.name())).append(">").toString()); } catch (UnsupportedEncodingException e) { throw new CommandException(e); } } public String getUsage() { return "<question>"; } }
// ... existing code ... package com.blamejared.mcbot.commands; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import com.blamejared.mcbot.commands.api.Command; import com.blamejared.mcbot.commands.api.CommandBase; // ... modified code ... import com.blamejared.mcbot.commands.api.CommandContext; import com.blamejared.mcbot.commands.api.CommandException; import com.blamejared.mcbot.commands.api.Flag; import com.google.common.base.Charsets; import com.google.common.base.Joiner; import com.google.common.collect.Lists; ... throw new CommandException("Not enough arguments."); } int iie = ctx.getFlags().containsKey(FLAG_IE) ? 1 : 0; StringBuilder url = new StringBuilder("<http://lmgtfy.com/?iie=").append(iie).append("&q="); String arg = Joiner.on(' ').join(ctx.getArgs()); try { ctx.reply(url.append(URLEncoder.encode(ctx.sanitize(arg), Charsets.UTF_8.name())).append(">").toString()); } catch (UnsupportedEncodingException e) { throw new CommandException(e); } } public String getUsage() { // ... rest of the code ...
0163f06fff5ae2a9a29db3572ce42c8b79ed345b
src/test/kotlin/io/kotlintest/TestCaseTest.kt
src/test/kotlin/io/kotlintest/TestCaseTest.kt
package io.kotlintest import io.kotlintest.matchers.shouldBe import io.kotlintest.specs.StringSpec class TestCaseTest : StringSpec() { object TagA : Tag() object TagB : Tag() init { val testTaggedA: TestCase = "should be tagged with tagA" { } testTaggedA.config(tags = setOf(TagA)) val untaggedTest = "should be untagged" { } val testTaggedB = "should be tagged with tagB" { } testTaggedB.config(tags = setOf(TagB)) "only tests without excluded tags should be active" { System.setProperty("excludeTags", "TagB") testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe true testTaggedB.isActive shouldBe false } "only tests with included tags should be active" { System.setProperty("includeTags", "TagA") testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe false testTaggedB.isActive shouldBe false } } override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) { test() System.clearProperty("excludeTags") System.clearProperty("includeTags") } }
package io.kotlintest import io.kotlintest.matchers.shouldBe import io.kotlintest.specs.StringSpec class TestCaseTest : StringSpec() { object TagA : Tag() object TagB : Tag() init { val testTaggedA: TestCase = "should be tagged with tagA" { } testTaggedA.config(tags = setOf(TagA)) val untaggedTest = "should be untagged" { } val testTaggedB = "should be tagged with tagB" { } testTaggedB.config(tags = setOf(TagB)) "only tests without excluded tags should be active" { System.setProperty("excludeTags", "TagB") testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe true testTaggedB.isActive shouldBe false } "only tests with included tags should be active" { System.setProperty("includeTags", "TagA") testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe false testTaggedB.isActive shouldBe false } "tagged tests should be active by default" { testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe true testTaggedB.isActive shouldBe true } } override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) { test() System.clearProperty("excludeTags") System.clearProperty("includeTags") } }
Add a test to verify tagged tests are active by default
Add a test to verify tagged tests are active by default If no include / exclude tags are specified, tagged tests should be active.
Kotlin
mit
kotlintest/kotlintest,sksamuel/ktest,kotlintest/kotlintest,kotlintest/kotlintest
kotlin
## Code Before: package io.kotlintest import io.kotlintest.matchers.shouldBe import io.kotlintest.specs.StringSpec class TestCaseTest : StringSpec() { object TagA : Tag() object TagB : Tag() init { val testTaggedA: TestCase = "should be tagged with tagA" { } testTaggedA.config(tags = setOf(TagA)) val untaggedTest = "should be untagged" { } val testTaggedB = "should be tagged with tagB" { } testTaggedB.config(tags = setOf(TagB)) "only tests without excluded tags should be active" { System.setProperty("excludeTags", "TagB") testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe true testTaggedB.isActive shouldBe false } "only tests with included tags should be active" { System.setProperty("includeTags", "TagA") testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe false testTaggedB.isActive shouldBe false } } override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) { test() System.clearProperty("excludeTags") System.clearProperty("includeTags") } } ## Instruction: Add a test to verify tagged tests are active by default If no include / exclude tags are specified, tagged tests should be active. ## Code After: package io.kotlintest import io.kotlintest.matchers.shouldBe import io.kotlintest.specs.StringSpec class TestCaseTest : StringSpec() { object TagA : Tag() object TagB : Tag() init { val testTaggedA: TestCase = "should be tagged with tagA" { } testTaggedA.config(tags = setOf(TagA)) val untaggedTest = "should be untagged" { } val testTaggedB = "should be tagged with tagB" { } testTaggedB.config(tags = setOf(TagB)) "only tests without excluded tags should be active" { System.setProperty("excludeTags", "TagB") testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe true testTaggedB.isActive shouldBe false } "only tests with included tags should be active" { System.setProperty("includeTags", "TagA") testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe false testTaggedB.isActive shouldBe false } "tagged tests should be active by default" { testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe true testTaggedB.isActive shouldBe true } } override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) { test() System.clearProperty("excludeTags") System.clearProperty("includeTags") } }
// ... existing code ... untaggedTest.isActive shouldBe false testTaggedB.isActive shouldBe false } "tagged tests should be active by default" { testTaggedA.isActive shouldBe true untaggedTest.isActive shouldBe true testTaggedB.isActive shouldBe true } } override fun interceptTestCase(context: TestCaseContext, test: () -> Unit) { // ... rest of the code ...
dafa014fa5c4788affd2712b68ef5bee56b5e600
engine/game.py
engine/game.py
from .gobject import GObject from . import signals class Game(GObject): def __init__(self): self.maps = {} self.player = None def run(self): pass def handle_signals(self): signals.handle_signals(self) @staticmethod def reg_signal(*args): signals.reg_signal(*args) @staticmethod def have_signals(): return signals.have_signals()
from .gobject import GObject from . import signals import time class Game(GObject): def __init__(self): self.maps = {} self.player = None def run(self): while True: self.handle_signals() time.sleep(0.3) def handle_signals(self): signals.handle_signals(self) @staticmethod def reg_signal(*args): signals.reg_signal(*args) @staticmethod def have_signals(): return signals.have_signals()
Handle signals with default interface
Handle signals with default interface
Python
bsd-3-clause
entwanne/NAGM
python
## Code Before: from .gobject import GObject from . import signals class Game(GObject): def __init__(self): self.maps = {} self.player = None def run(self): pass def handle_signals(self): signals.handle_signals(self) @staticmethod def reg_signal(*args): signals.reg_signal(*args) @staticmethod def have_signals(): return signals.have_signals() ## Instruction: Handle signals with default interface ## Code After: from .gobject import GObject from . import signals import time class Game(GObject): def __init__(self): self.maps = {} self.player = None def run(self): while True: self.handle_signals() time.sleep(0.3) def handle_signals(self): signals.handle_signals(self) @staticmethod def reg_signal(*args): signals.reg_signal(*args) @staticmethod def have_signals(): return signals.have_signals()
... from .gobject import GObject from . import signals import time class Game(GObject): def __init__(self): ... self.player = None def run(self): while True: self.handle_signals() time.sleep(0.3) def handle_signals(self): signals.handle_signals(self) ...
5c75ca067adae188f361c10a94aedc89735eea05
App/app/src/androidTest/java/eic/beike/projectx/network/projectXServer/DatabaseTest.java
App/app/src/androidTest/java/eic/beike/projectx/network/projectXServer/DatabaseTest.java
package eic.beike.projectx.network.projectXServer; import junit.framework.TestCase; /** * Test the database interaction. As of now this is against the live server. * Created by alex on 10/1/15. */ public class DatabaseTest extends TestCase { private Database db; /** * We use a fresh object for every test. * @throws Exception */ public void setUp() throws Exception { super.setUp(); db = new Database(); } public void testRegister() throws Exception { String id = "test" + Long.toString(System.currentTimeMillis()); //Should be able to register. boolean success = db.register(id, "alex"); assertTrue(success); //Should not be able to register twice. success = db.register(id, "alex"); assertFalse(success); } public void testRecordScore() throws Exception { } public void testGetTopTen() throws Exception { } public void testGetPlayerTopTen() throws Exception { } }
package eic.beike.projectx.network.projectXServer; import junit.framework.TestCase; /** * Test the database interaction. As of now this is against the live server. * Created by alex on 10/1/15. */ public class DatabaseTest extends TestCase { private Database db; /** * We use a fresh object for every test. * @throws Exception */ public void setUp() throws Exception { super.setUp(); db = new Database(); } public void testRegister() throws Exception { String id = "test" + Long.toString(System.currentTimeMillis()); //Should be able to register. boolean success = db.register(id, "alex"); assertTrue(success); //Should not be able to register twice. success = db.register(id, "alex"); assertFalse(success); } public void testRecordScore() throws Exception { //Create two users. String id1 = "test" + Long.toString(System.currentTimeMillis()); String id2 = "test" + Long.toString(System.currentTimeMillis() + 10); //Register one of them. if(db.register(id1, "alex")) { //Record a valid score. long t = System.currentTimeMillis(); boolean success = db.recordScore(id1,10,t,"Ericsson$100020"); assertTrue(success); //Try again. This should not be allowed. success = db.recordScore(id1,10,t,"Ericsson$100020"); assertFalse(success); //Try with unknown player, should not be allowed. success = db.recordScore(id2,10,System.currentTimeMillis(),"Ericsson$100020"); assertFalse(success); } } public void testGetTopTen() throws Exception { } public void testGetPlayerTopTen() throws Exception { } }
Add tests for recording a score.
Add tests for recording a score.
Java
apache-2.0
BeikeElectricity/ProjectX,BeikeElectricity/ProjectX,BeikeElectricity/ProjectX
java
## Code Before: package eic.beike.projectx.network.projectXServer; import junit.framework.TestCase; /** * Test the database interaction. As of now this is against the live server. * Created by alex on 10/1/15. */ public class DatabaseTest extends TestCase { private Database db; /** * We use a fresh object for every test. * @throws Exception */ public void setUp() throws Exception { super.setUp(); db = new Database(); } public void testRegister() throws Exception { String id = "test" + Long.toString(System.currentTimeMillis()); //Should be able to register. boolean success = db.register(id, "alex"); assertTrue(success); //Should not be able to register twice. success = db.register(id, "alex"); assertFalse(success); } public void testRecordScore() throws Exception { } public void testGetTopTen() throws Exception { } public void testGetPlayerTopTen() throws Exception { } } ## Instruction: Add tests for recording a score. ## Code After: package eic.beike.projectx.network.projectXServer; import junit.framework.TestCase; /** * Test the database interaction. As of now this is against the live server. * Created by alex on 10/1/15. */ public class DatabaseTest extends TestCase { private Database db; /** * We use a fresh object for every test. * @throws Exception */ public void setUp() throws Exception { super.setUp(); db = new Database(); } public void testRegister() throws Exception { String id = "test" + Long.toString(System.currentTimeMillis()); //Should be able to register. boolean success = db.register(id, "alex"); assertTrue(success); //Should not be able to register twice. success = db.register(id, "alex"); assertFalse(success); } public void testRecordScore() throws Exception { //Create two users. String id1 = "test" + Long.toString(System.currentTimeMillis()); String id2 = "test" + Long.toString(System.currentTimeMillis() + 10); //Register one of them. if(db.register(id1, "alex")) { //Record a valid score. long t = System.currentTimeMillis(); boolean success = db.recordScore(id1,10,t,"Ericsson$100020"); assertTrue(success); //Try again. This should not be allowed. success = db.recordScore(id1,10,t,"Ericsson$100020"); assertFalse(success); //Try with unknown player, should not be allowed. success = db.recordScore(id2,10,System.currentTimeMillis(),"Ericsson$100020"); assertFalse(success); } } public void testGetTopTen() throws Exception { } public void testGetPlayerTopTen() throws Exception { } }
// ... existing code ... } public void testRecordScore() throws Exception { //Create two users. String id1 = "test" + Long.toString(System.currentTimeMillis()); String id2 = "test" + Long.toString(System.currentTimeMillis() + 10); //Register one of them. if(db.register(id1, "alex")) { //Record a valid score. long t = System.currentTimeMillis(); boolean success = db.recordScore(id1,10,t,"Ericsson$100020"); assertTrue(success); //Try again. This should not be allowed. success = db.recordScore(id1,10,t,"Ericsson$100020"); assertFalse(success); //Try with unknown player, should not be allowed. success = db.recordScore(id2,10,System.currentTimeMillis(),"Ericsson$100020"); assertFalse(success); } } public void testGetTopTen() throws Exception { // ... rest of the code ...
f1e516e8002425f5f4f9904096848798b2bc97fa
jesusmtnez/python/kata/game.py
jesusmtnez/python/kata/game.py
class Game(): def __init__(self): self._rolls = [0] * 21 self._current_roll = 0 def roll(self, pins): self._rolls[self._current_roll] += pins self._current_roll += 1 def score(self): score = 0 for frame in range(0, 20, 2): if self._is_spare(frame): score += 10 + self._rolls[frame + 2] else: score += self._frame_score(frame) return score def _is_spare(self, frame): return self._rolls[frame] + self._rolls[frame + 1] == 10 def _frame_score(self, frame): return self._rolls[frame] + self._rolls[frame + 1]
class Game(): def __init__(self): self._rolls = [0] * 21 self._current_roll = 0 def roll(self, pins): self._rolls[self._current_roll] += pins self._current_roll += 1 if pins < 10 else 2 def score(self): score = 0 for frame in range(0, 20, 2): if self._is_strike(frame): score += 10 + self._rolls[frame + 2] + self._rolls[frame + 3] elif self._is_spare(frame): score += 10 + self._rolls[frame + 2] else: score += self._frame_score(frame) return score def _is_spare(self, frame): return self._rolls[frame] + self._rolls[frame + 1] == 10 def _is_strike(self, frame): print(frame) return self._rolls[frame] == 10 def _frame_score(self, frame): return self._rolls[frame] + self._rolls[frame + 1]
Add strikes support when rolling
[Python] Add strikes support when rolling
Python
mit
JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge
python
## Code Before: class Game(): def __init__(self): self._rolls = [0] * 21 self._current_roll = 0 def roll(self, pins): self._rolls[self._current_roll] += pins self._current_roll += 1 def score(self): score = 0 for frame in range(0, 20, 2): if self._is_spare(frame): score += 10 + self._rolls[frame + 2] else: score += self._frame_score(frame) return score def _is_spare(self, frame): return self._rolls[frame] + self._rolls[frame + 1] == 10 def _frame_score(self, frame): return self._rolls[frame] + self._rolls[frame + 1] ## Instruction: [Python] Add strikes support when rolling ## Code After: class Game(): def __init__(self): self._rolls = [0] * 21 self._current_roll = 0 def roll(self, pins): self._rolls[self._current_roll] += pins self._current_roll += 1 if pins < 10 else 2 def score(self): score = 0 for frame in range(0, 20, 2): if self._is_strike(frame): score += 10 + self._rolls[frame + 2] + self._rolls[frame + 3] elif self._is_spare(frame): score += 10 + self._rolls[frame + 2] else: score += self._frame_score(frame) return score def _is_spare(self, frame): return self._rolls[frame] + self._rolls[frame + 1] == 10 def _is_strike(self, frame): print(frame) return self._rolls[frame] == 10 def _frame_score(self, frame): return self._rolls[frame] + self._rolls[frame + 1]
# ... existing code ... def roll(self, pins): self._rolls[self._current_roll] += pins self._current_roll += 1 if pins < 10 else 2 def score(self): score = 0 for frame in range(0, 20, 2): if self._is_strike(frame): score += 10 + self._rolls[frame + 2] + self._rolls[frame + 3] elif self._is_spare(frame): score += 10 + self._rolls[frame + 2] else: score += self._frame_score(frame) # ... modified code ... def _is_spare(self, frame): return self._rolls[frame] + self._rolls[frame + 1] == 10 def _is_strike(self, frame): print(frame) return self._rolls[frame] == 10 def _frame_score(self, frame): return self._rolls[frame] + self._rolls[frame + 1] # ... rest of the code ...
f604de4794c87c155cdda758a43aa7261662dcff
examples/pystray_icon.py
examples/pystray_icon.py
from PIL import Image from pystray import Icon, Menu, MenuItem import webview import sys if sys.platform == 'darwin': raise NotImplementedError('This example does not work on macOS.') from threading import Thread from queue import Queue """ This example demonstrates running pywebview alongside with pystray to display a system tray icon. """ def run_webview(): window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello') webview.start() def run_pystray(queue: Queue): def on_open(icon, item): queue.put('open') def on_exit(icon, item): icon.stop() queue.put('exit') image = Image.open('logo/logo.png') menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit)) icon = Icon('Pystray', image, "Pystray", menu) icon.run() if __name__ == '__main__': queue = Queue() icon_thread = Thread(target=run_pystray, args=(queue,)) icon_thread.start() run_webview() while True: event = queue.get() if event == 'open': run_webview() if event == 'exit': break icon_thread.join()
from PIL import Image from pystray import Icon, Menu, MenuItem import webview import sys import multiprocessing if sys.platform == 'darwin': ctx = multiprocessing.get_context('spawn') Process = ctx.Process Queue = ctx.Queue else: Process = multiprocessing.Process Queue = multiprocessing.Queue """ This example demonstrates running pywebview alongside with pystray to display a system tray icon. """ webview_process = None def run_webview(): window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello') webview.start() if __name__ == '__main__': def start_webview_process(): global webview_process webview_process = Process(target=run_webview) webview_process.start() def on_open(icon, item): global webview_process if not webview_process.is_alive(): start_webview_process() def on_exit(icon, item): icon.stop() start_webview_process() image = Image.open('logo/logo.png') menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit)) icon = Icon('Pystray', image, menu=menu) icon.run() webview_process.terminate()
Improve example, start pystray in main thread and webview in new process
Improve example, start pystray in main thread and webview in new process
Python
bsd-3-clause
r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview,r0x0r/pywebview
python
## Code Before: from PIL import Image from pystray import Icon, Menu, MenuItem import webview import sys if sys.platform == 'darwin': raise NotImplementedError('This example does not work on macOS.') from threading import Thread from queue import Queue """ This example demonstrates running pywebview alongside with pystray to display a system tray icon. """ def run_webview(): window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello') webview.start() def run_pystray(queue: Queue): def on_open(icon, item): queue.put('open') def on_exit(icon, item): icon.stop() queue.put('exit') image = Image.open('logo/logo.png') menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit)) icon = Icon('Pystray', image, "Pystray", menu) icon.run() if __name__ == '__main__': queue = Queue() icon_thread = Thread(target=run_pystray, args=(queue,)) icon_thread.start() run_webview() while True: event = queue.get() if event == 'open': run_webview() if event == 'exit': break icon_thread.join() ## Instruction: Improve example, start pystray in main thread and webview in new process ## Code After: from PIL import Image from pystray import Icon, Menu, MenuItem import webview import sys import multiprocessing if sys.platform == 'darwin': ctx = multiprocessing.get_context('spawn') Process = ctx.Process Queue = ctx.Queue else: Process = multiprocessing.Process Queue = multiprocessing.Queue """ This example demonstrates running pywebview alongside with pystray to display a system tray icon. """ webview_process = None def run_webview(): window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello') webview.start() if __name__ == '__main__': def start_webview_process(): global webview_process webview_process = Process(target=run_webview) webview_process.start() def on_open(icon, item): global webview_process if not webview_process.is_alive(): start_webview_process() def on_exit(icon, item): icon.stop() start_webview_process() image = Image.open('logo/logo.png') menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit)) icon = Icon('Pystray', image, menu=menu) icon.run() webview_process.terminate()
# ... existing code ... from pystray import Icon, Menu, MenuItem import webview import sys import multiprocessing if sys.platform == 'darwin': ctx = multiprocessing.get_context('spawn') Process = ctx.Process Queue = ctx.Queue else: Process = multiprocessing.Process Queue = multiprocessing.Queue """ # ... modified code ... """ webview_process = None def run_webview(): window = webview.create_window('Webview', 'https://pywebview.flowrl.com/hello') webview.start() if __name__ == '__main__': def start_webview_process(): global webview_process webview_process = Process(target=run_webview) webview_process.start() def on_open(icon, item): global webview_process if not webview_process.is_alive(): start_webview_process() def on_exit(icon, item): icon.stop() start_webview_process() image = Image.open('logo/logo.png') menu = Menu(MenuItem('Open', on_open), MenuItem('Exit', on_exit)) icon = Icon('Pystray', image, menu=menu) icon.run() webview_process.terminate() # ... rest of the code ...
d0ca3952a34a74f0167b76bbedfa3cf8875a399c
var/spack/repos/builtin/packages/py-scikit-learn/package.py
var/spack/repos/builtin/packages/py-scikit-learn/package.py
from spack import * class PyScikitLearn(Package): """""" homepage = "https://pypi.python.org/pypi/scikit-learn" url = "https://pypi.python.org/packages/source/s/scikit-learn/scikit-learn-0.15.2.tar.gz" version('0.15.2', 'd9822ad0238e17b382a3c756ea94fe0d') version('0.16.1', '363ddda501e3b6b61726aa40b8dbdb7e') extends('python') def install(self, spec, prefix): python('setup.py', 'install', '--prefix=%s' % prefix)
from spack import * class PyScikitLearn(Package): """""" homepage = "https://pypi.python.org/pypi/scikit-learn" url = "https://pypi.python.org/packages/source/s/scikit-learn/scikit-learn-0.15.2.tar.gz" version('0.15.2', 'd9822ad0238e17b382a3c756ea94fe0d') version('0.16.1', '363ddda501e3b6b61726aa40b8dbdb7e') version('0.17.1', 'a2f8b877e6d99b1ed737144f5a478dfc') extends('python') def install(self, spec, prefix): python('setup.py', 'install', '--prefix=%s' % prefix)
Add version 0.17.1 of scikit-learn.
Add version 0.17.1 of scikit-learn.
Python
lgpl-2.1
matthiasdiener/spack,mfherbst/spack,EmreAtes/spack,TheTimmy/spack,iulian787/spack,iulian787/spack,iulian787/spack,mfherbst/spack,tmerrick1/spack,mfherbst/spack,LLNL/spack,LLNL/spack,tmerrick1/spack,skosukhin/spack,TheTimmy/spack,skosukhin/spack,TheTimmy/spack,skosukhin/spack,matthiasdiener/spack,mfherbst/spack,mfherbst/spack,lgarren/spack,LLNL/spack,matthiasdiener/spack,tmerrick1/spack,krafczyk/spack,krafczyk/spack,TheTimmy/spack,EmreAtes/spack,LLNL/spack,krafczyk/spack,iulian787/spack,lgarren/spack,tmerrick1/spack,EmreAtes/spack,EmreAtes/spack,krafczyk/spack,lgarren/spack,matthiasdiener/spack,lgarren/spack,iulian787/spack,LLNL/spack,lgarren/spack,skosukhin/spack,krafczyk/spack,skosukhin/spack,matthiasdiener/spack,TheTimmy/spack,EmreAtes/spack,tmerrick1/spack
python
## Code Before: from spack import * class PyScikitLearn(Package): """""" homepage = "https://pypi.python.org/pypi/scikit-learn" url = "https://pypi.python.org/packages/source/s/scikit-learn/scikit-learn-0.15.2.tar.gz" version('0.15.2', 'd9822ad0238e17b382a3c756ea94fe0d') version('0.16.1', '363ddda501e3b6b61726aa40b8dbdb7e') extends('python') def install(self, spec, prefix): python('setup.py', 'install', '--prefix=%s' % prefix) ## Instruction: Add version 0.17.1 of scikit-learn. ## Code After: from spack import * class PyScikitLearn(Package): """""" homepage = "https://pypi.python.org/pypi/scikit-learn" url = "https://pypi.python.org/packages/source/s/scikit-learn/scikit-learn-0.15.2.tar.gz" version('0.15.2', 'd9822ad0238e17b382a3c756ea94fe0d') version('0.16.1', '363ddda501e3b6b61726aa40b8dbdb7e') version('0.17.1', 'a2f8b877e6d99b1ed737144f5a478dfc') extends('python') def install(self, spec, prefix): python('setup.py', 'install', '--prefix=%s' % prefix)
// ... existing code ... version('0.15.2', 'd9822ad0238e17b382a3c756ea94fe0d') version('0.16.1', '363ddda501e3b6b61726aa40b8dbdb7e') version('0.17.1', 'a2f8b877e6d99b1ed737144f5a478dfc') extends('python') // ... rest of the code ...
ea164b66cc93d5d7fb1f89a0297ea0a8da926b54
server/core/views.py
server/core/views.py
from django.shortcuts import render from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def app(request): return render(request, 'html.html')
from django.shortcuts import render def app(request): return render(request, 'html.html')
Stop inserting the CSRF token into the main app page
Stop inserting the CSRF token into the main app page
Python
mit
Techbikers/techbikers,mwillmott/techbikers,mwillmott/techbikers,Techbikers/techbikers,mwillmott/techbikers,Techbikers/techbikers,Techbikers/techbikers,mwillmott/techbikers
python
## Code Before: from django.shortcuts import render from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def app(request): return render(request, 'html.html') ## Instruction: Stop inserting the CSRF token into the main app page ## Code After: from django.shortcuts import render def app(request): return render(request, 'html.html')
// ... existing code ... from django.shortcuts import render def app(request): return render(request, 'html.html') // ... rest of the code ...
c4f5877b49b235acc17296741de544da40ef8c0b
test/com/twu/biblioteca/BibliotecaAppTest.java
test/com/twu/biblioteca/BibliotecaAppTest.java
package com.twu.biblioteca; import org.junit.Test; import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.StringBuilder; import java.util.List; import java.util.ArrayList; public class BibliotecaAppTest { @Test public void testBibliotecaStartup() { List<String> bookList = new ArrayList<String>(); bookList.add("Test-Driven Development By Example"); bookList.add("The Agile Samurai"); bookList.add("Head First Java"); bookList.add("Don't Make Me Think, Revisited: A Common Sense Approach to Web Usability"); StringBuilder startupOutput = new StringBuilder(); startupOutput.append("Welcome to Biblioteca!\n"); startupOutput.append("Book list:\n"); for (String book : bookList) { startupOutput.append(book + "\n"); } ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); BibliotecaApp.main(new String[] {}); assertEquals(startupOutput.toString(), outContent.toString()); } }
package com.twu.biblioteca; import org.junit.Test; import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.StringBuilder; import java.util.List; import java.util.ArrayList; import java.util.Formatter; public class BibliotecaAppTest { @Test public void testBibliotecaStartup() { StringBuilder expectedOutput = new StringBuilder(); expectedOutput.append("Welcome to Biblioteca!\n"); expectedOutput.append(printBookList()); ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); BibliotecaApp.main(new String[] {}); assertEquals(expectedOutput.toString(), outContent.toString()); } private String printBookList() { List<Book> bookList = generateBookList(); StringBuilder output = new StringBuilder(); output.append("Book List:"); String leftAlignFormat = "%-32s | %-32s | %-4d\n"; output.append(String.format(leftAlignFormat, "Title", "Author", "Year Published")); for (List<Book> book : bookList) { output.append(String.format(leftAlignFormat, book.getTitle(), book.getAuthor(), book.getYearPublished())); } return output.toString(); } private List<Book> generateBookList() { List<Book> bookList = new ArrayList<Book>(); bookList.add(new Book("Test-Driven Development By Example", "Kent Beck", 2003)); bookList.add(new Book("The Agile Samurai", "Jonathan Rasmusson", 2010)); bookList.add(new Book("Head First Java", "Kathy Sierra & Bert Bates", 2005)); bookList.add(new Book("Don't Make Me Think, Revisited: A Common Sense Approach to Web Usability", "Steve Krug", 2014)); return bookList; } }
Test printing book list with author and publish year
Test printing book list with author and publish year
Java
apache-2.0
raingxm/twu-biblioteca-emilysiow
java
## Code Before: package com.twu.biblioteca; import org.junit.Test; import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.StringBuilder; import java.util.List; import java.util.ArrayList; public class BibliotecaAppTest { @Test public void testBibliotecaStartup() { List<String> bookList = new ArrayList<String>(); bookList.add("Test-Driven Development By Example"); bookList.add("The Agile Samurai"); bookList.add("Head First Java"); bookList.add("Don't Make Me Think, Revisited: A Common Sense Approach to Web Usability"); StringBuilder startupOutput = new StringBuilder(); startupOutput.append("Welcome to Biblioteca!\n"); startupOutput.append("Book list:\n"); for (String book : bookList) { startupOutput.append(book + "\n"); } ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); BibliotecaApp.main(new String[] {}); assertEquals(startupOutput.toString(), outContent.toString()); } } ## Instruction: Test printing book list with author and publish year ## Code After: package com.twu.biblioteca; import org.junit.Test; import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.StringBuilder; import java.util.List; import java.util.ArrayList; import java.util.Formatter; public class BibliotecaAppTest { @Test public void testBibliotecaStartup() { StringBuilder expectedOutput = new StringBuilder(); expectedOutput.append("Welcome to Biblioteca!\n"); expectedOutput.append(printBookList()); ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); BibliotecaApp.main(new String[] {}); assertEquals(expectedOutput.toString(), outContent.toString()); } private String printBookList() { List<Book> bookList = generateBookList(); StringBuilder output = new StringBuilder(); output.append("Book List:"); String leftAlignFormat = "%-32s | %-32s | %-4d\n"; output.append(String.format(leftAlignFormat, "Title", "Author", "Year Published")); for (List<Book> book : bookList) { output.append(String.format(leftAlignFormat, book.getTitle(), book.getAuthor(), book.getYearPublished())); } return output.toString(); } private List<Book> generateBookList() { List<Book> bookList = new ArrayList<Book>(); bookList.add(new Book("Test-Driven Development By Example", "Kent Beck", 2003)); bookList.add(new Book("The Agile Samurai", "Jonathan Rasmusson", 2010)); bookList.add(new Book("Head First Java", "Kathy Sierra & Bert Bates", 2005)); bookList.add(new Book("Don't Make Me Think, Revisited: A Common Sense Approach to Web Usability", "Steve Krug", 2014)); return bookList; } }
# ... existing code ... import java.lang.StringBuilder; import java.util.List; import java.util.ArrayList; import java.util.Formatter; public class BibliotecaAppTest { @Test public void testBibliotecaStartup() { StringBuilder expectedOutput = new StringBuilder(); expectedOutput.append("Welcome to Biblioteca!\n"); expectedOutput.append(printBookList()); ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); BibliotecaApp.main(new String[] {}); assertEquals(expectedOutput.toString(), outContent.toString()); } private String printBookList() { List<Book> bookList = generateBookList(); StringBuilder output = new StringBuilder(); output.append("Book List:"); String leftAlignFormat = "%-32s | %-32s | %-4d\n"; output.append(String.format(leftAlignFormat, "Title", "Author", "Year Published")); for (List<Book> book : bookList) { output.append(String.format(leftAlignFormat, book.getTitle(), book.getAuthor(), book.getYearPublished())); } return output.toString(); } private List<Book> generateBookList() { List<Book> bookList = new ArrayList<Book>(); bookList.add(new Book("Test-Driven Development By Example", "Kent Beck", 2003)); bookList.add(new Book("The Agile Samurai", "Jonathan Rasmusson", 2010)); bookList.add(new Book("Head First Java", "Kathy Sierra & Bert Bates", 2005)); bookList.add(new Book("Don't Make Me Think, Revisited: A Common Sense Approach to Web Usability", "Steve Krug", 2014)); return bookList; } } # ... rest of the code ...
17ed0b2c2ba12788f2fe3db3bf10ee381a4fe637
src/test/java/com/skraylabs/poker/model/InvalidCardFormatExceptionTest.java
src/test/java/com/skraylabs/poker/model/InvalidCardFormatExceptionTest.java
package com.skraylabs.poker.model; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.After; import org.junit.Before; import org.junit.Test; public class InvalidCardFormatExceptionTest { @Before public void setUp() throws Exception {} @After public void tearDown() throws Exception {} @Test public void testDefaultConstructor() { // Exercise InvalidCardFormatException exception = new InvalidCardFormatException(); // Verify String message = exception.getMessage(); String invalidString = exception.getInvalidString(); assertThat(message, equalTo(InvalidCardFormatException.MSG_DEFAULT)); assertThat(invalidString, is(nullValue())); } @Test public void testInitializingConstructor() { // Exercise InvalidCardFormatException exception = new InvalidCardFormatException("5x"); // Verify String message = exception.getMessage(); String invalidString = exception.getInvalidString(); String expectedMessage = String.format(InvalidCardFormatException.MSG_WITH_INVALID_STRING, "5x"); assertThat(message, equalTo(expectedMessage)); assertThat(invalidString, equalTo("5x")); } }
package com.skraylabs.poker.model; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.After; import org.junit.Before; import org.junit.Test; public class InvalidCardFormatExceptionTest { @Before public void setUp() throws Exception {} @After public void tearDown() throws Exception {} @Test public void testDefaultConstructor() { // Exercise InvalidCardFormatException exception = new InvalidCardFormatException(); // Verify String message = exception.getMessage(); String invalidString = exception.getInvalidString(); assertThat(message, equalTo(InvalidCardFormatException.MSG_DEFAULT)); assertThat(invalidString, is(nullValue())); } @Test public void testInitializingConstructor() { // Exercise InvalidCardFormatException exception = new InvalidCardFormatException("5x"); // Verify String message = exception.getMessage(); String invalidString = exception.getInvalidString(); String expectedMessage = String.format(InvalidCardFormatException.MSG_WITH_INVALID_STRING, "5x"); assertThat(message, equalTo(expectedMessage)); assertThat(invalidString, equalTo("5x")); } @Test public void testInitializingConstructor_emptyInvalidString() { // Exercise InvalidCardFormatException exception = new InvalidCardFormatException(""); // Verify String message = exception.getMessage(); String invalidString = exception.getInvalidString(); assertThat(message, equalTo(InvalidCardFormatException.MSG_DEFAULT)); assertThat(invalidString, is(nullValue())); } }
Add test for initializing ctor with empty String.
Add test for initializing ctor with empty String. Should treat this like the default constructor * invalidString is null * message is the default
Java
mit
AbeSkray/poker-calculator
java
## Code Before: package com.skraylabs.poker.model; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.After; import org.junit.Before; import org.junit.Test; public class InvalidCardFormatExceptionTest { @Before public void setUp() throws Exception {} @After public void tearDown() throws Exception {} @Test public void testDefaultConstructor() { // Exercise InvalidCardFormatException exception = new InvalidCardFormatException(); // Verify String message = exception.getMessage(); String invalidString = exception.getInvalidString(); assertThat(message, equalTo(InvalidCardFormatException.MSG_DEFAULT)); assertThat(invalidString, is(nullValue())); } @Test public void testInitializingConstructor() { // Exercise InvalidCardFormatException exception = new InvalidCardFormatException("5x"); // Verify String message = exception.getMessage(); String invalidString = exception.getInvalidString(); String expectedMessage = String.format(InvalidCardFormatException.MSG_WITH_INVALID_STRING, "5x"); assertThat(message, equalTo(expectedMessage)); assertThat(invalidString, equalTo("5x")); } } ## Instruction: Add test for initializing ctor with empty String. Should treat this like the default constructor * invalidString is null * message is the default ## Code After: package com.skraylabs.poker.model; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.After; import org.junit.Before; import org.junit.Test; public class InvalidCardFormatExceptionTest { @Before public void setUp() throws Exception {} @After public void tearDown() throws Exception {} @Test public void testDefaultConstructor() { // Exercise InvalidCardFormatException exception = new InvalidCardFormatException(); // Verify String message = exception.getMessage(); String invalidString = exception.getInvalidString(); assertThat(message, equalTo(InvalidCardFormatException.MSG_DEFAULT)); assertThat(invalidString, is(nullValue())); } @Test public void testInitializingConstructor() { // Exercise InvalidCardFormatException exception = new InvalidCardFormatException("5x"); // Verify String message = exception.getMessage(); String invalidString = exception.getInvalidString(); String expectedMessage = String.format(InvalidCardFormatException.MSG_WITH_INVALID_STRING, "5x"); assertThat(message, equalTo(expectedMessage)); assertThat(invalidString, equalTo("5x")); } @Test public void testInitializingConstructor_emptyInvalidString() { // Exercise InvalidCardFormatException exception = new InvalidCardFormatException(""); // Verify String message = exception.getMessage(); String invalidString = exception.getInvalidString(); assertThat(message, equalTo(InvalidCardFormatException.MSG_DEFAULT)); assertThat(invalidString, is(nullValue())); } }
... assertThat(message, equalTo(expectedMessage)); assertThat(invalidString, equalTo("5x")); } @Test public void testInitializingConstructor_emptyInvalidString() { // Exercise InvalidCardFormatException exception = new InvalidCardFormatException(""); // Verify String message = exception.getMessage(); String invalidString = exception.getInvalidString(); assertThat(message, equalTo(InvalidCardFormatException.MSG_DEFAULT)); assertThat(invalidString, is(nullValue())); } } ...
a28adab74e7d55aa414829a03cedd20bd966eacf
interpreter/cling/include/cling/UserInterface/CompilationException.h
interpreter/cling/include/cling/UserInterface/CompilationException.h
//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> //------------------------------------------------------------------------------ #ifndef CLING_COMPILATIONEXCEPTION_H #define CLING_COMPILATIONEXCEPTION_H #include <stdexcept> #include <string> #include "cling/Interpreter/RuntimeException.h" namespace cling { class Interpreter; class MetaProcessor; //\brief Exception pull us out of JIT (llvm + clang) errors. class CompilationException: public virtual runtime::InterpreterException, public virtual std::runtime_error { public: CompilationException(const std::string& reason): std::runtime_error(reason) {} ~CompilationException() throw(); // vtable pinned to UserInterface.cpp virtual const char* what() const throw() { return std::runtime_error::what(); } }; } #endif // CLING_COMPILATIONEXCEPTION_H
//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> //------------------------------------------------------------------------------ #ifndef CLING_COMPILATIONEXCEPTION_H #define CLING_COMPILATIONEXCEPTION_H #include <stdexcept> #include <string> #include "cling/Interpreter/RuntimeException.h" namespace cling { class Interpreter; class MetaProcessor; ///\brief Exception that pulls cling out of runtime-compilation (llvm + clang) /// errors. /// /// If user code provokes an llvm::unreachable it will cause this exception /// to be thrown. Given that this is at the process's runtime and an /// interpreter error it inherits from InterpreterException and runtime_error. /// Note that this exception is *not* thrown during the execution of the /// user's code but during its compilation (at runtime). class CompilationException: public virtual runtime::InterpreterException, public virtual std::runtime_error { public: CompilationException(const std::string& reason): std::runtime_error(reason) {} ~CompilationException() throw(); // vtable pinned to UserInterface.cpp virtual const char* what() const throw() { return std::runtime_error::what(); } }; } #endif // CLING_COMPILATIONEXCEPTION_H
Add more rationale as to how this exception is different from others.
Add more rationale as to how this exception is different from others.
C
lgpl-2.1
karies/root,mkret2/root,omazapa/root,buuck/root,krafczyk/root,CristinaCristescu/root,thomaskeck/root,sbinet/cxx-root,gganis/root,nilqed/root,arch1tect0r/root,mattkretz/root,esakellari/my_root_for_test,esakellari/my_root_for_test,zzxuanyuan/root,mattkretz/root,zzxuanyuan/root-compressor-dummy,georgtroska/root,mattkretz/root,omazapa/root-old,dfunke/root,mhuwiler/rootauto,buuck/root,bbockelm/root,veprbl/root,mattkretz/root,veprbl/root,alexschlueter/cern-root,omazapa/root-old,sawenzel/root,veprbl/root,vukasinmilosevic/root,buuck/root,krafczyk/root,0x0all/ROOT,perovic/root,BerserkerTroll/root,satyarth934/root,beniz/root,vukasinmilosevic/root,gbitzes/root,Duraznos/root,pspe/root,satyarth934/root,zzxuanyuan/root,zzxuanyuan/root,esakellari/my_root_for_test,lgiommi/root,davidlt/root,sawenzel/root,beniz/root,Y--/root,BerserkerTroll/root,evgeny-boger/root,alexschlueter/cern-root,thomaskeck/root,Y--/root,perovic/root,BerserkerTroll/root,davidlt/root,bbockelm/root,0x0all/ROOT,davidlt/root,karies/root,agarciamontoro/root,krafczyk/root,0x0all/ROOT,dfunke/root,Duraznos/root,simonpf/root,buuck/root,mhuwiler/rootauto,mhuwiler/rootauto,esakellari/root,esakellari/my_root_for_test,pspe/root,Duraznos/root,mattkretz/root,smarinac/root,Duraznos/root,beniz/root,gganis/root,georgtroska/root,veprbl/root,bbockelm/root,arch1tect0r/root,gganis/root,gbitzes/root,CristinaCristescu/root,smarinac/root,esakellari/my_root_for_test,krafczyk/root,nilqed/root,beniz/root,esakellari/root,Y--/root,esakellari/my_root_for_test,pspe/root,sawenzel/root,esakellari/my_root_for_test,gganis/root,esakellari/root,krafczyk/root,sawenzel/root,sirinath/root,gganis/root,olifre/root,beniz/root,vukasinmilosevic/root,BerserkerTroll/root,dfunke/root,zzxuanyuan/root-compressor-dummy,root-mirror/root,abhinavmoudgil95/root,zzxuanyuan/root-compressor-dummy,georgtroska/root,0x0all/ROOT,simonpf/root,buuck/root,zzxuanyuan/root,davidlt/root,vukasinmilosevic/root,bbockelm/root,omazapa/root,mhuwiler/rootauto,gbitzes/root,omazapa/root,vukasinmilosevic/root,BerserkerTroll/root,arch1tect0r/root,sawenzel/root,Duraznos/root,nilqed/root,cxx-hep/root-cern,veprbl/root,olifre/root,lgiommi/root,dfunke/root,alexschlueter/cern-root,simonpf/root,karies/root,evgeny-boger/root,jrtomps/root,gbitzes/root,root-mirror/root,gbitzes/root,cxx-hep/root-cern,abhinavmoudgil95/root,zzxuanyuan/root,esakellari/root,perovic/root,esakellari/root,agarciamontoro/root,thomaskeck/root,satyarth934/root,nilqed/root,BerserkerTroll/root,gganis/root,gbitzes/root,buuck/root,sawenzel/root,mattkretz/root,zzxuanyuan/root-compressor-dummy,jrtomps/root,Duraznos/root,Y--/root,Duraznos/root,nilqed/root,mkret2/root,vukasinmilosevic/root,esakellari/root,Duraznos/root,sirinath/root,CristinaCristescu/root,simonpf/root,beniz/root,karies/root,dfunke/root,evgeny-boger/root,satyarth934/root,gbitzes/root,pspe/root,omazapa/root-old,vukasinmilosevic/root,georgtroska/root,pspe/root,smarinac/root,pspe/root,mkret2/root,pspe/root,buuck/root,satyarth934/root,BerserkerTroll/root,sawenzel/root,olifre/root,smarinac/root,davidlt/root,beniz/root,gganis/root,zzxuanyuan/root-compressor-dummy,georgtroska/root,arch1tect0r/root,sbinet/cxx-root,mhuwiler/rootauto,bbockelm/root,beniz/root,Y--/root,veprbl/root,thomaskeck/root,root-mirror/root,sirinath/root,karies/root,Y--/root,omazapa/root-old,arch1tect0r/root,cxx-hep/root-cern,evgeny-boger/root,georgtroska/root,perovic/root,bbockelm/root,dfunke/root,0x0all/ROOT,zzxuanyuan/root,root-mirror/root,smarinac/root,thomaskeck/root,jrtomps/root,Y--/root,gganis/root,beniz/root,simonpf/root,nilqed/root,zzxuanyuan/root,buuck/root,simonpf/root,root-mirror/root,abhinavmoudgil95/root,sirinath/root,krafczyk/root,BerserkerTroll/root,sbinet/cxx-root,sirinath/root,nilqed/root,thomaskeck/root,gbitzes/root,omazapa/root-old,perovic/root,alexschlueter/cern-root,arch1tect0r/root,arch1tect0r/root,agarciamontoro/root,evgeny-boger/root,mhuwiler/rootauto,omazapa/root,mhuwiler/rootauto,zzxuanyuan/root-compressor-dummy,pspe/root,arch1tect0r/root,bbockelm/root,smarinac/root,perovic/root,zzxuanyuan/root,karies/root,davidlt/root,jrtomps/root,evgeny-boger/root,root-mirror/root,krafczyk/root,omazapa/root,zzxuanyuan/root,smarinac/root,root-mirror/root,esakellari/my_root_for_test,jrtomps/root,evgeny-boger/root,sirinath/root,BerserkerTroll/root,karies/root,zzxuanyuan/root,cxx-hep/root-cern,olifre/root,gganis/root,agarciamontoro/root,mattkretz/root,lgiommi/root,mkret2/root,veprbl/root,karies/root,nilqed/root,vukasinmilosevic/root,olifre/root,esakellari/root,jrtomps/root,omazapa/root-old,simonpf/root,veprbl/root,sawenzel/root,gbitzes/root,gganis/root,smarinac/root,satyarth934/root,karies/root,thomaskeck/root,BerserkerTroll/root,sbinet/cxx-root,esakellari/my_root_for_test,olifre/root,perovic/root,lgiommi/root,0x0all/ROOT,olifre/root,sawenzel/root,abhinavmoudgil95/root,olifre/root,dfunke/root,arch1tect0r/root,sbinet/cxx-root,satyarth934/root,zzxuanyuan/root-compressor-dummy,vukasinmilosevic/root,Duraznos/root,abhinavmoudgil95/root,simonpf/root,esakellari/root,krafczyk/root,CristinaCristescu/root,jrtomps/root,Duraznos/root,sbinet/cxx-root,0x0all/ROOT,buuck/root,mhuwiler/rootauto,georgtroska/root,omazapa/root,thomaskeck/root,mkret2/root,bbockelm/root,zzxuanyuan/root-compressor-dummy,evgeny-boger/root,cxx-hep/root-cern,sirinath/root,krafczyk/root,CristinaCristescu/root,agarciamontoro/root,gganis/root,omazapa/root-old,omazapa/root-old,root-mirror/root,omazapa/root,evgeny-boger/root,zzxuanyuan/root-compressor-dummy,lgiommi/root,evgeny-boger/root,root-mirror/root,vukasinmilosevic/root,jrtomps/root,zzxuanyuan/root,pspe/root,arch1tect0r/root,abhinavmoudgil95/root,Duraznos/root,satyarth934/root,sirinath/root,karies/root,veprbl/root,CristinaCristescu/root,omazapa/root,sawenzel/root,CristinaCristescu/root,simonpf/root,omazapa/root-old,georgtroska/root,mhuwiler/rootauto,abhinavmoudgil95/root,smarinac/root,sbinet/cxx-root,beniz/root,evgeny-boger/root,thomaskeck/root,agarciamontoro/root,mkret2/root,pspe/root,cxx-hep/root-cern,agarciamontoro/root,satyarth934/root,CristinaCristescu/root,abhinavmoudgil95/root,BerserkerTroll/root,esakellari/root,pspe/root,lgiommi/root,thomaskeck/root,mattkretz/root,agarciamontoro/root,root-mirror/root,agarciamontoro/root,satyarth934/root,mkret2/root,jrtomps/root,sirinath/root,dfunke/root,bbockelm/root,alexschlueter/cern-root,jrtomps/root,olifre/root,georgtroska/root,simonpf/root,0x0all/ROOT,omazapa/root,sbinet/cxx-root,abhinavmoudgil95/root,olifre/root,jrtomps/root,root-mirror/root,davidlt/root,bbockelm/root,perovic/root,cxx-hep/root-cern,davidlt/root,sbinet/cxx-root,omazapa/root,dfunke/root,olifre/root,mkret2/root,omazapa/root-old,mhuwiler/rootauto,vukasinmilosevic/root,esakellari/root,davidlt/root,esakellari/my_root_for_test,mattkretz/root,mattkretz/root,dfunke/root,Y--/root,agarciamontoro/root,veprbl/root,buuck/root,CristinaCristescu/root,perovic/root,mkret2/root,mattkretz/root,nilqed/root,lgiommi/root,lgiommi/root,abhinavmoudgil95/root,beniz/root,krafczyk/root,georgtroska/root,zzxuanyuan/root-compressor-dummy,CristinaCristescu/root,gbitzes/root,sirinath/root,gbitzes/root,sawenzel/root,nilqed/root,buuck/root,zzxuanyuan/root-compressor-dummy,mkret2/root,mkret2/root,smarinac/root,veprbl/root,mhuwiler/rootauto,alexschlueter/cern-root,omazapa/root,Y--/root,abhinavmoudgil95/root,cxx-hep/root-cern,satyarth934/root,Y--/root,nilqed/root,Y--/root,lgiommi/root,karies/root,simonpf/root,davidlt/root,sirinath/root,sbinet/cxx-root,davidlt/root,alexschlueter/cern-root,lgiommi/root,lgiommi/root,perovic/root,bbockelm/root,georgtroska/root,dfunke/root,krafczyk/root,agarciamontoro/root,sbinet/cxx-root,perovic/root,CristinaCristescu/root,zzxuanyuan/root,arch1tect0r/root,0x0all/ROOT,esakellari/root,omazapa/root-old
c
## Code Before: //--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> //------------------------------------------------------------------------------ #ifndef CLING_COMPILATIONEXCEPTION_H #define CLING_COMPILATIONEXCEPTION_H #include <stdexcept> #include <string> #include "cling/Interpreter/RuntimeException.h" namespace cling { class Interpreter; class MetaProcessor; //\brief Exception pull us out of JIT (llvm + clang) errors. class CompilationException: public virtual runtime::InterpreterException, public virtual std::runtime_error { public: CompilationException(const std::string& reason): std::runtime_error(reason) {} ~CompilationException() throw(); // vtable pinned to UserInterface.cpp virtual const char* what() const throw() { return std::runtime_error::what(); } }; } #endif // CLING_COMPILATIONEXCEPTION_H ## Instruction: Add more rationale as to how this exception is different from others. ## Code After: //--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> //------------------------------------------------------------------------------ #ifndef CLING_COMPILATIONEXCEPTION_H #define CLING_COMPILATIONEXCEPTION_H #include <stdexcept> #include <string> #include "cling/Interpreter/RuntimeException.h" namespace cling { class Interpreter; class MetaProcessor; ///\brief Exception that pulls cling out of runtime-compilation (llvm + clang) /// errors. /// /// If user code provokes an llvm::unreachable it will cause this exception /// to be thrown. Given that this is at the process's runtime and an /// interpreter error it inherits from InterpreterException and runtime_error. /// Note that this exception is *not* thrown during the execution of the /// user's code but during its compilation (at runtime). class CompilationException: public virtual runtime::InterpreterException, public virtual std::runtime_error { public: CompilationException(const std::string& reason): std::runtime_error(reason) {} ~CompilationException() throw(); // vtable pinned to UserInterface.cpp virtual const char* what() const throw() { return std::runtime_error::what(); } }; } #endif // CLING_COMPILATIONEXCEPTION_H
// ... existing code ... class Interpreter; class MetaProcessor; ///\brief Exception that pulls cling out of runtime-compilation (llvm + clang) /// errors. /// /// If user code provokes an llvm::unreachable it will cause this exception /// to be thrown. Given that this is at the process's runtime and an /// interpreter error it inherits from InterpreterException and runtime_error. /// Note that this exception is *not* thrown during the execution of the /// user's code but during its compilation (at runtime). class CompilationException: public virtual runtime::InterpreterException, public virtual std::runtime_error { // ... rest of the code ...
c62af27fdf1ffd59a9f245ecda6ed6f39a258856
main.c
main.c
// Copyright (c) 2016 LEGOAnimal22 #include <stdio.h> #include <inttypes.h> #include "electron.h" int main() { printf("Periodic Table by LEGOAnimal22\n"); electron_config carbon = create_electron_config(6); printf("%d, %d, %d, %d\n", carbon.atomic_number, carbon.highest_energy_level, carbon.valence_electrons, carbon.charge); electron_config gold = create_electron_config(79); printf("%d, %d, %d, %d\n", gold.atomic_number, gold.highest_energy_level, gold.valence_electrons, gold.charge); electron_config radon = create_electron_config(86); printf("%d, %d, %d, %d\n", radon.atomic_number, radon.highest_energy_level, radon.valence_electrons, radon.charge); // (((atomic_number - 54) > 2) ? 2 : (atomic_number - 54)) + ((atomic_number > 80) ? (atomic_number - 80) : 0) printf("%d\n", (((86 - 54) > 2) ? 2 : (86 - 54))); printf("%d\n", ((86 > 80) ? (86 - 80) : 0)); return 1; }
// Copyright (c) 2016 LEGOAnimal22 #include <stdio.h> #include <inttypes.h> #include "electron.h" int main() { printf("Periodic Table by LEGOAnimal22\n"); electron_config carbon = create_electron_config(6); printf("%d, %d, %d, %d\n", carbon.atomic_number, carbon.highest_energy_level, carbon.valence_electrons, carbon.charge); electron_config gold = create_electron_config(79); printf("%d, %d, %d, %d\n", gold.atomic_number, gold.highest_energy_level, gold.valence_electrons, gold.charge); electron_config radon = create_electron_config(86); printf("%d, %d, %d, %d\n", radon.atomic_number, radon.highest_energy_level, radon.valence_electrons, radon.charge); // (((atomic_number - 54) > 2) ? 2 : (atomic_number - 54)) + ((atomic_number > 80) ? (atomic_number - 80) : 0) unsigned int x = 86; printf("%d\n", (((x - 54) > 2) ? 2 : (x - 54))); printf("%d\n", ((x > 80) ? (x - 80) : 0)); printf("%d\n", (((x - 54) > 2) ? 2 : (x - 54)) + ((x > 80) ? (x - 80) : 0)); return 1; }
Test level 6 with a variable instead of a constant
Test level 6 with a variable instead of a constant
C
mit
LEGOAnimal22/periodictable_c
c
## Code Before: // Copyright (c) 2016 LEGOAnimal22 #include <stdio.h> #include <inttypes.h> #include "electron.h" int main() { printf("Periodic Table by LEGOAnimal22\n"); electron_config carbon = create_electron_config(6); printf("%d, %d, %d, %d\n", carbon.atomic_number, carbon.highest_energy_level, carbon.valence_electrons, carbon.charge); electron_config gold = create_electron_config(79); printf("%d, %d, %d, %d\n", gold.atomic_number, gold.highest_energy_level, gold.valence_electrons, gold.charge); electron_config radon = create_electron_config(86); printf("%d, %d, %d, %d\n", radon.atomic_number, radon.highest_energy_level, radon.valence_electrons, radon.charge); // (((atomic_number - 54) > 2) ? 2 : (atomic_number - 54)) + ((atomic_number > 80) ? (atomic_number - 80) : 0) printf("%d\n", (((86 - 54) > 2) ? 2 : (86 - 54))); printf("%d\n", ((86 > 80) ? (86 - 80) : 0)); return 1; } ## Instruction: Test level 6 with a variable instead of a constant ## Code After: // Copyright (c) 2016 LEGOAnimal22 #include <stdio.h> #include <inttypes.h> #include "electron.h" int main() { printf("Periodic Table by LEGOAnimal22\n"); electron_config carbon = create_electron_config(6); printf("%d, %d, %d, %d\n", carbon.atomic_number, carbon.highest_energy_level, carbon.valence_electrons, carbon.charge); electron_config gold = create_electron_config(79); printf("%d, %d, %d, %d\n", gold.atomic_number, gold.highest_energy_level, gold.valence_electrons, gold.charge); electron_config radon = create_electron_config(86); printf("%d, %d, %d, %d\n", radon.atomic_number, radon.highest_energy_level, radon.valence_electrons, radon.charge); // (((atomic_number - 54) > 2) ? 2 : (atomic_number - 54)) + ((atomic_number > 80) ? (atomic_number - 80) : 0) unsigned int x = 86; printf("%d\n", (((x - 54) > 2) ? 2 : (x - 54))); printf("%d\n", ((x > 80) ? (x - 80) : 0)); printf("%d\n", (((x - 54) > 2) ? 2 : (x - 54)) + ((x > 80) ? (x - 80) : 0)); return 1; }
... printf("%d, %d, %d, %d\n", radon.atomic_number, radon.highest_energy_level, radon.valence_electrons, radon.charge); // (((atomic_number - 54) > 2) ? 2 : (atomic_number - 54)) + ((atomic_number > 80) ? (atomic_number - 80) : 0) unsigned int x = 86; printf("%d\n", (((x - 54) > 2) ? 2 : (x - 54))); printf("%d\n", ((x > 80) ? (x - 80) : 0)); printf("%d\n", (((x - 54) > 2) ? 2 : (x - 54)) + ((x > 80) ? (x - 80) : 0)); return 1; } ...
8f0956313b140d7a0d51510cd9b4a5eec7d54570
plugins/holland.lib.lvm/tests/test_util.py
plugins/holland.lib.lvm/tests/test_util.py
import os import signal from nose.tools import * from holland.lib.lvm.util import * def test_format_bytes(): assert_equals(format_bytes(1024), '1.00KB') assert_equals(format_bytes(0), '0.00Bytes') def test_getmount(): assert_equals(getmount('/'), '/') assert_equals(getmount('/foobarbaz'), '/') def test_getdevice(): # XXX: bad hack dev = open('/etc/mtab', 'r').readline().split()[0].strip() assert_equals(getdevice('/'), dev) assert_equals(getdevice('/foobarbaz'), None) def test_relpath(): assert_raises(ValueError, relpath, '') assert_equals(relpath('/foo/bar/baz', '/foo/bar'), 'baz') assert_equals(relpath('/foo/bar/', '/foo/bar/'), os.curdir) def test_signalmanager(): sigmgr = SignalManager() sigmgr.trap(signal.SIGINT) os.kill(os.getpid(), signal.SIGINT) ok_(sigmgr.pending) assert_equals(sigmgr.pending[0], signal.SIGINT) sigmgr.restore() assert_raises(KeyboardInterrupt, os.kill, os.getpid(), signal.SIGINT)
import os import signal from nose.tools import * from holland.lib.lvm.util import * def test_format_bytes(): assert_equals(format_bytes(1024), '1.00KB') assert_equals(format_bytes(0), '0.00Bytes') def test_getmount(): assert_equals(getmount('/'), '/') assert_equals(getmount('/foobarbaz'), '/') def test_getdevice(): # XXX: bad hack dev = open('/etc/mtab', 'r').readline().split()[0].strip() assert_equals(getdevice('/'), dev) assert_equals(getdevice('/foobarbaz'), None) def test_relpath(): assert_raises(ValueError, relpath, '') assert_equals(relpath('/foo/bar/baz', '/foo/bar'), 'baz') assert_equals(relpath('/foo/bar/', '/foo/bar/'), os.curdir) def test_signalmanager(): sigmgr = SignalManager() sigmgr.trap(signal.SIGINT) os.kill(os.getpid(), signal.SIGINT) ok_(sigmgr.pending) assert_equals(sigmgr.pending[0], signal.SIGINT) sigmgr.restore() assert_raises(KeyboardInterrupt, os.kill, os.getpid(), signal.SIGINT) def test_parsebytes(): # bytes without units should be interpretted as MB bytes = parse_bytes('1024') assert_equals(bytes, 1024**3) # this should not be bytes ok_(bytes > 1024) bytes = parse_bytes('1024G') assert_equals(bytes, 1024**4)
Add test case to holland.lib.lvm for parsing snapshot-size without units
Add test case to holland.lib.lvm for parsing snapshot-size without units
Python
bsd-3-clause
m00dawg/holland,m00dawg/holland
python
## Code Before: import os import signal from nose.tools import * from holland.lib.lvm.util import * def test_format_bytes(): assert_equals(format_bytes(1024), '1.00KB') assert_equals(format_bytes(0), '0.00Bytes') def test_getmount(): assert_equals(getmount('/'), '/') assert_equals(getmount('/foobarbaz'), '/') def test_getdevice(): # XXX: bad hack dev = open('/etc/mtab', 'r').readline().split()[0].strip() assert_equals(getdevice('/'), dev) assert_equals(getdevice('/foobarbaz'), None) def test_relpath(): assert_raises(ValueError, relpath, '') assert_equals(relpath('/foo/bar/baz', '/foo/bar'), 'baz') assert_equals(relpath('/foo/bar/', '/foo/bar/'), os.curdir) def test_signalmanager(): sigmgr = SignalManager() sigmgr.trap(signal.SIGINT) os.kill(os.getpid(), signal.SIGINT) ok_(sigmgr.pending) assert_equals(sigmgr.pending[0], signal.SIGINT) sigmgr.restore() assert_raises(KeyboardInterrupt, os.kill, os.getpid(), signal.SIGINT) ## Instruction: Add test case to holland.lib.lvm for parsing snapshot-size without units ## Code After: import os import signal from nose.tools import * from holland.lib.lvm.util import * def test_format_bytes(): assert_equals(format_bytes(1024), '1.00KB') assert_equals(format_bytes(0), '0.00Bytes') def test_getmount(): assert_equals(getmount('/'), '/') assert_equals(getmount('/foobarbaz'), '/') def test_getdevice(): # XXX: bad hack dev = open('/etc/mtab', 'r').readline().split()[0].strip() assert_equals(getdevice('/'), dev) assert_equals(getdevice('/foobarbaz'), None) def test_relpath(): assert_raises(ValueError, relpath, '') assert_equals(relpath('/foo/bar/baz', '/foo/bar'), 'baz') assert_equals(relpath('/foo/bar/', '/foo/bar/'), os.curdir) def test_signalmanager(): sigmgr = SignalManager() sigmgr.trap(signal.SIGINT) os.kill(os.getpid(), signal.SIGINT) ok_(sigmgr.pending) assert_equals(sigmgr.pending[0], signal.SIGINT) sigmgr.restore() assert_raises(KeyboardInterrupt, os.kill, os.getpid(), signal.SIGINT) def test_parsebytes(): # bytes without units should be interpretted as MB bytes = parse_bytes('1024') assert_equals(bytes, 1024**3) # this should not be bytes ok_(bytes > 1024) bytes = parse_bytes('1024G') assert_equals(bytes, 1024**4)
# ... existing code ... assert_equals(sigmgr.pending[0], signal.SIGINT) sigmgr.restore() assert_raises(KeyboardInterrupt, os.kill, os.getpid(), signal.SIGINT) def test_parsebytes(): # bytes without units should be interpretted as MB bytes = parse_bytes('1024') assert_equals(bytes, 1024**3) # this should not be bytes ok_(bytes > 1024) bytes = parse_bytes('1024G') assert_equals(bytes, 1024**4) # ... rest of the code ...
814846bfc8f30cd91164ae126863ae4252edabb0
app/drones/messages/JPEGFrameMessage.java
app/drones/messages/JPEGFrameMessage.java
package drones.messages; import java.io.Serializable; /** * Created by brecht on 4/20/15. */ public class JPEGFrameMessage implements Serializable { private String imageData; public JPEGFrameMessage(String imageData) { this.imageData = imageData; } public String getImageData() { return imageData; } }
package drones.messages; import java.io.Serializable; /** * Created by brecht on 4/20/15. */ public class JPEGFrameMessage implements Serializable { private String imageData; /** * * @param imageData The image data as a base 64 string */ public JPEGFrameMessage(String imageData) { this.imageData = imageData; } /** * * @return The image data as a base 64 string */ public String getImageData() { return imageData; } }
Add comments to JPEG message
Add comments to JPEG message
Java
mit
ugent-cros/cros-core,ugent-cros/cros-core,ugent-cros/cros-core
java
## Code Before: package drones.messages; import java.io.Serializable; /** * Created by brecht on 4/20/15. */ public class JPEGFrameMessage implements Serializable { private String imageData; public JPEGFrameMessage(String imageData) { this.imageData = imageData; } public String getImageData() { return imageData; } } ## Instruction: Add comments to JPEG message ## Code After: package drones.messages; import java.io.Serializable; /** * Created by brecht on 4/20/15. */ public class JPEGFrameMessage implements Serializable { private String imageData; /** * * @param imageData The image data as a base 64 string */ public JPEGFrameMessage(String imageData) { this.imageData = imageData; } /** * * @return The image data as a base 64 string */ public String getImageData() { return imageData; } }
// ... existing code ... private String imageData; /** * * @param imageData The image data as a base 64 string */ public JPEGFrameMessage(String imageData) { this.imageData = imageData; } /** * * @return The image data as a base 64 string */ public String getImageData() { return imageData; } // ... rest of the code ...
2a17e7ec549d6e535ed585ed46075a825bc607ab
ZhihuDailyPurify/src/main/java/io/github/izzyleung/zhihudailypurify/task/BaseGetNewsTask.java
ZhihuDailyPurify/src/main/java/io/github/izzyleung/zhihudailypurify/task/BaseGetNewsTask.java
package io.github.izzyleung.zhihudailypurify.task; import io.github.izzyleung.zhihudailypurify.ZhihuDailyPurifyApplication; import io.github.izzyleung.zhihudailypurify.bean.DailyNews; import java.util.List; public abstract class BaseGetNewsTask extends BaseDownloadTask<Void, Void, List<DailyNews>> { protected boolean isRefreshSuccess = true; protected boolean isContentSame = false; protected String date; private OnTaskFinishedCallback mCallback; public BaseGetNewsTask(String date, OnTaskFinishedCallback callback) { this.date = date; this.mCallback = callback; } @Override protected void onPreExecute() { mCallback.beforeTaskStart(); } @Override protected void onPostExecute(List<DailyNews> resultNewsList) { mCallback.afterTaskFinished(resultNewsList, isRefreshSuccess, isContentSame); } protected boolean checkIsNewsListEquals(List<DailyNews> newsListFromWeb) { return newsListFromWeb.equals(ZhihuDailyPurifyApplication.getInstance().getDataSource().newsOfTheDay(date)); } public interface OnTaskFinishedCallback { public void beforeTaskStart(); public void afterTaskFinished(List<DailyNews> resultList, boolean isRefreshSuccess, boolean isContentSame); } }
package io.github.izzyleung.zhihudailypurify.task; import io.github.izzyleung.zhihudailypurify.ZhihuDailyPurifyApplication; import io.github.izzyleung.zhihudailypurify.bean.DailyNews; import java.util.List; public abstract class BaseGetNewsTask extends BaseDownloadTask<Void, Void, List<DailyNews>> { protected boolean isRefreshSuccess = true; protected boolean isContentSame = false; protected String date; private OnTaskFinishedCallback mCallback; public BaseGetNewsTask(String date, OnTaskFinishedCallback callback) { this.date = date; this.mCallback = callback; } @Override protected void onPreExecute() { mCallback.beforeTaskStart(); } @Override protected void onPostExecute(List<DailyNews> resultNewsList) { mCallback.afterTaskFinished(resultNewsList, isRefreshSuccess, isContentSame); mCallback = null; } protected boolean checkIsNewsListEquals(List<DailyNews> newsListFromWeb) { return newsListFromWeb.equals(ZhihuDailyPurifyApplication.getInstance().getDataSource().newsOfTheDay(date)); } public interface OnTaskFinishedCallback { public void beforeTaskStart(); public void afterTaskFinished(List<DailyNews> resultList, boolean isRefreshSuccess, boolean isContentSame); } }
Remove callback when the job is done
Remove callback when the job is done
Java
apache-2.0
JohnTsaiAndroid/ZhihuDailyPurify,hzy87email/ZhihuDailyPurify,02N/ZhihuDailyPurify,ALEXGUOQ/ZhihuDailyPurify,Neilsgithub/ZhihuDailyPurify,hesy007/ZhihuDailyPurify,shireworld/ZhihuDailyPurify,zhouzizi/ZhihuDailyPurify,520it/ZhihuDailyPurify,owenmike/ZhihuDailyPurify,treejames/ZhihuDailyPurify,pingfanganwei/ZhihuDailyPurify,Feitianyuan/ZhihuDailyPurify,AlphaShawn/ZhihuDailyPurify,Hazy-Sunshine/ZhihuDailyPurify,PandaraWen/ZhihuDailyPurify,tonycheng93/ZhihuDailyPurify,michellewkx/ZhihuDailyPurify,Carbs0126/ZhihuDailyPurify,hxx/ZhihuDailyPurify,wslongchen/ZhihuDailyPurify,huhu/ZhihuDailyPurify,it114/ZhihuDailyPurify,zhangswings/ZhihuDailyPurify,qianguming/ZhihuDailyPurify,XinboAndroid/ZhihuDailyPurify,Ph0enixxx/ZhihuDailyPurify,leo493852107/ZhihuDailyPurify,lkkjzx/ZhihuDailyPurify,Jokeby/ZhihuDailyPurify,yuxiaole/ZhihuDailyPurify,Rowandjj/ZhihuDailyPurify,yiShanXin/ZhihuDailyPurify,zzwwws/ZhihuDailyPurify,Tedko/ZhihuDailyPurify,youlingme/ZhihuDailyPurify,164738777/ZhihuDailyPurify,uurain/ZhihuDailyPurify,sunhai1992/ZhihuDailyPurify,wangmingjob/ZhihuDailyPurify,sinlov/ZhihuDailyPurify
java
## Code Before: package io.github.izzyleung.zhihudailypurify.task; import io.github.izzyleung.zhihudailypurify.ZhihuDailyPurifyApplication; import io.github.izzyleung.zhihudailypurify.bean.DailyNews; import java.util.List; public abstract class BaseGetNewsTask extends BaseDownloadTask<Void, Void, List<DailyNews>> { protected boolean isRefreshSuccess = true; protected boolean isContentSame = false; protected String date; private OnTaskFinishedCallback mCallback; public BaseGetNewsTask(String date, OnTaskFinishedCallback callback) { this.date = date; this.mCallback = callback; } @Override protected void onPreExecute() { mCallback.beforeTaskStart(); } @Override protected void onPostExecute(List<DailyNews> resultNewsList) { mCallback.afterTaskFinished(resultNewsList, isRefreshSuccess, isContentSame); } protected boolean checkIsNewsListEquals(List<DailyNews> newsListFromWeb) { return newsListFromWeb.equals(ZhihuDailyPurifyApplication.getInstance().getDataSource().newsOfTheDay(date)); } public interface OnTaskFinishedCallback { public void beforeTaskStart(); public void afterTaskFinished(List<DailyNews> resultList, boolean isRefreshSuccess, boolean isContentSame); } } ## Instruction: Remove callback when the job is done ## Code After: package io.github.izzyleung.zhihudailypurify.task; import io.github.izzyleung.zhihudailypurify.ZhihuDailyPurifyApplication; import io.github.izzyleung.zhihudailypurify.bean.DailyNews; import java.util.List; public abstract class BaseGetNewsTask extends BaseDownloadTask<Void, Void, List<DailyNews>> { protected boolean isRefreshSuccess = true; protected boolean isContentSame = false; protected String date; private OnTaskFinishedCallback mCallback; public BaseGetNewsTask(String date, OnTaskFinishedCallback callback) { this.date = date; this.mCallback = callback; } @Override protected void onPreExecute() { mCallback.beforeTaskStart(); } @Override protected void onPostExecute(List<DailyNews> resultNewsList) { mCallback.afterTaskFinished(resultNewsList, isRefreshSuccess, isContentSame); mCallback = null; } protected boolean checkIsNewsListEquals(List<DailyNews> newsListFromWeb) { return newsListFromWeb.equals(ZhihuDailyPurifyApplication.getInstance().getDataSource().newsOfTheDay(date)); } public interface OnTaskFinishedCallback { public void beforeTaskStart(); public void afterTaskFinished(List<DailyNews> resultList, boolean isRefreshSuccess, boolean isContentSame); } }
// ... existing code ... @Override protected void onPostExecute(List<DailyNews> resultNewsList) { mCallback.afterTaskFinished(resultNewsList, isRefreshSuccess, isContentSame); mCallback = null; } protected boolean checkIsNewsListEquals(List<DailyNews> newsListFromWeb) { // ... rest of the code ...
c823a476b265b46d27b221831be952a811fe3468
ANN.py
ANN.py
class Neuron: pass class NeuronNetwork: neurons = []
class Neuron: pass class NeuronNetwork: neurons = [] def __init__(self, rows, columns): self.neurons = [] for row in xrange(rows): self.neurons.append([]) for column in xrange(columns): self.neurons[row].append(Neuron())
Create 2D list of Neurons in NeuronNetwork's init
Create 2D list of Neurons in NeuronNetwork's init
Python
mit
tysonzero/py-ann
python
## Code Before: class Neuron: pass class NeuronNetwork: neurons = [] ## Instruction: Create 2D list of Neurons in NeuronNetwork's init ## Code After: class Neuron: pass class NeuronNetwork: neurons = [] def __init__(self, rows, columns): self.neurons = [] for row in xrange(rows): self.neurons.append([]) for column in xrange(columns): self.neurons[row].append(Neuron())
# ... existing code ... class NeuronNetwork: neurons = [] def __init__(self, rows, columns): self.neurons = [] for row in xrange(rows): self.neurons.append([]) for column in xrange(columns): self.neurons[row].append(Neuron()) # ... rest of the code ...
480c89d81e1610d698269c41f4543c38193bef13
test/test_orthomcl_database.py
test/test_orthomcl_database.py
import shutil import tempfile import unittest import orthomcl_database class Test(unittest.TestCase): def setUp(self): self.run_dir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.run_dir) def test_get_configuration_file(self): conffile = orthomcl_database.get_configuration_file(self.run_dir, 'test_dbname', 5) with open(conffile) as reader: content = reader.read() self.assertIn('orthomcl', content) self.assertIn('127.0.0.1', content) self.assertIn('mysql', content) self.assertIn('evalueExponentCutoff=5\n', content) def test_create_database(self): dbname = orthomcl_database.create_database() orthomcl_database.delete_database(dbname)
import MySQLdb import shutil import tempfile import unittest import orthomcl_database class Test(unittest.TestCase): def setUp(self): self.run_dir = tempfile.mkdtemp() self.credentials = orthomcl_database._get_root_credentials() def tearDown(self): shutil.rmtree(self.run_dir) def test_get_configuration_file(self): ''' Create a configuration file, and ensure the contents match assumptions. ''' conffile = orthomcl_database.get_configuration_file(self.run_dir, 'test_dbname', 5) with open(conffile) as reader: content = reader.read() self.assertIn('orthomcl', content) self.assertIn('127.0.0.1', content) self.assertIn('mysql', content) self.assertIn('evalueExponentCutoff=5\n', content) def test_create_database(self): ''' Create a database, connect to it and perform a simple select query, verify the outcome and delete the database. ''' try: # Create database dbname = orthomcl_database.create_database() # Access database as restricted user db_connection = MySQLdb.connect(host=self.credentials.host, port=self.credentials.port, user='orthomcl', passwd='pass') db_connection.query('SELECT 1') result = db_connection.store_result() self.assertEqual(1L, result.fetch_row()[0][0]) db_connection.close() finally: if dbname: # Delete database orthomcl_database.delete_database(dbname)
Expand test to include query on the created database as restricted user
Expand test to include query on the created database as restricted user
Python
mit
ODoSE/odose.nl
python
## Code Before: import shutil import tempfile import unittest import orthomcl_database class Test(unittest.TestCase): def setUp(self): self.run_dir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.run_dir) def test_get_configuration_file(self): conffile = orthomcl_database.get_configuration_file(self.run_dir, 'test_dbname', 5) with open(conffile) as reader: content = reader.read() self.assertIn('orthomcl', content) self.assertIn('127.0.0.1', content) self.assertIn('mysql', content) self.assertIn('evalueExponentCutoff=5\n', content) def test_create_database(self): dbname = orthomcl_database.create_database() orthomcl_database.delete_database(dbname) ## Instruction: Expand test to include query on the created database as restricted user ## Code After: import MySQLdb import shutil import tempfile import unittest import orthomcl_database class Test(unittest.TestCase): def setUp(self): self.run_dir = tempfile.mkdtemp() self.credentials = orthomcl_database._get_root_credentials() def tearDown(self): shutil.rmtree(self.run_dir) def test_get_configuration_file(self): ''' Create a configuration file, and ensure the contents match assumptions. ''' conffile = orthomcl_database.get_configuration_file(self.run_dir, 'test_dbname', 5) with open(conffile) as reader: content = reader.read() self.assertIn('orthomcl', content) self.assertIn('127.0.0.1', content) self.assertIn('mysql', content) self.assertIn('evalueExponentCutoff=5\n', content) def test_create_database(self): ''' Create a database, connect to it and perform a simple select query, verify the outcome and delete the database. ''' try: # Create database dbname = orthomcl_database.create_database() # Access database as restricted user db_connection = MySQLdb.connect(host=self.credentials.host, port=self.credentials.port, user='orthomcl', passwd='pass') db_connection.query('SELECT 1') result = db_connection.store_result() self.assertEqual(1L, result.fetch_row()[0][0]) db_connection.close() finally: if dbname: # Delete database orthomcl_database.delete_database(dbname)
# ... existing code ... import MySQLdb import shutil import tempfile import unittest # ... modified code ... def setUp(self): self.run_dir = tempfile.mkdtemp() self.credentials = orthomcl_database._get_root_credentials() def tearDown(self): shutil.rmtree(self.run_dir) def test_get_configuration_file(self): ''' Create a configuration file, and ensure the contents match assumptions. ''' conffile = orthomcl_database.get_configuration_file(self.run_dir, 'test_dbname', 5) with open(conffile) as reader: content = reader.read() ... self.assertIn('evalueExponentCutoff=5\n', content) def test_create_database(self): ''' Create a database, connect to it and perform a simple select query, verify the outcome and delete the database. ''' try: # Create database dbname = orthomcl_database.create_database() # Access database as restricted user db_connection = MySQLdb.connect(host=self.credentials.host, port=self.credentials.port, user='orthomcl', passwd='pass') db_connection.query('SELECT 1') result = db_connection.store_result() self.assertEqual(1L, result.fetch_row()[0][0]) db_connection.close() finally: if dbname: # Delete database orthomcl_database.delete_database(dbname) # ... rest of the code ...
5fe3187ba546bea4d948914b2eb5cf9953a5bee6
tests/clip_test.py
tests/clip_test.py
import PyDSTool as dst from PyDSTool.Toolbox.phaseplane import Point2D from matplotlib import pyplot as plt from fovea.graphics import * # ISSUE: fix to use new argument format for function (no global) plotter.domain={'x': [-1,1], 'y': [-2,2]} plotter.coords=('x','y') a, b = force_line_to_extent(Point2D((0.25,0)), Point2D((0.5,0.1))) plt.plot(np.array((a, b)).T[0], np.array((a, b)).T[1], 'g') cc, dd = Point2D((3,-2.5)), Point2D((-5.1,1.8)) plt.plot(np.array((cc, dd)).T[0], np.array((cc, dd)).T[1], 'b:') c, d = force_line_to_extent(Point2D((3,-2.5)), Point2D((-5.1,1.8))) plt.plot(np.array((c, d)).T[0], np.array((c, d)).T[1], 'r') plt.show()
import PyDSTool as dst from PyDSTool.Toolbox.phaseplane import Point2D from matplotlib import pyplot as plt import numpy as np from fovea.graphics import * plotter.domain={'x': [-1,1], 'y': [-2,2]} plotter.coords=('x','y') a, b = force_line_to_extent(Point2D((0.25,0)), Point2D((0.5,0.1)), plotter.domain, plotter.coords) plt.plot(np.array((a, b)).T[0], np.array((a, b)).T[1], 'g') cc, dd = Point2D((3,-2.5)), Point2D((-5.1,1.8)) plt.plot(np.array((cc, dd)).T[0], np.array((cc, dd)).T[1], 'b:') c, d = force_line_to_extent(Point2D((3,-2.5)), Point2D((-5.1,1.8)), plotter.domain, plotter.coords) plt.plot(np.array((c, d)).T[0], np.array((c, d)).T[1], 'r') e, f = force_line_to_extent(np.array((0.25,0)), np.array((1.5,0.1)), plotter.domain, plotter.coords) plt.plot(np.array((e, f)).T[0], np.array((e, f)).T[1], 'g') plt.show()
Fix new syntax and add example using numpy arrays
Fix new syntax and add example using numpy arrays
Python
bsd-3-clause
robclewley/fovea,akuefler/fovea
python
## Code Before: import PyDSTool as dst from PyDSTool.Toolbox.phaseplane import Point2D from matplotlib import pyplot as plt from fovea.graphics import * # ISSUE: fix to use new argument format for function (no global) plotter.domain={'x': [-1,1], 'y': [-2,2]} plotter.coords=('x','y') a, b = force_line_to_extent(Point2D((0.25,0)), Point2D((0.5,0.1))) plt.plot(np.array((a, b)).T[0], np.array((a, b)).T[1], 'g') cc, dd = Point2D((3,-2.5)), Point2D((-5.1,1.8)) plt.plot(np.array((cc, dd)).T[0], np.array((cc, dd)).T[1], 'b:') c, d = force_line_to_extent(Point2D((3,-2.5)), Point2D((-5.1,1.8))) plt.plot(np.array((c, d)).T[0], np.array((c, d)).T[1], 'r') plt.show() ## Instruction: Fix new syntax and add example using numpy arrays ## Code After: import PyDSTool as dst from PyDSTool.Toolbox.phaseplane import Point2D from matplotlib import pyplot as plt import numpy as np from fovea.graphics import * plotter.domain={'x': [-1,1], 'y': [-2,2]} plotter.coords=('x','y') a, b = force_line_to_extent(Point2D((0.25,0)), Point2D((0.5,0.1)), plotter.domain, plotter.coords) plt.plot(np.array((a, b)).T[0], np.array((a, b)).T[1], 'g') cc, dd = Point2D((3,-2.5)), Point2D((-5.1,1.8)) plt.plot(np.array((cc, dd)).T[0], np.array((cc, dd)).T[1], 'b:') c, d = force_line_to_extent(Point2D((3,-2.5)), Point2D((-5.1,1.8)), plotter.domain, plotter.coords) plt.plot(np.array((c, d)).T[0], np.array((c, d)).T[1], 'r') e, f = force_line_to_extent(np.array((0.25,0)), np.array((1.5,0.1)), plotter.domain, plotter.coords) plt.plot(np.array((e, f)).T[0], np.array((e, f)).T[1], 'g') plt.show()
... import PyDSTool as dst from PyDSTool.Toolbox.phaseplane import Point2D from matplotlib import pyplot as plt import numpy as np from fovea.graphics import * plotter.domain={'x': [-1,1], 'y': [-2,2]} plotter.coords=('x','y') a, b = force_line_to_extent(Point2D((0.25,0)), Point2D((0.5,0.1)), plotter.domain, plotter.coords) plt.plot(np.array((a, b)).T[0], np.array((a, b)).T[1], 'g') cc, dd = Point2D((3,-2.5)), Point2D((-5.1,1.8)) plt.plot(np.array((cc, dd)).T[0], np.array((cc, dd)).T[1], 'b:') c, d = force_line_to_extent(Point2D((3,-2.5)), Point2D((-5.1,1.8)), plotter.domain, plotter.coords) plt.plot(np.array((c, d)).T[0], np.array((c, d)).T[1], 'r') e, f = force_line_to_extent(np.array((0.25,0)), np.array((1.5,0.1)), plotter.domain, plotter.coords) plt.plot(np.array((e, f)).T[0], np.array((e, f)).T[1], 'g') plt.show() ...
e94eaefbc28978b1ed171407a70fdb1373a617cc
Jrainbuck/src/io/github/rlee287/jrainbuck/constants/Constants.java
Jrainbuck/src/io/github/rlee287/jrainbuck/constants/Constants.java
package io.github.rlee287.jrainbuck.constants; public class SwitchList { //public static final int CLASSIC_SIZE=30000; public static final String[] LIST_SWITCHES={"-file","-input","-output"}; /* 0|file MANDATORY * 1|stdin OPTIONAL * 2|stdout OPTIONAL */ }
package io.github.rlee287.jrainbuck.constants; import java.util.HashMap; public class Constants { //public static final int CLASSIC_SIZE=30000; public static final String[] LIST_SWITCHES={"-file","-input","-output"}; /* 0|file MANDATORY * 1|stdin OPTIONAL * 2|stdout OPTIONAL */ public static final Character[] ALLOWED_CHAR={'[',']','+','-','<','>','.',','}; private static HashMap<Character, Byte> INIT_UVB_MAP= new HashMap <Character,Byte>(); static { /* JUMP_FORWARD_ZERO 0b1000 0001*/ INIT_UVB_MAP.put('[', new Byte((byte)-127)); /* JUMP_BACKWARD_NONZERO 0b1000 0000*/ INIT_UVB_MAP.put(']', new Byte((byte)-128)); /* ARRAY_INCREMENT 0b0100 0001*/ INIT_UVB_MAP.put('+', new Byte((byte)65)); /* ARRAY_DECREMENT 0b0100 0000*/ INIT_UVB_MAP.put('-', new Byte((byte)64)); /* POINTER_LEFT 0b0010 0000*/ INIT_UVB_MAP.put('<', new Byte((byte)32)); /* POINTER_RIGHT 0b0010 0001*/ INIT_UVB_MAP.put('>', new Byte((byte)33)); /* STDOUT 0b0001 0000*/ INIT_UVB_MAP.put('.', new Byte((byte)16)); /* STDIN 0b0001 0001*/ INIT_UVB_MAP.put(',', new Byte((byte)17)); } public static final HashMap<Character,Byte> UVB_MAP=INIT_UVB_MAP; /* * 0 |0 |0 |0 |0 |0 |0 |0 * []|+-|<>|.,|00|00|00|sign */ }
Add UVB mapping to constants
Add UVB mapping to constants
Java
apache-2.0
rlee287/jrainbuck
java
## Code Before: package io.github.rlee287.jrainbuck.constants; public class SwitchList { //public static final int CLASSIC_SIZE=30000; public static final String[] LIST_SWITCHES={"-file","-input","-output"}; /* 0|file MANDATORY * 1|stdin OPTIONAL * 2|stdout OPTIONAL */ } ## Instruction: Add UVB mapping to constants ## Code After: package io.github.rlee287.jrainbuck.constants; import java.util.HashMap; public class Constants { //public static final int CLASSIC_SIZE=30000; public static final String[] LIST_SWITCHES={"-file","-input","-output"}; /* 0|file MANDATORY * 1|stdin OPTIONAL * 2|stdout OPTIONAL */ public static final Character[] ALLOWED_CHAR={'[',']','+','-','<','>','.',','}; private static HashMap<Character, Byte> INIT_UVB_MAP= new HashMap <Character,Byte>(); static { /* JUMP_FORWARD_ZERO 0b1000 0001*/ INIT_UVB_MAP.put('[', new Byte((byte)-127)); /* JUMP_BACKWARD_NONZERO 0b1000 0000*/ INIT_UVB_MAP.put(']', new Byte((byte)-128)); /* ARRAY_INCREMENT 0b0100 0001*/ INIT_UVB_MAP.put('+', new Byte((byte)65)); /* ARRAY_DECREMENT 0b0100 0000*/ INIT_UVB_MAP.put('-', new Byte((byte)64)); /* POINTER_LEFT 0b0010 0000*/ INIT_UVB_MAP.put('<', new Byte((byte)32)); /* POINTER_RIGHT 0b0010 0001*/ INIT_UVB_MAP.put('>', new Byte((byte)33)); /* STDOUT 0b0001 0000*/ INIT_UVB_MAP.put('.', new Byte((byte)16)); /* STDIN 0b0001 0001*/ INIT_UVB_MAP.put(',', new Byte((byte)17)); } public static final HashMap<Character,Byte> UVB_MAP=INIT_UVB_MAP; /* * 0 |0 |0 |0 |0 |0 |0 |0 * []|+-|<>|.,|00|00|00|sign */ }
# ... existing code ... package io.github.rlee287.jrainbuck.constants; import java.util.HashMap; public class Constants { //public static final int CLASSIC_SIZE=30000; public static final String[] LIST_SWITCHES={"-file","-input","-output"}; /* 0|file MANDATORY # ... modified code ... * 1|stdin OPTIONAL * 2|stdout OPTIONAL */ public static final Character[] ALLOWED_CHAR={'[',']','+','-','<','>','.',','}; private static HashMap<Character, Byte> INIT_UVB_MAP= new HashMap <Character,Byte>(); static { /* JUMP_FORWARD_ZERO 0b1000 0001*/ INIT_UVB_MAP.put('[', new Byte((byte)-127)); /* JUMP_BACKWARD_NONZERO 0b1000 0000*/ INIT_UVB_MAP.put(']', new Byte((byte)-128)); /* ARRAY_INCREMENT 0b0100 0001*/ INIT_UVB_MAP.put('+', new Byte((byte)65)); /* ARRAY_DECREMENT 0b0100 0000*/ INIT_UVB_MAP.put('-', new Byte((byte)64)); /* POINTER_LEFT 0b0010 0000*/ INIT_UVB_MAP.put('<', new Byte((byte)32)); /* POINTER_RIGHT 0b0010 0001*/ INIT_UVB_MAP.put('>', new Byte((byte)33)); /* STDOUT 0b0001 0000*/ INIT_UVB_MAP.put('.', new Byte((byte)16)); /* STDIN 0b0001 0001*/ INIT_UVB_MAP.put(',', new Byte((byte)17)); } public static final HashMap<Character,Byte> UVB_MAP=INIT_UVB_MAP; /* * 0 |0 |0 |0 |0 |0 |0 |0 * []|+-|<>|.,|00|00|00|sign */ } # ... rest of the code ...
1cb261bce94e7eb5bccccd282f938074e758f5bc
setup.py
setup.py
import setuptools _metadata = {} with open("src/txkube/_metadata.py") as f: exec(f.read(), _metadata) setuptools.setup( name="txkube", version=_metadata["version_string"], description="A Twisted-based Kubernetes client.", author="txkube Developers", url="https://github.com/leastauthority.com/txkube", license="MIT", package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), include_package_data=True, zip_safe=False, install_requires=[ "zope.interface", "attrs", "pyrsistent", "incremental", # See https://github.com/twisted/treq/issues/167 # And https://twistedmatrix.com/trac/ticket/9032 "twisted[tls]!=17.1.0", "pem", "eliot", "python-dateutil", "pykube", "treq", "klein", ], extras_require={ "dev": [ "testtools", "hypothesis", "eliot-tree>=17.0.0", ], }, )
import setuptools _metadata = {} with open("src/txkube/_metadata.py") as f: exec(f.read(), _metadata) with open("README.rst") as f: _metadata["description"] = f.read() setuptools.setup( name="txkube", version=_metadata["version_string"], description="A Twisted-based Kubernetes client.", long_description=_metadata["description"], author="txkube Developers", url="https://github.com/leastauthority.com/txkube", license="MIT", package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), include_package_data=True, zip_safe=False, install_requires=[ "zope.interface", "attrs", "pyrsistent", "incremental", # See https://github.com/twisted/treq/issues/167 # And https://twistedmatrix.com/trac/ticket/9032 "twisted[tls]!=17.1.0", "pem", "eliot", "python-dateutil", "pykube", "treq", "klein", ], extras_require={ "dev": [ "testtools", "hypothesis", "eliot-tree>=17.0.0", ], }, )
Add the README as the long description.
Add the README as the long description.
Python
mit
LeastAuthority/txkube
python
## Code Before: import setuptools _metadata = {} with open("src/txkube/_metadata.py") as f: exec(f.read(), _metadata) setuptools.setup( name="txkube", version=_metadata["version_string"], description="A Twisted-based Kubernetes client.", author="txkube Developers", url="https://github.com/leastauthority.com/txkube", license="MIT", package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), include_package_data=True, zip_safe=False, install_requires=[ "zope.interface", "attrs", "pyrsistent", "incremental", # See https://github.com/twisted/treq/issues/167 # And https://twistedmatrix.com/trac/ticket/9032 "twisted[tls]!=17.1.0", "pem", "eliot", "python-dateutil", "pykube", "treq", "klein", ], extras_require={ "dev": [ "testtools", "hypothesis", "eliot-tree>=17.0.0", ], }, ) ## Instruction: Add the README as the long description. ## Code After: import setuptools _metadata = {} with open("src/txkube/_metadata.py") as f: exec(f.read(), _metadata) with open("README.rst") as f: _metadata["description"] = f.read() setuptools.setup( name="txkube", version=_metadata["version_string"], description="A Twisted-based Kubernetes client.", long_description=_metadata["description"], author="txkube Developers", url="https://github.com/leastauthority.com/txkube", license="MIT", package_dir={"": "src"}, packages=setuptools.find_packages(where="src"), include_package_data=True, zip_safe=False, install_requires=[ "zope.interface", "attrs", "pyrsistent", "incremental", # See https://github.com/twisted/treq/issues/167 # And https://twistedmatrix.com/trac/ticket/9032 "twisted[tls]!=17.1.0", "pem", "eliot", "python-dateutil", "pykube", "treq", "klein", ], extras_require={ "dev": [ "testtools", "hypothesis", "eliot-tree>=17.0.0", ], }, )
// ... existing code ... _metadata = {} with open("src/txkube/_metadata.py") as f: exec(f.read(), _metadata) with open("README.rst") as f: _metadata["description"] = f.read() setuptools.setup( name="txkube", version=_metadata["version_string"], description="A Twisted-based Kubernetes client.", long_description=_metadata["description"], author="txkube Developers", url="https://github.com/leastauthority.com/txkube", license="MIT", // ... rest of the code ...
8d5a7fe5401126873fbd23990610e916d37482f7
testframework/hu/adamsan/selenium/framework/pages/LoginPage.java
testframework/hu/adamsan/selenium/framework/pages/LoginPage.java
package hu.adamsan.selenium.framework.pages; import org.openqa.selenium.support.ui.WebDriverWait; import hu.adamsan.selenium.framework.selenium.Driver; public class LoginPage { private static final String LOGIN_PAGE = Driver.BASE_ADDRESS + "/wp-login.php"; public static void goTo() { Driver.INSTANCE.navigate().to(LOGIN_PAGE); WebDriverWait wait = new WebDriverWait(Driver.INSTANCE, 5); wait.until(driver -> { return driver.switchTo().activeElement().getAttribute("id").equals("user_login"); }); } public static LoginCommand loginAs(String username) { return new LoginCommand(username); } }
package hu.adamsan.selenium.framework.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.WebDriverWait; import hu.adamsan.selenium.framework.selenium.Driver; public class LoginPage { private static final String LOGIN_PAGE = Driver.BASE_ADDRESS + "/wp-login.php"; public static void goTo() { Driver.INSTANCE.navigate().to(LOGIN_PAGE); WebDriverWait wait = new WebDriverWait(Driver.INSTANCE, 5); com.google.common.base.Predicate<WebDriver> p = driver -> { return driver.switchTo().activeElement().getAttribute("id").equals("user_login"); }; wait.until(p); } public static LoginCommand loginAs(String username) { return new LoginCommand(username); } }
Fix previously not occurring bug:The method until(Predicate<WebDriver>) is ambiguous for the type WebDriverWait
Fix previously not occurring bug:The method until(Predicate<WebDriver>) is ambiguous for the type WebDriverWait
Java
mit
adamsan/WordpressBlackBoxTesting
java
## Code Before: package hu.adamsan.selenium.framework.pages; import org.openqa.selenium.support.ui.WebDriverWait; import hu.adamsan.selenium.framework.selenium.Driver; public class LoginPage { private static final String LOGIN_PAGE = Driver.BASE_ADDRESS + "/wp-login.php"; public static void goTo() { Driver.INSTANCE.navigate().to(LOGIN_PAGE); WebDriverWait wait = new WebDriverWait(Driver.INSTANCE, 5); wait.until(driver -> { return driver.switchTo().activeElement().getAttribute("id").equals("user_login"); }); } public static LoginCommand loginAs(String username) { return new LoginCommand(username); } } ## Instruction: Fix previously not occurring bug:The method until(Predicate<WebDriver>) is ambiguous for the type WebDriverWait ## Code After: package hu.adamsan.selenium.framework.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.WebDriverWait; import hu.adamsan.selenium.framework.selenium.Driver; public class LoginPage { private static final String LOGIN_PAGE = Driver.BASE_ADDRESS + "/wp-login.php"; public static void goTo() { Driver.INSTANCE.navigate().to(LOGIN_PAGE); WebDriverWait wait = new WebDriverWait(Driver.INSTANCE, 5); com.google.common.base.Predicate<WebDriver> p = driver -> { return driver.switchTo().activeElement().getAttribute("id").equals("user_login"); }; wait.until(p); } public static LoginCommand loginAs(String username) { return new LoginCommand(username); } }
# ... existing code ... package hu.adamsan.selenium.framework.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.WebDriverWait; import hu.adamsan.selenium.framework.selenium.Driver; # ... modified code ... public static void goTo() { Driver.INSTANCE.navigate().to(LOGIN_PAGE); WebDriverWait wait = new WebDriverWait(Driver.INSTANCE, 5); com.google.common.base.Predicate<WebDriver> p = driver -> { return driver.switchTo().activeElement().getAttribute("id").equals("user_login"); }; wait.until(p); } # ... rest of the code ...
0de213c88dcee2db8f8cd416ff928e6018329e68
passwd_change.py
passwd_change.py
import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 5: keys_file = _args[1] target_file = _args[2] result_file = _args[3] log_file = _args[4] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open(log_file, 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or \ line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('==================================================') print('python passwd_change.py keys passwd passwd_new log') print('==================================================')
import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 8: keys_file = _args[1] passwd_orig = _args[2] passwd_new = _args[3] passwd_log = _args[4] shadow_orig = _args[5] shadow_new = _args[6] shadow_log = _args[7] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(passwd_orig, 'r') as po: passwd_lines = po.readlines() passwd_log = open(passwd_log, 'w') passwd_new_keys = [] with open(passwd_new, 'w') as pn: for line in passwd_lines: if line.split(':')[0] in keys or \ line.split(':')[3] != '12': pn.write(line) passwd_new_keys.append(line.split(':')[0]) else: passwd_log.write(line) passwd_log.close() with open(shadow_orig, 'r') as so: shadow_lines = so.readlines() shadow_log = open(shadow_log, 'w') with open(shadow_new, 'w') as sn: for line in shadow_lines: if line.split(':')[0] in passwd_new_keys: sn.write(line) else: shadow_log.write(line) shadow_log.close() except Exception as e: print(str(e)) sys.exit() else: print('==================================================') print('python passwd_change.py keys passwd passwd_new passwd_log' + ' shadow shadow_new shadow_log') print('==================================================')
Add shadow changing support according to our new passwd.
Add shadow changing support according to our new passwd.
Python
mit
maxsocl/oldmailer
python
## Code Before: import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 5: keys_file = _args[1] target_file = _args[2] result_file = _args[3] log_file = _args[4] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open(log_file, 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or \ line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('==================================================') print('python passwd_change.py keys passwd passwd_new log') print('==================================================') ## Instruction: Add shadow changing support according to our new passwd. ## Code After: import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 8: keys_file = _args[1] passwd_orig = _args[2] passwd_new = _args[3] passwd_log = _args[4] shadow_orig = _args[5] shadow_new = _args[6] shadow_log = _args[7] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(passwd_orig, 'r') as po: passwd_lines = po.readlines() passwd_log = open(passwd_log, 'w') passwd_new_keys = [] with open(passwd_new, 'w') as pn: for line in passwd_lines: if line.split(':')[0] in keys or \ line.split(':')[3] != '12': pn.write(line) passwd_new_keys.append(line.split(':')[0]) else: passwd_log.write(line) passwd_log.close() with open(shadow_orig, 'r') as so: shadow_lines = so.readlines() shadow_log = open(shadow_log, 'w') with open(shadow_new, 'w') as sn: for line in shadow_lines: if line.split(':')[0] in passwd_new_keys: sn.write(line) else: shadow_log.write(line) shadow_log.close() except Exception as e: print(str(e)) sys.exit() else: print('==================================================') print('python passwd_change.py keys passwd passwd_new passwd_log' + ' shadow shadow_new shadow_log') print('==================================================')
# ... existing code ... _args = sys.argv if __name__ == "__main__": if len(_args) == 8: keys_file = _args[1] passwd_orig = _args[2] passwd_new = _args[3] passwd_log = _args[4] shadow_orig = _args[5] shadow_new = _args[6] shadow_log = _args[7] try: with open(keys_file, 'r') as k: # ... modified code ... keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(passwd_orig, 'r') as po: passwd_lines = po.readlines() passwd_log = open(passwd_log, 'w') passwd_new_keys = [] with open(passwd_new, 'w') as pn: for line in passwd_lines: if line.split(':')[0] in keys or \ line.split(':')[3] != '12': pn.write(line) passwd_new_keys.append(line.split(':')[0]) else: passwd_log.write(line) passwd_log.close() with open(shadow_orig, 'r') as so: shadow_lines = so.readlines() shadow_log = open(shadow_log, 'w') with open(shadow_new, 'w') as sn: for line in shadow_lines: if line.split(':')[0] in passwd_new_keys: sn.write(line) else: shadow_log.write(line) shadow_log.close() except Exception as e: print(str(e)) ... sys.exit() else: print('==================================================') print('python passwd_change.py keys passwd passwd_new passwd_log' + ' shadow shadow_new shadow_log') print('==================================================') # ... rest of the code ...
9149bd2c3a9a443367b31bc99c55b69cb60e920b
IRKit/IRKit/IRHTTPJSONOperation.h
IRKit/IRKit/IRHTTPJSONOperation.h
// // IRHTTPJSONOperation.h // IRKit // // Created by Masakazu Ohtsuka on 2013/12/02. // // #import "ISHTTPOperation.h" @interface IRHTTPJSONOperation : ISHTTPOperation @end
// // IRHTTPJSONOperation.h // IRKit // // Created by Masakazu Ohtsuka on 2013/12/02. // // // #import "ISHTTPOperation.h" @import ISHTTPOperation; @interface IRHTTPJSONOperation : ISHTTPOperation @end
Fix again error: include of non-modular header inside framework module
Fix again error: include of non-modular header inside framework module
C
mit
irkit/ios-sdk
c
## Code Before: // // IRHTTPJSONOperation.h // IRKit // // Created by Masakazu Ohtsuka on 2013/12/02. // // #import "ISHTTPOperation.h" @interface IRHTTPJSONOperation : ISHTTPOperation @end ## Instruction: Fix again error: include of non-modular header inside framework module ## Code After: // // IRHTTPJSONOperation.h // IRKit // // Created by Masakazu Ohtsuka on 2013/12/02. // // // #import "ISHTTPOperation.h" @import ISHTTPOperation; @interface IRHTTPJSONOperation : ISHTTPOperation @end
# ... existing code ... // // // #import "ISHTTPOperation.h" @import ISHTTPOperation; @interface IRHTTPJSONOperation : ISHTTPOperation @end # ... rest of the code ...
d7a8cf2b5a26acdb8348ac8b37a82b356d35ba25
workcraft/WorkcraftCore/src/org/workcraft/gui/controls/FlatCellRenderer.java
workcraft/WorkcraftCore/src/org/workcraft/gui/controls/FlatCellRenderer.java
package org.workcraft.gui.controls; import org.workcraft.utils.GuiUtils; import javax.swing.*; import javax.swing.table.TableCellRenderer; import java.awt.*; @SuppressWarnings("serial") public class FlatCellRenderer extends JLabel implements TableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value == null) { setText(""); setOpaque(true); } else { String text = value.toString(); setText(text); setFont(table.getFont()); setOpaque(text.isEmpty()); } setBorder(GuiUtils.getTableCellBorder()); return this; } }
package org.workcraft.gui.controls; import org.workcraft.utils.GuiUtils; import javax.swing.*; import javax.swing.table.TableCellRenderer; import java.awt.*; public class FlatCellRenderer extends JLabel implements TableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value == null) { setText(""); setOpaque(true); } else { String text = value.toString(); setText(text); setFont(table.getFont()); setOpaque(text.isEmpty()); } setBorder(GuiUtils.getTableCellBorder()); return this; } }
Remove suppression for serialisation warning
Remove suppression for serialisation warning
Java
mit
danilovesky/workcraft,workcraft/workcraft,danilovesky/workcraft,tuura/workcraft,danilovesky/workcraft,workcraft/workcraft,workcraft/workcraft,workcraft/workcraft,tuura/workcraft,danilovesky/workcraft,tuura/workcraft
java
## Code Before: package org.workcraft.gui.controls; import org.workcraft.utils.GuiUtils; import javax.swing.*; import javax.swing.table.TableCellRenderer; import java.awt.*; @SuppressWarnings("serial") public class FlatCellRenderer extends JLabel implements TableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value == null) { setText(""); setOpaque(true); } else { String text = value.toString(); setText(text); setFont(table.getFont()); setOpaque(text.isEmpty()); } setBorder(GuiUtils.getTableCellBorder()); return this; } } ## Instruction: Remove suppression for serialisation warning ## Code After: package org.workcraft.gui.controls; import org.workcraft.utils.GuiUtils; import javax.swing.*; import javax.swing.table.TableCellRenderer; import java.awt.*; public class FlatCellRenderer extends JLabel implements TableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (value == null) { setText(""); setOpaque(true); } else { String text = value.toString(); setText(text); setFont(table.getFont()); setOpaque(text.isEmpty()); } setBorder(GuiUtils.getTableCellBorder()); return this; } }
// ... existing code ... import javax.swing.table.TableCellRenderer; import java.awt.*; public class FlatCellRenderer extends JLabel implements TableCellRenderer { @Override // ... rest of the code ...
077016fbe6ee17c8eb3528b957b05eb4682b8d26
scrapi/processing/elastic_search.py
scrapi/processing/elastic_search.py
import json import logging from elasticsearch import Elasticsearch from scrapi import settings from scrapi.processing.base import BaseProcessor es = Elasticsearch( settings.ELASTIC_URI, request_timeout=settings.ELASTIC_TIMEOUT ) logging.getLogger('elasticsearch').setLevel(logging.WARN) logging.getLogger('elasticsearch.trace').setLevel(logging.WARN) logging.getLogger('urllib3').setLevel(logging.WARN) logging.getLogger('requests').setLevel(logging.WARN) es.cluster.health(wait_for_status='yellow') logger = logging.getLogger(__name__) class ElasticsearchProcessor(BaseProcessor): NAME = 'elasticsearch' def process_normalized(self, raw_doc, normalized): data = { key: value for key, value in normalized.attributes.items() if key in settings.FRONTEND_KEYS } normalized['dateUpdated'] = self.version_dateUpdated(normalized) es.index( body=data, refresh=True, index='share', doc_type=normalized['source'], id=normalized['id']['serviceID'], ) def version_dateUpdated(self, normalized): old_doc = es.get_source( index='share', doc_type=normalized['source'], id=normalized['id']['serviceID'], ignore=[404] ) logger.info(json.dumps(old_doc, indent=4)) return old_doc['dateUpdated'] if old_doc else normalized['dateUpdated']
import json import logging from elasticsearch import Elasticsearch from scrapi import settings from scrapi.processing.base import BaseProcessor es = Elasticsearch( settings.ELASTIC_URI, request_timeout=settings.ELASTIC_TIMEOUT ) logging.getLogger('elasticsearch').setLevel(logging.WARN) logging.getLogger('elasticsearch.trace').setLevel(logging.WARN) logging.getLogger('urllib3').setLevel(logging.WARN) logging.getLogger('requests').setLevel(logging.WARN) es.cluster.health(wait_for_status='yellow') logger = logging.getLogger(__name__) class ElasticsearchProcessor(BaseProcessor): NAME = 'elasticsearch' def process_normalized(self, raw_doc, normalized): data = { key: value for key, value in normalized.attributes.items() if key in settings.FRONTEND_KEYS } normalized['dateUpdated'] = self.version_dateUpdated(normalized) es.index( body=data, refresh=True, index='share', doc_type=normalized['source'], id=normalized['id']['serviceID'], ) def version_dateUpdated(self, normalized): try: old_doc = es.get_source( index='share', doc_type=normalized['source'], id=normalized['id']['serviceID'], ) except elasticsearch.IndexMissingException: return normalized['dateUpdated'] return old_doc['dateUpdated'] if old_doc else normalized['dateUpdated']
Handle 404s due to index not existing when doing versioning
Handle 404s due to index not existing when doing versioning
Python
apache-2.0
jeffreyliu3230/scrapi,ostwald/scrapi,felliott/scrapi,felliott/scrapi,fabianvf/scrapi,erinspace/scrapi,fabianvf/scrapi,erinspace/scrapi,mehanig/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,icereval/scrapi,alexgarciac/scrapi,CenterForOpenScience/scrapi
python
## Code Before: import json import logging from elasticsearch import Elasticsearch from scrapi import settings from scrapi.processing.base import BaseProcessor es = Elasticsearch( settings.ELASTIC_URI, request_timeout=settings.ELASTIC_TIMEOUT ) logging.getLogger('elasticsearch').setLevel(logging.WARN) logging.getLogger('elasticsearch.trace').setLevel(logging.WARN) logging.getLogger('urllib3').setLevel(logging.WARN) logging.getLogger('requests').setLevel(logging.WARN) es.cluster.health(wait_for_status='yellow') logger = logging.getLogger(__name__) class ElasticsearchProcessor(BaseProcessor): NAME = 'elasticsearch' def process_normalized(self, raw_doc, normalized): data = { key: value for key, value in normalized.attributes.items() if key in settings.FRONTEND_KEYS } normalized['dateUpdated'] = self.version_dateUpdated(normalized) es.index( body=data, refresh=True, index='share', doc_type=normalized['source'], id=normalized['id']['serviceID'], ) def version_dateUpdated(self, normalized): old_doc = es.get_source( index='share', doc_type=normalized['source'], id=normalized['id']['serviceID'], ignore=[404] ) logger.info(json.dumps(old_doc, indent=4)) return old_doc['dateUpdated'] if old_doc else normalized['dateUpdated'] ## Instruction: Handle 404s due to index not existing when doing versioning ## Code After: import json import logging from elasticsearch import Elasticsearch from scrapi import settings from scrapi.processing.base import BaseProcessor es = Elasticsearch( settings.ELASTIC_URI, request_timeout=settings.ELASTIC_TIMEOUT ) logging.getLogger('elasticsearch').setLevel(logging.WARN) logging.getLogger('elasticsearch.trace').setLevel(logging.WARN) logging.getLogger('urllib3').setLevel(logging.WARN) logging.getLogger('requests').setLevel(logging.WARN) es.cluster.health(wait_for_status='yellow') logger = logging.getLogger(__name__) class ElasticsearchProcessor(BaseProcessor): NAME = 'elasticsearch' def process_normalized(self, raw_doc, normalized): data = { key: value for key, value in normalized.attributes.items() if key in settings.FRONTEND_KEYS } normalized['dateUpdated'] = self.version_dateUpdated(normalized) es.index( body=data, refresh=True, index='share', doc_type=normalized['source'], id=normalized['id']['serviceID'], ) def version_dateUpdated(self, normalized): try: old_doc = es.get_source( index='share', doc_type=normalized['source'], id=normalized['id']['serviceID'], ) except elasticsearch.IndexMissingException: return normalized['dateUpdated'] return old_doc['dateUpdated'] if old_doc else normalized['dateUpdated']
// ... existing code ... ) def version_dateUpdated(self, normalized): try: old_doc = es.get_source( index='share', doc_type=normalized['source'], id=normalized['id']['serviceID'], ) except elasticsearch.IndexMissingException: return normalized['dateUpdated'] return old_doc['dateUpdated'] if old_doc else normalized['dateUpdated'] // ... rest of the code ...
f408c35b1716e255634a2a2e9b3366b47eb7b3d7
test/Analysis/misc-driver.c
test/Analysis/misc-driver.c
// RUN: %clang -### --analyze %s 2>&1 | FileCheck %s // CHECK: -D__clang_analyzer__
// RUN: %clang --analyze %s #ifndef __clang_analyzer__ #error __clang_analyzer__ not defined #endif
Revert "[static analyzer][test] Test directly that driver sets D__clang_analyzer__"
Revert "[static analyzer][test] Test directly that driver sets D__clang_analyzer__" This reverts commit c7541903d72765a38808e9973572a8d50c9d94fb. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@372685 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang
c
## Code Before: // RUN: %clang -### --analyze %s 2>&1 | FileCheck %s // CHECK: -D__clang_analyzer__ ## Instruction: Revert "[static analyzer][test] Test directly that driver sets D__clang_analyzer__" This reverts commit c7541903d72765a38808e9973572a8d50c9d94fb. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@372685 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: // RUN: %clang --analyze %s #ifndef __clang_analyzer__ #error __clang_analyzer__ not defined #endif
# ... existing code ... // RUN: %clang --analyze %s #ifndef __clang_analyzer__ #error __clang_analyzer__ not defined #endif # ... rest of the code ...
fd0e81b5426685646310bd068792647d3b154b7e
src/backupBasic/backup/Main.java
src/backupBasic/backup/Main.java
package backupBasic.backup; /*(c)2016, Tobias Hotz * Further Information can be found in Info.txt */ import backupBasic.util.i18n; import javax.swing.*; import java.awt.*; import java.util.logging.Logger; /** * @author Tobias Hotz */ public class Main implements Thread.UncaughtExceptionHandler { private static final Logger logger = i18n.getLogger(Main.class); /** * Verwaltet das Logging-System und gibt dann an den ArgParser ab */ public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler(new Main()); i18n.initLogging(); ArgParser.parseArgs(args); } @Override public void uncaughtException(Thread t, Throwable e) { logger.severe(i18n.translate("UncaughtException")+ "\t Stacktrace:"); e.printStackTrace(); if(!GraphicsEnvironment.isHeadless()) { JOptionPane.showMessageDialog(null, i18n.translate("UncaughtException") + "\n" + i18n.translate("Error") + ": "+ e +"\n" + i18n.translate("Details"), "ERROR", JOptionPane.ERROR_MESSAGE); } System.exit(-1); } }
package backupBasic.backup; /*(c)2016, Tobias Hotz * Further Information can be found in Info.txt */ import backupBasic.util.i18n; import javax.swing.*; import java.awt.*; import java.util.logging.Logger; /** * @author Tobias Hotz */ public class Main implements Thread.UncaughtExceptionHandler { private static final Logger logger = i18n.getLogger(Main.class); /** * Verwaltet das Logging-System und gibt dann an den ArgParser ab */ public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler(new Main()); i18n.initLogging(); ArgParser.parseArgs(args); } @Override public void uncaughtException(Thread t, Throwable e) { try { logger.severe(i18n.translate("UncaughtException")+ "\t Stacktrace:"); e.printStackTrace(); if(!GraphicsEnvironment.isHeadless()) JOptionPane.showMessageDialog(null, i18n.translate("UncaughtException") + "\n" + i18n.translate("Error") + ": " + e + "\n" + i18n.translate("Details"), "ERROR", JOptionPane.ERROR_MESSAGE); } catch(Exception e2) { e.printStackTrace(); System.err.println("Errors while printing Error:"); e2.printStackTrace(); if(!GraphicsEnvironment.isHeadless()) JOptionPane.showMessageDialog(null, "An fatal error occurred, and the program crashed." + "\nIn addition to that, it failed to translate this Message", "ERROR", JOptionPane.ERROR_MESSAGE); } System.exit(-1); } }
Fix crash when showing crash information
Fix crash when showing crash information
Java
mit
ichttt/BackupBasic
java
## Code Before: package backupBasic.backup; /*(c)2016, Tobias Hotz * Further Information can be found in Info.txt */ import backupBasic.util.i18n; import javax.swing.*; import java.awt.*; import java.util.logging.Logger; /** * @author Tobias Hotz */ public class Main implements Thread.UncaughtExceptionHandler { private static final Logger logger = i18n.getLogger(Main.class); /** * Verwaltet das Logging-System und gibt dann an den ArgParser ab */ public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler(new Main()); i18n.initLogging(); ArgParser.parseArgs(args); } @Override public void uncaughtException(Thread t, Throwable e) { logger.severe(i18n.translate("UncaughtException")+ "\t Stacktrace:"); e.printStackTrace(); if(!GraphicsEnvironment.isHeadless()) { JOptionPane.showMessageDialog(null, i18n.translate("UncaughtException") + "\n" + i18n.translate("Error") + ": "+ e +"\n" + i18n.translate("Details"), "ERROR", JOptionPane.ERROR_MESSAGE); } System.exit(-1); } } ## Instruction: Fix crash when showing crash information ## Code After: package backupBasic.backup; /*(c)2016, Tobias Hotz * Further Information can be found in Info.txt */ import backupBasic.util.i18n; import javax.swing.*; import java.awt.*; import java.util.logging.Logger; /** * @author Tobias Hotz */ public class Main implements Thread.UncaughtExceptionHandler { private static final Logger logger = i18n.getLogger(Main.class); /** * Verwaltet das Logging-System und gibt dann an den ArgParser ab */ public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler(new Main()); i18n.initLogging(); ArgParser.parseArgs(args); } @Override public void uncaughtException(Thread t, Throwable e) { try { logger.severe(i18n.translate("UncaughtException")+ "\t Stacktrace:"); e.printStackTrace(); if(!GraphicsEnvironment.isHeadless()) JOptionPane.showMessageDialog(null, i18n.translate("UncaughtException") + "\n" + i18n.translate("Error") + ": " + e + "\n" + i18n.translate("Details"), "ERROR", JOptionPane.ERROR_MESSAGE); } catch(Exception e2) { e.printStackTrace(); System.err.println("Errors while printing Error:"); e2.printStackTrace(); if(!GraphicsEnvironment.isHeadless()) JOptionPane.showMessageDialog(null, "An fatal error occurred, and the program crashed." + "\nIn addition to that, it failed to translate this Message", "ERROR", JOptionPane.ERROR_MESSAGE); } System.exit(-1); } }
... * @author Tobias Hotz */ public class Main implements Thread.UncaughtExceptionHandler { private static final Logger logger = i18n.getLogger(Main.class); /** * Verwaltet das Logging-System und gibt dann an den ArgParser ab */ ... @Override public void uncaughtException(Thread t, Throwable e) { try { logger.severe(i18n.translate("UncaughtException")+ "\t Stacktrace:"); e.printStackTrace(); if(!GraphicsEnvironment.isHeadless()) JOptionPane.showMessageDialog(null, i18n.translate("UncaughtException") + "\n" + i18n.translate("Error") + ": " + e + "\n" + i18n.translate("Details"), "ERROR", JOptionPane.ERROR_MESSAGE); } catch(Exception e2) { e.printStackTrace(); System.err.println("Errors while printing Error:"); e2.printStackTrace(); if(!GraphicsEnvironment.isHeadless()) JOptionPane.showMessageDialog(null, "An fatal error occurred, and the program crashed." + "\nIn addition to that, it failed to translate this Message", "ERROR", JOptionPane.ERROR_MESSAGE); } System.exit(-1); } } ...
b7cc6302904e7adbc21edf65a797ded421b35d9a
setup.py
setup.py
from setuptools import setup, find_packages setup( name='pyseeyou', version='0.3.0', description='A Python Parser for the ICU MessageFormat.', author='Siame Rafiq', author_email='[email protected]', packages=find_packages(exclude=['tests']), install_requires=['parsimonious', 'toolz'], tests_require=['pytest'], url='https://github.com/rolepoint/pyseeyou', download_url='https://github.com/rolepoint/pyseeyou/archive/v0.3.0.tar.gz', keywords='python i18n messageformat python3 python2' )
from setuptools import setup, find_packages setup( name='pyseeyou', version='0.3.0', description='A Python Parser for the ICU MessageFormat.', author='Siame Rafiq', author_email='[email protected]', packages=find_packages(exclude=['tests']), install_requires=['parsimonious', 'toolz', 'future'], tests_require=['pytest'], url='https://github.com/rolepoint/pyseeyou', download_url='https://github.com/rolepoint/pyseeyou/archive/v0.3.0.tar.gz', keywords='python i18n messageformat python3 python2' )
Add future as required lib for pypi install
Add future as required lib for pypi install
Python
mit
rolepoint/pyseeyou
python
## Code Before: from setuptools import setup, find_packages setup( name='pyseeyou', version='0.3.0', description='A Python Parser for the ICU MessageFormat.', author='Siame Rafiq', author_email='[email protected]', packages=find_packages(exclude=['tests']), install_requires=['parsimonious', 'toolz'], tests_require=['pytest'], url='https://github.com/rolepoint/pyseeyou', download_url='https://github.com/rolepoint/pyseeyou/archive/v0.3.0.tar.gz', keywords='python i18n messageformat python3 python2' ) ## Instruction: Add future as required lib for pypi install ## Code After: from setuptools import setup, find_packages setup( name='pyseeyou', version='0.3.0', description='A Python Parser for the ICU MessageFormat.', author='Siame Rafiq', author_email='[email protected]', packages=find_packages(exclude=['tests']), install_requires=['parsimonious', 'toolz', 'future'], tests_require=['pytest'], url='https://github.com/rolepoint/pyseeyou', download_url='https://github.com/rolepoint/pyseeyou/archive/v0.3.0.tar.gz', keywords='python i18n messageformat python3 python2' )
... author='Siame Rafiq', author_email='[email protected]', packages=find_packages(exclude=['tests']), install_requires=['parsimonious', 'toolz', 'future'], tests_require=['pytest'], url='https://github.com/rolepoint/pyseeyou', download_url='https://github.com/rolepoint/pyseeyou/archive/v0.3.0.tar.gz', ...
8e4d77636a9846296225ddbfab872be4c7486261
dask_distance/_pycompat.py
dask_distance/_pycompat.py
try: irange = xrange except NameError: irange = range
try: irange = xrange except NameError: irange = range try: from itertools import izip except ImportError: izip = zip
Add izip for Python 2/3 compatibility
Add izip for Python 2/3 compatibility Simply use `izip` from `itertools` on Python 2 and alias `izip` as `zip` on Python 3. This way an iterable form of `zip` remains available on both Python 2 and Python 3 that is named `izip`. Should help avoid having the performance of the two implementations from diverging too far.
Python
bsd-3-clause
jakirkham/dask-distance
python
## Code Before: try: irange = xrange except NameError: irange = range ## Instruction: Add izip for Python 2/3 compatibility Simply use `izip` from `itertools` on Python 2 and alias `izip` as `zip` on Python 3. This way an iterable form of `zip` remains available on both Python 2 and Python 3 that is named `izip`. Should help avoid having the performance of the two implementations from diverging too far. ## Code After: try: irange = xrange except NameError: irange = range try: from itertools import izip except ImportError: izip = zip
# ... existing code ... irange = xrange except NameError: irange = range try: from itertools import izip except ImportError: izip = zip # ... rest of the code ...
36c43be6f365107373e93138c189b17274916269
src/main/java/org/hummingbirdlang/types/ClassType.java
src/main/java/org/hummingbirdlang/types/ClassType.java
package org.hummingbirdlang.types; public class ClassType extends CompositeType { private Type superClass; }
package org.hummingbirdlang.types; public class ClassType extends CompositeType { private String name; private Type superClass; public ClassType(String name, Type superClass) { this.name = name; this.superClass = superClass; } }
Add name and constructor to class type
Add name and constructor to class type
Java
bsd-3-clause
dirk/hummingbird2,dirk/hummingbird2,dirk/hummingbird2
java
## Code Before: package org.hummingbirdlang.types; public class ClassType extends CompositeType { private Type superClass; } ## Instruction: Add name and constructor to class type ## Code After: package org.hummingbirdlang.types; public class ClassType extends CompositeType { private String name; private Type superClass; public ClassType(String name, Type superClass) { this.name = name; this.superClass = superClass; } }
... package org.hummingbirdlang.types; public class ClassType extends CompositeType { private String name; private Type superClass; public ClassType(String name, Type superClass) { this.name = name; this.superClass = superClass; } } ...
a06e6cc3c0b0440d3adedd1ccce78309d8fae9a9
feincms/module/page/extensions/navigationgroups.py
feincms/module/page/extensions/navigationgroups.py
from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms import extensions class Extension(extensions.Extension): ident = 'navigationgroups' groups = [ ('default', _('Default')), ('footer', _('Footer')), ] def handle_model(self): self.model.add_to_class( 'navigation_group', models.CharField( _('navigation group'), choices=self.groups, default=self.groups[0][0], max_length=20, db_index=True)) def handle_modeladmin(self, modeladmin): modeladmin.add_extension_options('navigation_group') modeladmin.extend_list('list_display', ['navigation_group']) modeladmin.extend_list('list_filter', ['navigation_group'])
from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms import extensions class Extension(extensions.Extension): ident = 'navigationgroups' groups = [ ('default', _('Default')), ('footer', _('Footer')), ] def handle_model(self): self.model.add_to_class( 'navigation_group', models.CharField( _('navigation group'), choices=self.groups, default=self.groups[0][0], max_length=20, blank=True, db_index=True)) def handle_modeladmin(self, modeladmin): modeladmin.add_extension_options('navigation_group') modeladmin.extend_list('list_display', ['navigation_group']) modeladmin.extend_list('list_filter', ['navigation_group'])
Allow navigationgroup to be blank
Allow navigationgroup to be blank
Python
bsd-3-clause
joshuajonah/feincms,feincms/feincms,joshuajonah/feincms,joshuajonah/feincms,feincms/feincms,joshuajonah/feincms,feincms/feincms,mjl/feincms,mjl/feincms,mjl/feincms
python
## Code Before: from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms import extensions class Extension(extensions.Extension): ident = 'navigationgroups' groups = [ ('default', _('Default')), ('footer', _('Footer')), ] def handle_model(self): self.model.add_to_class( 'navigation_group', models.CharField( _('navigation group'), choices=self.groups, default=self.groups[0][0], max_length=20, db_index=True)) def handle_modeladmin(self, modeladmin): modeladmin.add_extension_options('navigation_group') modeladmin.extend_list('list_display', ['navigation_group']) modeladmin.extend_list('list_filter', ['navigation_group']) ## Instruction: Allow navigationgroup to be blank ## Code After: from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms import extensions class Extension(extensions.Extension): ident = 'navigationgroups' groups = [ ('default', _('Default')), ('footer', _('Footer')), ] def handle_model(self): self.model.add_to_class( 'navigation_group', models.CharField( _('navigation group'), choices=self.groups, default=self.groups[0][0], max_length=20, blank=True, db_index=True)) def handle_modeladmin(self, modeladmin): modeladmin.add_extension_options('navigation_group') modeladmin.extend_list('list_display', ['navigation_group']) modeladmin.extend_list('list_filter', ['navigation_group'])
# ... existing code ... choices=self.groups, default=self.groups[0][0], max_length=20, blank=True, db_index=True)) def handle_modeladmin(self, modeladmin): # ... rest of the code ...
053a858efa46c9ab86363b271374ec02ad2af753
arch/powerpc/lib/code-patching.c
arch/powerpc/lib/code-patching.c
/* * Copyright 2008 Michael Ellerman, IBM Corporation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/kernel.h> #include <asm/code-patching.h> void patch_instruction(unsigned int *addr, unsigned int instr) { *addr = instr; asm ("dcbst 0, %0; sync; icbi 0,%0; sync; isync" : : "r" (addr)); } void patch_branch(unsigned int *addr, unsigned long target, int flags) { patch_instruction(addr, create_branch(addr, target, flags)); } unsigned int create_branch(const unsigned int *addr, unsigned long target, int flags) { unsigned int instruction; if (! (flags & BRANCH_ABSOLUTE)) target = target - (unsigned long)addr; /* Mask out the flags and target, so they don't step on each other. */ instruction = 0x48000000 | (flags & 0x3) | (target & 0x03FFFFFC); return instruction; }
/* * Copyright 2008 Michael Ellerman, IBM Corporation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/kernel.h> #include <asm/code-patching.h> void patch_instruction(unsigned int *addr, unsigned int instr) { *addr = instr; asm ("dcbst 0, %0; sync; icbi 0,%0; sync; isync" : : "r" (addr)); } void patch_branch(unsigned int *addr, unsigned long target, int flags) { patch_instruction(addr, create_branch(addr, target, flags)); } unsigned int create_branch(const unsigned int *addr, unsigned long target, int flags) { unsigned int instruction; long offset; offset = target; if (! (flags & BRANCH_ABSOLUTE)) offset = offset - (unsigned long)addr; /* Check we can represent the target in the instruction format */ if (offset < -0x2000000 || offset > 0x1fffffc || offset & 0x3) return 0; /* Mask out the flags and target, so they don't step on each other. */ instruction = 0x48000000 | (flags & 0x3) | (offset & 0x03FFFFFC); return instruction; }
Make create_branch() return errors if the branch target is too large
powerpc: Make create_branch() return errors if the branch target is too large If you pass a target value to create_branch() which is more than 32MB - 4, or - 32MB away from the branch site, then it's impossible to create an immediate branch. The current code doesn't check, which will lead to us creating a branch to somewhere else - which is bad. For code that cares to check we return 0, which is easy to check for, and for code that doesn't at least we'll be creating an illegal instruction, rather than a branch to some random address. Signed-off-by: Michael Ellerman <[email protected]> Acked-by: Kumar Gala <[email protected]> Signed-off-by: Paul Mackerras <[email protected]>
C
mit
KristFoundation/Programs,TeamVee-Kanas/android_kernel_samsung_kanas,KristFoundation/Programs,TeamVee-Kanas/android_kernel_samsung_kanas,TeamVee-Kanas/android_kernel_samsung_kanas,KristFoundation/Programs,TeamVee-Kanas/android_kernel_samsung_kanas,TeamVee-Kanas/android_kernel_samsung_kanas,KristFoundation/Programs,KristFoundation/Programs,KristFoundation/Programs
c
## Code Before: /* * Copyright 2008 Michael Ellerman, IBM Corporation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/kernel.h> #include <asm/code-patching.h> void patch_instruction(unsigned int *addr, unsigned int instr) { *addr = instr; asm ("dcbst 0, %0; sync; icbi 0,%0; sync; isync" : : "r" (addr)); } void patch_branch(unsigned int *addr, unsigned long target, int flags) { patch_instruction(addr, create_branch(addr, target, flags)); } unsigned int create_branch(const unsigned int *addr, unsigned long target, int flags) { unsigned int instruction; if (! (flags & BRANCH_ABSOLUTE)) target = target - (unsigned long)addr; /* Mask out the flags and target, so they don't step on each other. */ instruction = 0x48000000 | (flags & 0x3) | (target & 0x03FFFFFC); return instruction; } ## Instruction: powerpc: Make create_branch() return errors if the branch target is too large If you pass a target value to create_branch() which is more than 32MB - 4, or - 32MB away from the branch site, then it's impossible to create an immediate branch. The current code doesn't check, which will lead to us creating a branch to somewhere else - which is bad. For code that cares to check we return 0, which is easy to check for, and for code that doesn't at least we'll be creating an illegal instruction, rather than a branch to some random address. Signed-off-by: Michael Ellerman <[email protected]> Acked-by: Kumar Gala <[email protected]> Signed-off-by: Paul Mackerras <[email protected]> ## Code After: /* * Copyright 2008 Michael Ellerman, IBM Corporation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/kernel.h> #include <asm/code-patching.h> void patch_instruction(unsigned int *addr, unsigned int instr) { *addr = instr; asm ("dcbst 0, %0; sync; icbi 0,%0; sync; isync" : : "r" (addr)); } void patch_branch(unsigned int *addr, unsigned long target, int flags) { patch_instruction(addr, create_branch(addr, target, flags)); } unsigned int create_branch(const unsigned int *addr, unsigned long target, int flags) { unsigned int instruction; long offset; offset = target; if (! (flags & BRANCH_ABSOLUTE)) offset = offset - (unsigned long)addr; /* Check we can represent the target in the instruction format */ if (offset < -0x2000000 || offset > 0x1fffffc || offset & 0x3) return 0; /* Mask out the flags and target, so they don't step on each other. */ instruction = 0x48000000 | (flags & 0x3) | (offset & 0x03FFFFFC); return instruction; }
... unsigned long target, int flags) { unsigned int instruction; long offset; offset = target; if (! (flags & BRANCH_ABSOLUTE)) offset = offset - (unsigned long)addr; /* Check we can represent the target in the instruction format */ if (offset < -0x2000000 || offset > 0x1fffffc || offset & 0x3) return 0; /* Mask out the flags and target, so they don't step on each other. */ instruction = 0x48000000 | (flags & 0x3) | (offset & 0x03FFFFFC); return instruction; } ...
49a371728a2e9167494264e0c07c6dd90abec0ff
saleor/core/views.py
saleor/core/views.py
from django.template.response import TemplateResponse from ..product.utils import products_with_availability, products_with_details def home(request): products = Product.objects.get_available_products()[:6] products = products.prefetch_related('categories', 'images', 'variants__stock') return TemplateResponse( request, 'home.html', {'products': products, 'parent': None})
from django.template.response import TemplateResponse from ..product.utils import products_with_availability, products_with_details def home(request): products = products_with_details(request.user)[:6] products = products_with_availability( products, discounts=request.discounts, local_currency=request.currency) return TemplateResponse( request, 'home.html', {'products': products, 'parent': None})
Fix homepage after wrong rebase
Fix homepage after wrong rebase
Python
bsd-3-clause
jreigel/saleor,car3oon/saleor,HyperManTT/ECommerceSaleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,UITools/saleor,mociepka/saleor,car3oon/saleor,KenMutemi/saleor,jreigel/saleor,UITools/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor,itbabu/saleor,UITools/saleor,KenMutemi/saleor,mociepka/saleor,itbabu/saleor,maferelo/saleor,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,jreigel/saleor,itbabu/saleor,tfroehlich82/saleor,UITools/saleor,KenMutemi/saleor,car3oon/saleor,maferelo/saleor
python
## Code Before: from django.template.response import TemplateResponse from ..product.utils import products_with_availability, products_with_details def home(request): products = Product.objects.get_available_products()[:6] products = products.prefetch_related('categories', 'images', 'variants__stock') return TemplateResponse( request, 'home.html', {'products': products, 'parent': None}) ## Instruction: Fix homepage after wrong rebase ## Code After: from django.template.response import TemplateResponse from ..product.utils import products_with_availability, products_with_details def home(request): products = products_with_details(request.user)[:6] products = products_with_availability( products, discounts=request.discounts, local_currency=request.currency) return TemplateResponse( request, 'home.html', {'products': products, 'parent': None})
# ... existing code ... def home(request): products = products_with_details(request.user)[:6] products = products_with_availability( products, discounts=request.discounts, local_currency=request.currency) return TemplateResponse( request, 'home.html', {'products': products, 'parent': None}) # ... rest of the code ...