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
1c32b17bd4c85165f91fbb188b22471a296c6176
kajiki/i18n.py
kajiki/i18n.py
from __future__ import (absolute_import, division, print_function, unicode_literals) from .ir import TranslatableTextNode def gettext(s): return s def extract(fileobj, keywords, comment_tags, options): '''Babel entry point that extracts translation strings from XML templates. ''' from .xml_template import _Parser, _Compiler, expand doc = _Parser(filename='<string>', source=fileobj.read()).parse() expand(doc) compiler = _Compiler(filename='<string>', doc=doc, mode=options.get('mode', 'xml'), is_fragment=options.get('is_fragment', False)) ir = compiler.compile() for node in ir: if isinstance(node, TranslatableTextNode): if node.text.strip(): for line in node.text.split('\n'): yield (node.lineno, '_', line, [])
from __future__ import (absolute_import, division, print_function, unicode_literals) from .ir import TranslatableTextNode def gettext(s): return s def extract(fileobj, keywords, comment_tags, options): '''Babel entry point that extracts translation strings from XML templates. ''' from .xml_template import _Parser, _Compiler, expand source = fileobj.read() if isinstance(source, bytes): source = source.decode('utf-8') doc = _Parser(filename='<string>', source=source).parse() expand(doc) compiler = _Compiler(filename='<string>', doc=doc, mode=options.get('mode', 'xml'), is_fragment=options.get('is_fragment', False)) ir = compiler.compile() for node in ir: if isinstance(node, TranslatableTextNode): if node.text.strip(): for line in node.text.split('\n'): yield (node.lineno, '_', line, [])
Fix issue with message extractor on Py2
Fix issue with message extractor on Py2
Python
mit
ollyc/kajiki,ollyc/kajiki,ollyc/kajiki
python
## Code Before: from __future__ import (absolute_import, division, print_function, unicode_literals) from .ir import TranslatableTextNode def gettext(s): return s def extract(fileobj, keywords, comment_tags, options): '''Babel entry point that extracts translation strings from XML templates. ''' from .xml_template import _Parser, _Compiler, expand doc = _Parser(filename='<string>', source=fileobj.read()).parse() expand(doc) compiler = _Compiler(filename='<string>', doc=doc, mode=options.get('mode', 'xml'), is_fragment=options.get('is_fragment', False)) ir = compiler.compile() for node in ir: if isinstance(node, TranslatableTextNode): if node.text.strip(): for line in node.text.split('\n'): yield (node.lineno, '_', line, []) ## Instruction: Fix issue with message extractor on Py2 ## Code After: from __future__ import (absolute_import, division, print_function, unicode_literals) from .ir import TranslatableTextNode def gettext(s): return s def extract(fileobj, keywords, comment_tags, options): '''Babel entry point that extracts translation strings from XML templates. ''' from .xml_template import _Parser, _Compiler, expand source = fileobj.read() if isinstance(source, bytes): source = source.decode('utf-8') doc = _Parser(filename='<string>', source=source).parse() expand(doc) compiler = _Compiler(filename='<string>', doc=doc, mode=options.get('mode', 'xml'), is_fragment=options.get('is_fragment', False)) ir = compiler.compile() for node in ir: if isinstance(node, TranslatableTextNode): if node.text.strip(): for line in node.text.split('\n'): yield (node.lineno, '_', line, [])
... '''Babel entry point that extracts translation strings from XML templates. ''' from .xml_template import _Parser, _Compiler, expand source = fileobj.read() if isinstance(source, bytes): source = source.decode('utf-8') doc = _Parser(filename='<string>', source=source).parse() expand(doc) compiler = _Compiler(filename='<string>', doc=doc, mode=options.get('mode', 'xml'), ...
8b9454fdf9e54059edcc951f188c05cb0f34c0a4
lookup_isbn.py
lookup_isbn.py
import yaml from amazon.api import AmazonAPI class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_key_id'], self.config['aws_secret_key'], self.config['amazon_associate_tag'] ) def lookup(self, isbn): product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books") book = { 'title': product.title, 'image_url': product.large_image_url, 'sales_rank': int(product.sales_rank), 'price': product.price_and_currency[0], 'offer_url': product.offer_url, 'authors': product.authors, 'publisher': product.publisher, 'isbn': isbn, 'binding': product.binding, 'pages': product.pages, 'publication_date': product.publication_date, 'list_price': product.list_price[0] } return book book = Books('config.yml').lookup('9781449389734') print yaml.dump(book, default_flow_style = False)
import yaml import sys import os from amazon.api import AmazonAPI # Change to script directory os.chdir(os.path.dirname(sys.argv[0])) class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_key_id'], self.config['aws_secret_key'], self.config['amazon_associate_tag'] ) def lookup(self, isbn): product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books") book = { 'title': product.title, 'image_url': product.large_image_url, 'sales_rank': int(product.sales_rank), 'price': product.price_and_currency[0], 'offer_url': product.offer_url, 'authors': product.authors, 'publisher': product.publisher, 'isbn': isbn, 'binding': product.binding, 'pages': product.pages, 'publication_date': product.publication_date, 'list_price': product.list_price[0] } return book books = Books('config.yml') for isbn in sys.argv[1:]: book = books.lookup(isbn) with open('raw_data/{0}.yml'.format(isbn), 'w') as out: out.write(yaml.dump(book, default_flow_style = False))
Read commandline args as isbns
Read commandline args as isbns
Python
mit
sortelli/book_pivot,sortelli/book_pivot
python
## Code Before: import yaml from amazon.api import AmazonAPI class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_key_id'], self.config['aws_secret_key'], self.config['amazon_associate_tag'] ) def lookup(self, isbn): product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books") book = { 'title': product.title, 'image_url': product.large_image_url, 'sales_rank': int(product.sales_rank), 'price': product.price_and_currency[0], 'offer_url': product.offer_url, 'authors': product.authors, 'publisher': product.publisher, 'isbn': isbn, 'binding': product.binding, 'pages': product.pages, 'publication_date': product.publication_date, 'list_price': product.list_price[0] } return book book = Books('config.yml').lookup('9781449389734') print yaml.dump(book, default_flow_style = False) ## Instruction: Read commandline args as isbns ## Code After: import yaml import sys import os from amazon.api import AmazonAPI # Change to script directory os.chdir(os.path.dirname(sys.argv[0])) class Books: def __init__(self, config_file): self.config = yaml.load(open(config_file, 'r')) self.amazon = AmazonAPI( self.config['aws_access_key_id'], self.config['aws_secret_key'], self.config['amazon_associate_tag'] ) def lookup(self, isbn): product = self.amazon.lookup(ItemId = isbn, IdType = 'ISBN', SearchIndex = "Books") book = { 'title': product.title, 'image_url': product.large_image_url, 'sales_rank': int(product.sales_rank), 'price': product.price_and_currency[0], 'offer_url': product.offer_url, 'authors': product.authors, 'publisher': product.publisher, 'isbn': isbn, 'binding': product.binding, 'pages': product.pages, 'publication_date': product.publication_date, 'list_price': product.list_price[0] } return book books = Books('config.yml') for isbn in sys.argv[1:]: book = books.lookup(isbn) with open('raw_data/{0}.yml'.format(isbn), 'w') as out: out.write(yaml.dump(book, default_flow_style = False))
// ... existing code ... import yaml import sys import os from amazon.api import AmazonAPI # Change to script directory os.chdir(os.path.dirname(sys.argv[0])) class Books: def __init__(self, config_file): // ... modified code ... return book books = Books('config.yml') for isbn in sys.argv[1:]: book = books.lookup(isbn) with open('raw_data/{0}.yml'.format(isbn), 'w') as out: out.write(yaml.dump(book, default_flow_style = False)) // ... rest of the code ...
f1ced257101996d64991a2ace8f04fb55ebfdef7
app/src/main/java/com/popalay/cardme/ui/base/BaseFragment.java
app/src/main/java/com/popalay/cardme/ui/base/BaseFragment.java
package com.popalay.cardme.ui.base; import android.app.Activity; import android.support.annotation.NonNull; import com.arellomobile.mvp.MvpAppCompatFragment; public abstract class BaseFragment extends MvpAppCompatFragment implements BaseView { @NonNull public BaseActivity getBaseActivity() { final Activity activity = getActivity(); if (activity != null && activity instanceof BaseActivity) { return (BaseActivity) activity; } throw new RuntimeException("BaseActivity is null"); } protected void showLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showLoadingDialog(); } protected void hideLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideLoadingDialog(); } @Override public void showError(String error) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showError(error); } @Override public void showMessage(String message) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showMessage(message); } @Override public void hideError() { } @Override public void hideMessage() { } @Override public void showProgress() { showLoadingDialog(); } @Override public void hideProgress() { hideLoadingDialog(); } @Override public void hideKeyboard() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideKeyboard(); } @Override public void close() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.close(); } }
package com.popalay.cardme.ui.base; import android.app.Activity; import android.support.annotation.NonNull; import com.arellomobile.mvp.MvpAppCompatFragment; public abstract class BaseFragment extends MvpAppCompatFragment implements BaseView { @NonNull public BaseActivity getBaseActivity() { final Activity activity = getActivity(); if (activity != null && activity instanceof BaseActivity) { return (BaseActivity) activity; } throw new RuntimeException("BaseActivity is null"); } protected void showLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showLoadingDialog(); } protected void hideLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideLoadingDialog(); } @Override public void showError(String error) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showError(error); } @Override public void showMessage(String message) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showMessage(message); } @Override public void hideError() { } @Override public void hideMessage() { } @Override public void showProgress() { showLoadingDialog(); } @Override public void hideProgress() { hideLoadingDialog(); } @Override public void hideKeyboard() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideKeyboard(); } @Override public void close() { throw new UnsupportedOperationException("You can not close the fragment"); } }
Throw exception when call close() on fragment
Throw exception when call close() on fragment
Java
apache-2.0
Popalay/Cardme,Popalay/Cardme,Popalay/Cardme
java
## Code Before: package com.popalay.cardme.ui.base; import android.app.Activity; import android.support.annotation.NonNull; import com.arellomobile.mvp.MvpAppCompatFragment; public abstract class BaseFragment extends MvpAppCompatFragment implements BaseView { @NonNull public BaseActivity getBaseActivity() { final Activity activity = getActivity(); if (activity != null && activity instanceof BaseActivity) { return (BaseActivity) activity; } throw new RuntimeException("BaseActivity is null"); } protected void showLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showLoadingDialog(); } protected void hideLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideLoadingDialog(); } @Override public void showError(String error) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showError(error); } @Override public void showMessage(String message) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showMessage(message); } @Override public void hideError() { } @Override public void hideMessage() { } @Override public void showProgress() { showLoadingDialog(); } @Override public void hideProgress() { hideLoadingDialog(); } @Override public void hideKeyboard() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideKeyboard(); } @Override public void close() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.close(); } } ## Instruction: Throw exception when call close() on fragment ## Code After: package com.popalay.cardme.ui.base; import android.app.Activity; import android.support.annotation.NonNull; import com.arellomobile.mvp.MvpAppCompatFragment; public abstract class BaseFragment extends MvpAppCompatFragment implements BaseView { @NonNull public BaseActivity getBaseActivity() { final Activity activity = getActivity(); if (activity != null && activity instanceof BaseActivity) { return (BaseActivity) activity; } throw new RuntimeException("BaseActivity is null"); } protected void showLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showLoadingDialog(); } protected void hideLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideLoadingDialog(); } @Override public void showError(String error) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showError(error); } @Override public void showMessage(String message) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showMessage(message); } @Override public void hideError() { } @Override public void hideMessage() { } @Override public void showProgress() { showLoadingDialog(); } @Override public void hideProgress() { hideLoadingDialog(); } @Override public void hideKeyboard() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideKeyboard(); } @Override public void close() { throw new UnsupportedOperationException("You can not close the fragment"); } }
// ... existing code ... @Override public void close() { throw new UnsupportedOperationException("You can not close the fragment"); } } // ... rest of the code ...
c78d9c63238b5535b1881f4eee54700f5a138b04
lupa/__init__.py
lupa/__init__.py
def _try_import_with_global_library_symbols(): try: import DLFCN dlopen_flags = DLFCN.RTLD_NOW | DLFCN.RTLD_GLOBAL except ImportError: import ctypes dlopen_flags = ctypes.RTLD_GLOBAL import sys old_flags = sys.getdlopenflags() try: sys.setdlopenflags(dlopen_flags) import lupa._lupa finally: sys.setdlopenflags(old_flags) try: _try_import_with_global_library_symbols() except: pass del _try_import_with_global_library_symbols # the following is all that should stay in the namespace: from lupa._lupa import * try: from lupa.version import __version__ except ImportError: pass
from __future__ import absolute_import # We need to enable global symbol visibility for lupa in order to # support binary module loading in Lua. If we can enable it here, we # do it temporarily. def _try_import_with_global_library_symbols(): try: from os import RTLD_NOW, RTLD_GLOBAL except ImportError: from DLFCN import RTLD_NOW, RTLD_GLOBAL # Py2.7 dlopen_flags = RTLD_NOW | RTLD_GLOBAL import sys old_flags = sys.getdlopenflags() try: sys.setdlopenflags(dlopen_flags) import lupa._lupa finally: sys.setdlopenflags(old_flags) try: _try_import_with_global_library_symbols() except: pass del _try_import_with_global_library_symbols # the following is all that should stay in the namespace: from lupa._lupa import * try: from lupa.version import __version__ except ImportError: pass
Use "os.RTLD_*" flags in Py3, as "DLFCN.*" is only the right thing to use in Py2.
Use "os.RTLD_*" flags in Py3, as "DLFCN.*" is only the right thing to use in Py2.
Python
mit
pombredanne/lupa,pombredanne/lupa
python
## Code Before: def _try_import_with_global_library_symbols(): try: import DLFCN dlopen_flags = DLFCN.RTLD_NOW | DLFCN.RTLD_GLOBAL except ImportError: import ctypes dlopen_flags = ctypes.RTLD_GLOBAL import sys old_flags = sys.getdlopenflags() try: sys.setdlopenflags(dlopen_flags) import lupa._lupa finally: sys.setdlopenflags(old_flags) try: _try_import_with_global_library_symbols() except: pass del _try_import_with_global_library_symbols # the following is all that should stay in the namespace: from lupa._lupa import * try: from lupa.version import __version__ except ImportError: pass ## Instruction: Use "os.RTLD_*" flags in Py3, as "DLFCN.*" is only the right thing to use in Py2. ## Code After: from __future__ import absolute_import # We need to enable global symbol visibility for lupa in order to # support binary module loading in Lua. If we can enable it here, we # do it temporarily. def _try_import_with_global_library_symbols(): try: from os import RTLD_NOW, RTLD_GLOBAL except ImportError: from DLFCN import RTLD_NOW, RTLD_GLOBAL # Py2.7 dlopen_flags = RTLD_NOW | RTLD_GLOBAL import sys old_flags = sys.getdlopenflags() try: sys.setdlopenflags(dlopen_flags) import lupa._lupa finally: sys.setdlopenflags(old_flags) try: _try_import_with_global_library_symbols() except: pass del _try_import_with_global_library_symbols # the following is all that should stay in the namespace: from lupa._lupa import * try: from lupa.version import __version__ except ImportError: pass
// ... existing code ... from __future__ import absolute_import # We need to enable global symbol visibility for lupa in order to # support binary module loading in Lua. If we can enable it here, we # do it temporarily. def _try_import_with_global_library_symbols(): try: from os import RTLD_NOW, RTLD_GLOBAL except ImportError: from DLFCN import RTLD_NOW, RTLD_GLOBAL # Py2.7 dlopen_flags = RTLD_NOW | RTLD_GLOBAL import sys old_flags = sys.getdlopenflags() // ... rest of the code ...
bb2c338baf4dacdca91841a4995a81b21786f80b
d03/d03s02/src/main/java/net/safedata/springboot/training/d03/s01/handler/PostLogoutHandler.java
d03/d03s02/src/main/java/net/safedata/springboot/training/d03/s01/handler/PostLogoutHandler.java
package net.safedata.springboot.training.d03.s01.handler; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class PostLogoutHandler implements LogoutHandler { @Override public void logout(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse, final Authentication authentication) { // perform any post-logout operations } }
package net.safedata.springboot.training.d03.s01.handler; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class PostLogoutHandler implements LogoutHandler { @Override public void logout(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse, final Authentication authentication) { // perform any post-logout operations } }
Split the parameter on the next line
[improve] Split the parameter on the next line
Java
apache-2.0
bogdansolga/spring-boot-training,bogdansolga/spring-boot-training
java
## Code Before: package net.safedata.springboot.training.d03.s01.handler; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class PostLogoutHandler implements LogoutHandler { @Override public void logout(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse, final Authentication authentication) { // perform any post-logout operations } } ## Instruction: [improve] Split the parameter on the next line ## Code After: package net.safedata.springboot.training.d03.s01.handler; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class PostLogoutHandler implements LogoutHandler { @Override public void logout(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse, final Authentication authentication) { // perform any post-logout operations } }
# ... existing code ... public class PostLogoutHandler implements LogoutHandler { @Override public void logout(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse, final Authentication authentication) { // perform any post-logout operations } # ... rest of the code ...
de9dda1eab33702a0367504547d0a1caff409782
src/model/Weights.java
src/model/Weights.java
package model; import io.Preface; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Weights { double[] weights; public Weights() { } public Weights(String weightsFile, int numFeatures) throws IOException { this.weights = new double[numFeatures]; if (!weightsFile.equals("zero")) { readWeights(weightsFile); } } public void setWeights(double[] weights) { this.weights = weights; } private void readWeights(String weightsFile) throws IOException { int ID = 0; BufferedReader in = new BufferedReader(new FileReader(weightsFile)); Preface.readPreface(in); String line = null; while ((line = in.readLine()) != null) { double weight = Double.parseDouble(line); weights[ID] = weight; ID++; } if (ID != weights.length) { throw new IllegalArgumentException("number of weights != number of features!"); } } public double getWeight(int ID) { return weights[ID]; } public void setWeight(int ID, double weight) { weights[ID] = weight; } }
package model; import io.Preface; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Weights { private double[] weights; public Weights() { } public Weights(String weightsFile, int numFeatures) throws IOException { this.weights = new double[numFeatures]; if (!weightsFile.equals("zero")) { readWeights(weightsFile); } } public void setWeights(double[] weights) { this.weights = (double[]) weights.clone(); } private void readWeights(String weightsFile) throws IOException { int ID = 0; BufferedReader in = new BufferedReader(new FileReader(weightsFile)); Preface.readPreface(in); String line = null; while ((line = in.readLine()) != null) { double weight = Double.parseDouble(line); weights[ID] = weight; ID++; } if (ID != weights.length) { throw new IllegalArgumentException("number of weights != number of features!"); } } public double getWeight(int ID) { return weights[ID]; } public void setWeight(int ID, double weight) { weights[ID] = weight; } }
Fix leaky abstraction by cloning double array instead of just copying reference.
Fix leaky abstraction by cloning double array instead of just copying reference.
Java
bsd-2-clause
darrenfoong/candc
java
## Code Before: package model; import io.Preface; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Weights { double[] weights; public Weights() { } public Weights(String weightsFile, int numFeatures) throws IOException { this.weights = new double[numFeatures]; if (!weightsFile.equals("zero")) { readWeights(weightsFile); } } public void setWeights(double[] weights) { this.weights = weights; } private void readWeights(String weightsFile) throws IOException { int ID = 0; BufferedReader in = new BufferedReader(new FileReader(weightsFile)); Preface.readPreface(in); String line = null; while ((line = in.readLine()) != null) { double weight = Double.parseDouble(line); weights[ID] = weight; ID++; } if (ID != weights.length) { throw new IllegalArgumentException("number of weights != number of features!"); } } public double getWeight(int ID) { return weights[ID]; } public void setWeight(int ID, double weight) { weights[ID] = weight; } } ## Instruction: Fix leaky abstraction by cloning double array instead of just copying reference. ## Code After: package model; import io.Preface; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Weights { private double[] weights; public Weights() { } public Weights(String weightsFile, int numFeatures) throws IOException { this.weights = new double[numFeatures]; if (!weightsFile.equals("zero")) { readWeights(weightsFile); } } public void setWeights(double[] weights) { this.weights = (double[]) weights.clone(); } private void readWeights(String weightsFile) throws IOException { int ID = 0; BufferedReader in = new BufferedReader(new FileReader(weightsFile)); Preface.readPreface(in); String line = null; while ((line = in.readLine()) != null) { double weight = Double.parseDouble(line); weights[ID] = weight; ID++; } if (ID != weights.length) { throw new IllegalArgumentException("number of weights != number of features!"); } } public double getWeight(int ID) { return weights[ID]; } public void setWeight(int ID, double weight) { weights[ID] = weight; } }
... import java.io.IOException; public class Weights { private double[] weights; public Weights() { } ... } public void setWeights(double[] weights) { this.weights = (double[]) weights.clone(); } private void readWeights(String weightsFile) throws IOException { ...
f313c9c476f6ae441f65567552ed835e96c62cb3
avocado/tests/settings.py
avocado/tests/settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } MODELTREES = { 'default': { 'model': 'tests.Employee' } } INSTALLED_APPS = ( 'avocado', 'avocado.meta', 'avocado.tests', ) COVERAGE_MODULES = ( 'avocado.meta.formatters', 'avocado.meta.exporters._base', 'avocado.meta.exporters._csv', 'avocado.meta.exporters._excel', 'avocado.meta.exporters._sas', 'avocado.meta.exporters._r', # 'avocado.meta.logictree', 'avocado.meta.managers', 'avocado.meta.mixins', 'avocado.meta.models', 'avocado.meta.operators', 'avocado.meta.translators', 'avocado.meta.utils', ) TEST_RUNNER = 'avocado.tests.coverage_test.CoverageTestRunner'
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } MODELTREES = { 'default': { 'model': 'tests.Employee' } } INSTALLED_APPS = ( 'avocado', 'avocado.meta', 'avocado.tests', ) COVERAGE_MODULES = ( 'avocado.meta.formatters', 'avocado.meta.exporters._base', 'avocado.meta.exporters._csv', 'avocado.meta.exporters._excel', 'avocado.meta.exporters._sas', 'avocado.meta.exporters._r', 'avocado.meta.exporters._json', # 'avocado.meta.logictree', 'avocado.meta.managers', 'avocado.meta.mixins', 'avocado.meta.models', 'avocado.meta.operators', 'avocado.meta.translators', 'avocado.meta.utils', ) TEST_RUNNER = 'avocado.tests.coverage_test.CoverageTestRunner'
Add json exporter module to modules coveraged
Add json exporter module to modules coveraged
Python
bsd-2-clause
murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado
python
## Code Before: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } MODELTREES = { 'default': { 'model': 'tests.Employee' } } INSTALLED_APPS = ( 'avocado', 'avocado.meta', 'avocado.tests', ) COVERAGE_MODULES = ( 'avocado.meta.formatters', 'avocado.meta.exporters._base', 'avocado.meta.exporters._csv', 'avocado.meta.exporters._excel', 'avocado.meta.exporters._sas', 'avocado.meta.exporters._r', # 'avocado.meta.logictree', 'avocado.meta.managers', 'avocado.meta.mixins', 'avocado.meta.models', 'avocado.meta.operators', 'avocado.meta.translators', 'avocado.meta.utils', ) TEST_RUNNER = 'avocado.tests.coverage_test.CoverageTestRunner' ## Instruction: Add json exporter module to modules coveraged ## Code After: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } } MODELTREES = { 'default': { 'model': 'tests.Employee' } } INSTALLED_APPS = ( 'avocado', 'avocado.meta', 'avocado.tests', ) COVERAGE_MODULES = ( 'avocado.meta.formatters', 'avocado.meta.exporters._base', 'avocado.meta.exporters._csv', 'avocado.meta.exporters._excel', 'avocado.meta.exporters._sas', 'avocado.meta.exporters._r', 'avocado.meta.exporters._json', # 'avocado.meta.logictree', 'avocado.meta.managers', 'avocado.meta.mixins', 'avocado.meta.models', 'avocado.meta.operators', 'avocado.meta.translators', 'avocado.meta.utils', ) TEST_RUNNER = 'avocado.tests.coverage_test.CoverageTestRunner'
... 'avocado.meta.exporters._excel', 'avocado.meta.exporters._sas', 'avocado.meta.exporters._r', 'avocado.meta.exporters._json', # 'avocado.meta.logictree', 'avocado.meta.managers', 'avocado.meta.mixins', ...
b6fc94d9c6b5015ad2dc882d454127d4b0a6ecee
django_foodbot/api/models.py
django_foodbot/api/models.py
from django.db import models class Menu(models.Model): day = models.CharField(max_length=10, blank=False, null=False) food = models.CharField(max_length=60, blank=False, null=False) meal = models.CharField(max_length=10, blank=False, null=False) option = models.IntegerField(null=False) week = models.IntegerField(null=False) class Meta: ordering = ('-week',) db_table = 'menu_table' def __unicode__(self): return u'%s %s' % (self.day, self.week) class Rating(models.Model): date = models.DateTimeField(auto_now_add=True) user_id = models.CharField(max_length=20) menu = models.ForeignKey(Menu, related_name='rating') rate = models.IntegerField(blank=False, null=False) comment = models.TextField(default='no comment', ) class Meta: ordering = ('-date',) db_table = 'rating' def __unicode__(self): return u'%s' % (self.date)
from django.db import models class Menu(models.Model): day = models.CharField(max_length=10, blank=False, null=False) food = models.CharField(max_length=120, blank=False, null=False) meal = models.CharField(max_length=10, blank=False, null=False) option = models.IntegerField(null=False) week = models.IntegerField(null=False) class Meta: ordering = ('-week',) db_table = 'menu_table' def __unicode__(self): return u'%s %s %s' % (self.day, self.week, self.meal) class Rating(models.Model): date = models.DateTimeField(auto_now_add=True) user_id = models.CharField(max_length=20) menu = models.ForeignKey(Menu, related_name='rating') rate = models.IntegerField(blank=False, null=False) comment = models.TextField(default='no comment', ) class Meta: ordering = ('-date',) db_table = 'rating' def __unicode__(self): return u'%s' % (self.date)
Increase character length for food
Increase character length for food
Python
mit
andela-kanyanwu/food-bot-review
python
## Code Before: from django.db import models class Menu(models.Model): day = models.CharField(max_length=10, blank=False, null=False) food = models.CharField(max_length=60, blank=False, null=False) meal = models.CharField(max_length=10, blank=False, null=False) option = models.IntegerField(null=False) week = models.IntegerField(null=False) class Meta: ordering = ('-week',) db_table = 'menu_table' def __unicode__(self): return u'%s %s' % (self.day, self.week) class Rating(models.Model): date = models.DateTimeField(auto_now_add=True) user_id = models.CharField(max_length=20) menu = models.ForeignKey(Menu, related_name='rating') rate = models.IntegerField(blank=False, null=False) comment = models.TextField(default='no comment', ) class Meta: ordering = ('-date',) db_table = 'rating' def __unicode__(self): return u'%s' % (self.date) ## Instruction: Increase character length for food ## Code After: from django.db import models class Menu(models.Model): day = models.CharField(max_length=10, blank=False, null=False) food = models.CharField(max_length=120, blank=False, null=False) meal = models.CharField(max_length=10, blank=False, null=False) option = models.IntegerField(null=False) week = models.IntegerField(null=False) class Meta: ordering = ('-week',) db_table = 'menu_table' def __unicode__(self): return u'%s %s %s' % (self.day, self.week, self.meal) class Rating(models.Model): date = models.DateTimeField(auto_now_add=True) user_id = models.CharField(max_length=20) menu = models.ForeignKey(Menu, related_name='rating') rate = models.IntegerField(blank=False, null=False) comment = models.TextField(default='no comment', ) class Meta: ordering = ('-date',) db_table = 'rating' def __unicode__(self): return u'%s' % (self.date)
... class Menu(models.Model): day = models.CharField(max_length=10, blank=False, null=False) food = models.CharField(max_length=120, blank=False, null=False) meal = models.CharField(max_length=10, blank=False, null=False) option = models.IntegerField(null=False) week = models.IntegerField(null=False) ... db_table = 'menu_table' def __unicode__(self): return u'%s %s %s' % (self.day, self.week, self.meal) class Rating(models.Model): ...
44650a0b3d395b4201a039bd2f3eb916987dce8d
_grains/osqueryinfo.py
_grains/osqueryinfo.py
import salt.utils import salt.modules.cmdmod __salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet} def osquerygrain(): ''' Return osquery version in grain ''' # Provides: # osqueryversion # osquerybinpath grains = {} option = '--version' # Prefer our /opt/osquery/osqueryi if present osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi') for path in osqueryipaths: if salt.utils.which(path): for item in __salt__['cmd.run']('{0} {1}'.format(path, option)).split(): if item[:1].isdigit(): grains['osqueryversion'] = item grains['osquerybinpath'] = salt.utils.which(path) break break return grains
import salt.utils import salt.modules.cmdmod __salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet} def osquerygrain(): ''' Return osquery version in grain ''' # Provides: # osqueryversion # osquerybinpath grains = {} option = '--version' # Prefer our /opt/osquery/osqueryi if present osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi') for path in osqueryipaths: if salt.utils.path.which(path): for item in __salt__['cmd.run']('{0} {1}'.format(path, option)).split(): if item[:1].isdigit(): grains['osqueryversion'] = item grains['osquerybinpath'] = salt.utils.path.which(path) break break return grains
Use of salt.utils.which detected. This function has been moved to salt.utils.path.which as of Salt 2018.3.0
DeprecationWarning: Use of salt.utils.which detected. This function has been moved to salt.utils.path.which as of Salt 2018.3.0
Python
apache-2.0
hubblestack/hubble-salt
python
## Code Before: import salt.utils import salt.modules.cmdmod __salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet} def osquerygrain(): ''' Return osquery version in grain ''' # Provides: # osqueryversion # osquerybinpath grains = {} option = '--version' # Prefer our /opt/osquery/osqueryi if present osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi') for path in osqueryipaths: if salt.utils.which(path): for item in __salt__['cmd.run']('{0} {1}'.format(path, option)).split(): if item[:1].isdigit(): grains['osqueryversion'] = item grains['osquerybinpath'] = salt.utils.which(path) break break return grains ## Instruction: DeprecationWarning: Use of salt.utils.which detected. This function has been moved to salt.utils.path.which as of Salt 2018.3.0 ## Code After: import salt.utils import salt.modules.cmdmod __salt__ = {'cmd.run': salt.modules.cmdmod._run_quiet} def osquerygrain(): ''' Return osquery version in grain ''' # Provides: # osqueryversion # osquerybinpath grains = {} option = '--version' # Prefer our /opt/osquery/osqueryi if present osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi') for path in osqueryipaths: if salt.utils.path.which(path): for item in __salt__['cmd.run']('{0} {1}'.format(path, option)).split(): if item[:1].isdigit(): grains['osqueryversion'] = item grains['osquerybinpath'] = salt.utils.path.which(path) break break return grains
... # Prefer our /opt/osquery/osqueryi if present osqueryipaths = ('/opt/osquery/osqueryi', 'osqueryi', '/usr/bin/osqueryi') for path in osqueryipaths: if salt.utils.path.which(path): for item in __salt__['cmd.run']('{0} {1}'.format(path, option)).split(): if item[:1].isdigit(): grains['osqueryversion'] = item grains['osquerybinpath'] = salt.utils.path.which(path) break break return grains ...
5b7e2c7c4ad28634db9641a2b8c96f4d047ae503
arim/fields.py
arim/fields.py
import re from django import forms mac_pattern = re.compile("^[0-9a-f]{12}$") class MacAddrFormField(forms.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 17 super(MacAddrFormField, self).__init__(*args, **kwargs) def clean(self, value): value = super(MacAddrFormField, self).clean(value) value = filter(lambda x: x in "0123456789abcdef", value) if mac_pattern.match(value) is None: raise forms.ValidationError('Invalid MAC address') value = reduce(lambda x,y: x + ':' + y, (value[i:i+2] for i in xrange(0, 12, 2))) return value
import re from django import forms mac_pattern = re.compile("^[0-9a-f]{12}$") class MacAddrFormField(forms.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 17 super(MacAddrFormField, self).__init__(*args, **kwargs) def clean(self, value): value = super(MacAddrFormField, self).clean(value) value = value.lower().replace(':', '').replace('-', '') if mac_pattern.match(value) is None: raise forms.ValidationError('Invalid MAC address') value = reduce(lambda x,y: x + ':' + y, (value[i:i+2] for i in xrange(0, 12, 2))) return value
Revert "Properly handle non-hex characters in MAC"
Revert "Properly handle non-hex characters in MAC" This reverts commit 2734a3f0212c722fb9fe3698dfea0dbd8a14faa7.
Python
bsd-3-clause
OSU-Net/arim,drkitty/arim,OSU-Net/arim,drkitty/arim,drkitty/arim,OSU-Net/arim
python
## Code Before: import re from django import forms mac_pattern = re.compile("^[0-9a-f]{12}$") class MacAddrFormField(forms.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 17 super(MacAddrFormField, self).__init__(*args, **kwargs) def clean(self, value): value = super(MacAddrFormField, self).clean(value) value = filter(lambda x: x in "0123456789abcdef", value) if mac_pattern.match(value) is None: raise forms.ValidationError('Invalid MAC address') value = reduce(lambda x,y: x + ':' + y, (value[i:i+2] for i in xrange(0, 12, 2))) return value ## Instruction: Revert "Properly handle non-hex characters in MAC" This reverts commit 2734a3f0212c722fb9fe3698dfea0dbd8a14faa7. ## Code After: import re from django import forms mac_pattern = re.compile("^[0-9a-f]{12}$") class MacAddrFormField(forms.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 17 super(MacAddrFormField, self).__init__(*args, **kwargs) def clean(self, value): value = super(MacAddrFormField, self).clean(value) value = value.lower().replace(':', '').replace('-', '') if mac_pattern.match(value) is None: raise forms.ValidationError('Invalid MAC address') value = reduce(lambda x,y: x + ':' + y, (value[i:i+2] for i in xrange(0, 12, 2))) return value
... def clean(self, value): value = super(MacAddrFormField, self).clean(value) value = value.lower().replace(':', '').replace('-', '') if mac_pattern.match(value) is None: raise forms.ValidationError('Invalid MAC address') value = reduce(lambda x,y: x + ':' + y, ...
d23ee11cb7deb9ae9ada7b3eca603d3589f9a343
stagecraft/apps/datasets/admin/backdrop_user.py
stagecraft/apps/datasets/admin/backdrop_user.py
from __future__ import unicode_literals from django.contrib import admin import reversion from stagecraft.apps.datasets.models.backdrop_user import BackdropUser class BackdropUserAdmin(reversion.VersionAdmin): search_fields = ['email'] list_display = ('email') admin.site.register(BackdropUser)
from __future__ import unicode_literals from django.contrib import admin from django.db import models import reversion from stagecraft.apps.datasets.models.backdrop_user import BackdropUser from stagecraft.apps.datasets.models.data_set import DataSet class DataSetInline(admin.StackedInline): model = DataSet fields = ('name',) extra = 0 class BackdropUserAdmin(reversion.VersionAdmin): search_fields = ['email', 'data_sets'] list_display = ('email', 'numer_of_datasets_user_has_access_to',) list_per_page = 30 def queryset(self, request): return BackdropUser.objects.annotate( dataset_count=models.Count('data_sets') ) def numer_of_datasets_user_has_access_to(self, obj): return obj.dataset_count numer_of_datasets_user_has_access_to.admin_order_field = 'dataset_count' admin.site.register(BackdropUser, BackdropUserAdmin)
Add user:dataset count to backdrop user admin
Add user:dataset count to backdrop user admin - Sortable by number of data-sets the user has access to - Vaguely useful, but mainly an exercise in seeing how easily we can customise the output of the manytomany field (not very easily)
Python
mit
alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft
python
## Code Before: from __future__ import unicode_literals from django.contrib import admin import reversion from stagecraft.apps.datasets.models.backdrop_user import BackdropUser class BackdropUserAdmin(reversion.VersionAdmin): search_fields = ['email'] list_display = ('email') admin.site.register(BackdropUser) ## Instruction: Add user:dataset count to backdrop user admin - Sortable by number of data-sets the user has access to - Vaguely useful, but mainly an exercise in seeing how easily we can customise the output of the manytomany field (not very easily) ## Code After: from __future__ import unicode_literals from django.contrib import admin from django.db import models import reversion from stagecraft.apps.datasets.models.backdrop_user import BackdropUser from stagecraft.apps.datasets.models.data_set import DataSet class DataSetInline(admin.StackedInline): model = DataSet fields = ('name',) extra = 0 class BackdropUserAdmin(reversion.VersionAdmin): search_fields = ['email', 'data_sets'] list_display = ('email', 'numer_of_datasets_user_has_access_to',) list_per_page = 30 def queryset(self, request): return BackdropUser.objects.annotate( dataset_count=models.Count('data_sets') ) def numer_of_datasets_user_has_access_to(self, obj): return obj.dataset_count numer_of_datasets_user_has_access_to.admin_order_field = 'dataset_count' admin.site.register(BackdropUser, BackdropUserAdmin)
... from __future__ import unicode_literals from django.contrib import admin from django.db import models import reversion from stagecraft.apps.datasets.models.backdrop_user import BackdropUser from stagecraft.apps.datasets.models.data_set import DataSet class DataSetInline(admin.StackedInline): model = DataSet fields = ('name',) extra = 0 class BackdropUserAdmin(reversion.VersionAdmin): search_fields = ['email', 'data_sets'] list_display = ('email', 'numer_of_datasets_user_has_access_to',) list_per_page = 30 def queryset(self, request): return BackdropUser.objects.annotate( dataset_count=models.Count('data_sets') ) def numer_of_datasets_user_has_access_to(self, obj): return obj.dataset_count numer_of_datasets_user_has_access_to.admin_order_field = 'dataset_count' admin.site.register(BackdropUser, BackdropUserAdmin) ...
c2de694b7c7196954bbe62f5edfd9438a071faa0
src/main/java/org/cyclops/cyclopscore/config/extendedconfig/VillagerConfig.java
src/main/java/org/cyclops/cyclopscore/config/extendedconfig/VillagerConfig.java
package org.cyclops.cyclopscore.config.extendedconfig; import org.cyclops.cyclopscore.config.ConfigurableType; import org.cyclops.cyclopscore.config.configurable.ConfigurableVillager; import org.cyclops.cyclopscore.init.ModBase; /** * Config for villagers. * @author rubensworks * @see ExtendedConfig */ public abstract class VillagerConfig extends ExtendedConfig<VillagerConfig> { private final int id; /** * Make a new instance. * @param mod The mod instance. * @param defaultId The default ID for the configurable. * @param namedId The unique name ID for the configurable. * @param comment The comment to add in the config file for this configurable. * @param element The class of this configurable. */ public VillagerConfig(ModBase mod, int defaultId, String namedId, String comment, Class<? extends ConfigurableVillager> element) { super(mod, defaultId != 0, namedId, comment, element); this.id = defaultId; } public int getId() { return this.id; } @Override public String getUnlocalizedName() { return "entity.villager." + getNamedId(); } @Override public ConfigurableType getHolderType() { return ConfigurableType.VILLAGER; } }
package org.cyclops.cyclopscore.config.extendedconfig; import org.cyclops.cyclopscore.config.ConfigurableType; import org.cyclops.cyclopscore.config.configurable.ConfigurableVillager; import org.cyclops.cyclopscore.init.ModBase; /** * Config for villagers. * @author rubensworks * @see ExtendedConfig */ public abstract class VillagerConfig extends ExtendedConfig<VillagerConfig> { private int id; /** * Make a new instance. * @param mod The mod instance. * @param defaultId The default ID for the configurable. * @param namedId The unique name ID for the configurable. * @param comment The comment to add in the config file for this configurable. * @param element The class of this configurable. */ public VillagerConfig(ModBase mod, int defaultId, String namedId, String comment, Class<? extends ConfigurableVillager> element) { super(mod, defaultId != 0, namedId, comment, element); this.id = defaultId; } public void setId(int id) { this.id = id; } public int getId() { return this.id; } @Override public String getUnlocalizedName() { return "entity.villager." + getNamedId(); } @Override public ConfigurableType getHolderType() { return ConfigurableType.VILLAGER; } }
Allow changing of villager id
Allow changing of villager id
Java
mit
CyclopsMC/CyclopsCore
java
## Code Before: package org.cyclops.cyclopscore.config.extendedconfig; import org.cyclops.cyclopscore.config.ConfigurableType; import org.cyclops.cyclopscore.config.configurable.ConfigurableVillager; import org.cyclops.cyclopscore.init.ModBase; /** * Config for villagers. * @author rubensworks * @see ExtendedConfig */ public abstract class VillagerConfig extends ExtendedConfig<VillagerConfig> { private final int id; /** * Make a new instance. * @param mod The mod instance. * @param defaultId The default ID for the configurable. * @param namedId The unique name ID for the configurable. * @param comment The comment to add in the config file for this configurable. * @param element The class of this configurable. */ public VillagerConfig(ModBase mod, int defaultId, String namedId, String comment, Class<? extends ConfigurableVillager> element) { super(mod, defaultId != 0, namedId, comment, element); this.id = defaultId; } public int getId() { return this.id; } @Override public String getUnlocalizedName() { return "entity.villager." + getNamedId(); } @Override public ConfigurableType getHolderType() { return ConfigurableType.VILLAGER; } } ## Instruction: Allow changing of villager id ## Code After: package org.cyclops.cyclopscore.config.extendedconfig; import org.cyclops.cyclopscore.config.ConfigurableType; import org.cyclops.cyclopscore.config.configurable.ConfigurableVillager; import org.cyclops.cyclopscore.init.ModBase; /** * Config for villagers. * @author rubensworks * @see ExtendedConfig */ public abstract class VillagerConfig extends ExtendedConfig<VillagerConfig> { private int id; /** * Make a new instance. * @param mod The mod instance. * @param defaultId The default ID for the configurable. * @param namedId The unique name ID for the configurable. * @param comment The comment to add in the config file for this configurable. * @param element The class of this configurable. */ public VillagerConfig(ModBase mod, int defaultId, String namedId, String comment, Class<? extends ConfigurableVillager> element) { super(mod, defaultId != 0, namedId, comment, element); this.id = defaultId; } public void setId(int id) { this.id = id; } public int getId() { return this.id; } @Override public String getUnlocalizedName() { return "entity.villager." + getNamedId(); } @Override public ConfigurableType getHolderType() { return ConfigurableType.VILLAGER; } }
// ... existing code ... */ public abstract class VillagerConfig extends ExtendedConfig<VillagerConfig> { private int id; /** * Make a new instance. // ... modified code ... String comment, Class<? extends ConfigurableVillager> element) { super(mod, defaultId != 0, namedId, comment, element); this.id = defaultId; } public void setId(int id) { this.id = id; } public int getId() { // ... rest of the code ...
d343b8f4f1a7500cd7120967d0fd0f06c5002592
src/main/java/com/hp/autonomy/frontend/find/search/DocumentsServiceImpl.java
src/main/java/com/hp/autonomy/frontend/find/search/DocumentsServiceImpl.java
/* * Copyright 2014-2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ package com.hp.autonomy.frontend.find.search; import com.hp.autonomy.frontend.find.ApiKeyService; import com.hp.autonomy.iod.client.api.search.*; import com.hp.autonomy.iod.client.error.IodErrorException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class DocumentsServiceImpl implements DocumentsService { @Autowired private ApiKeyService apiKeyService; @Autowired private QueryTextIndexService queryTextIndexService; @Override public Documents queryTextIndex(final String text, final int maxResults, final Summary summary, final List<String> indexes, final String fieldText) throws IodErrorException { final Map<String, Object> params = new QueryRequestBuilder() .setAbsoluteMaxResults(maxResults) .setSummary(summary) .setIndexes(indexes) .setFieldText(fieldText) .build(); return queryTextIndexService.queryTextIndexWithText(apiKeyService.getApiKey(), text, params); } }
/* * Copyright 2014-2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ package com.hp.autonomy.frontend.find.search; import com.hp.autonomy.frontend.find.ApiKeyService; import com.hp.autonomy.frontend.find.QueryProfileService; import com.hp.autonomy.iod.client.api.search.*; import com.hp.autonomy.iod.client.error.IodErrorException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class DocumentsServiceImpl implements DocumentsService { @Autowired private ApiKeyService apiKeyService; @Autowired private QueryProfileService queryProfileService; @Autowired private QueryTextIndexService queryTextIndexService; @Override public Documents queryTextIndex(final String text, final int maxResults, final Summary summary, final List<String> indexes, final String fieldText) throws IodErrorException { final Map<String, Object> params = new QueryRequestBuilder() .setAbsoluteMaxResults(maxResults) .setSummary(summary) .setIndexes(indexes) .setFieldText(fieldText) .setQueryProfile(queryProfileService.getQueryProfile()) .build(); return queryTextIndexService.queryTextIndexWithText(apiKeyService.getApiKey(), text, params); } }
Use query profile when querying for results documents
Use query profile when querying for results documents
Java
mit
hpe-idol/find,LinkPowerHK/find,LinkPowerHK/find,hpe-idol/find,hpautonomy/find,hpe-idol/find,hpe-idol/java-powerpoint-report,hpautonomy/find,hpautonomy/find,hpautonomy/find,hpe-idol/java-powerpoint-report,hpe-idol/find,hpautonomy/find,LinkPowerHK/find,LinkPowerHK/find,hpe-idol/find,LinkPowerHK/find
java
## Code Before: /* * Copyright 2014-2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ package com.hp.autonomy.frontend.find.search; import com.hp.autonomy.frontend.find.ApiKeyService; import com.hp.autonomy.iod.client.api.search.*; import com.hp.autonomy.iod.client.error.IodErrorException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class DocumentsServiceImpl implements DocumentsService { @Autowired private ApiKeyService apiKeyService; @Autowired private QueryTextIndexService queryTextIndexService; @Override public Documents queryTextIndex(final String text, final int maxResults, final Summary summary, final List<String> indexes, final String fieldText) throws IodErrorException { final Map<String, Object> params = new QueryRequestBuilder() .setAbsoluteMaxResults(maxResults) .setSummary(summary) .setIndexes(indexes) .setFieldText(fieldText) .build(); return queryTextIndexService.queryTextIndexWithText(apiKeyService.getApiKey(), text, params); } } ## Instruction: Use query profile when querying for results documents ## Code After: /* * Copyright 2014-2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ package com.hp.autonomy.frontend.find.search; import com.hp.autonomy.frontend.find.ApiKeyService; import com.hp.autonomy.frontend.find.QueryProfileService; import com.hp.autonomy.iod.client.api.search.*; import com.hp.autonomy.iod.client.error.IodErrorException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; @Service public class DocumentsServiceImpl implements DocumentsService { @Autowired private ApiKeyService apiKeyService; @Autowired private QueryProfileService queryProfileService; @Autowired private QueryTextIndexService queryTextIndexService; @Override public Documents queryTextIndex(final String text, final int maxResults, final Summary summary, final List<String> indexes, final String fieldText) throws IodErrorException { final Map<String, Object> params = new QueryRequestBuilder() .setAbsoluteMaxResults(maxResults) .setSummary(summary) .setIndexes(indexes) .setFieldText(fieldText) .setQueryProfile(queryProfileService.getQueryProfile()) .build(); return queryTextIndexService.queryTextIndexWithText(apiKeyService.getApiKey(), text, params); } }
... package com.hp.autonomy.frontend.find.search; import com.hp.autonomy.frontend.find.ApiKeyService; import com.hp.autonomy.frontend.find.QueryProfileService; import com.hp.autonomy.iod.client.api.search.*; import com.hp.autonomy.iod.client.error.IodErrorException; import org.springframework.beans.factory.annotation.Autowired; ... private ApiKeyService apiKeyService; @Autowired private QueryProfileService queryProfileService; @Autowired private QueryTextIndexService queryTextIndexService; @Override ... .setSummary(summary) .setIndexes(indexes) .setFieldText(fieldText) .setQueryProfile(queryProfileService.getQueryProfile()) .build(); return queryTextIndexService.queryTextIndexWithText(apiKeyService.getApiKey(), text, params); ...
f98ff54c363fc2f2b0885464afffcb92cdea8cfe
ubersmith/calls/device.py
ubersmith/calls/device.py
from ubersmith.calls import BaseCall, GroupCall from ubersmith.utils import prepend_base __all__ = [ 'GetCall', 'ListCall', ] _ = prepend_base(__name__.split('.')[-1]) class GetCall(BaseCall): method = _('get') required_fields = ['device_id'] class ListCall(GroupCall): method = _('list') rename_fields = {'clientid': 'client_id'} int_fields = ['client_id'] class ModuleGraphCall(FileCall): method = _('module_graph')
from ubersmith.calls import BaseCall, GroupCall, FileCall from ubersmith.utils import prepend_base __all__ = [ 'GetCall', 'ListCall', 'ModuleGraphCall', ] _ = prepend_base(__name__.split('.')[-1]) class GetCall(BaseCall): method = _('get') required_fields = ['device_id'] class ListCall(GroupCall): method = _('list') rename_fields = {'clientid': 'client_id'} int_fields = ['client_id'] class ModuleGraphCall(FileCall): method = _('module_graph')
Make module graph call return a file.
Make module graph call return a file.
Python
mit
hivelocity/python-ubersmith,jasonkeene/python-ubersmith,hivelocity/python-ubersmith,jasonkeene/python-ubersmith
python
## Code Before: from ubersmith.calls import BaseCall, GroupCall from ubersmith.utils import prepend_base __all__ = [ 'GetCall', 'ListCall', ] _ = prepend_base(__name__.split('.')[-1]) class GetCall(BaseCall): method = _('get') required_fields = ['device_id'] class ListCall(GroupCall): method = _('list') rename_fields = {'clientid': 'client_id'} int_fields = ['client_id'] class ModuleGraphCall(FileCall): method = _('module_graph') ## Instruction: Make module graph call return a file. ## Code After: from ubersmith.calls import BaseCall, GroupCall, FileCall from ubersmith.utils import prepend_base __all__ = [ 'GetCall', 'ListCall', 'ModuleGraphCall', ] _ = prepend_base(__name__.split('.')[-1]) class GetCall(BaseCall): method = _('get') required_fields = ['device_id'] class ListCall(GroupCall): method = _('list') rename_fields = {'clientid': 'client_id'} int_fields = ['client_id'] class ModuleGraphCall(FileCall): method = _('module_graph')
// ... existing code ... from ubersmith.calls import BaseCall, GroupCall, FileCall from ubersmith.utils import prepend_base __all__ = [ 'GetCall', 'ListCall', 'ModuleGraphCall', ] _ = prepend_base(__name__.split('.')[-1]) // ... rest of the code ...
3b091fba819f1ad69d0ce9e9038ccf5d14fea215
tests/core/tests/test_mixins.py
tests/core/tests/test_mixins.py
from core.models import Category from django.test.testcases import TestCase from django.urls import reverse class ExportViewMixinTest(TestCase): def setUp(self): self.url = reverse('export-category') self.cat1 = Category.objects.create(name='Cat 1') self.cat2 = Category.objects.create(name='Cat 2') def test_get(self): response = self.client.get(self.url) self.assertContains(response, self.cat1.name, status_code=200) self.assertTrue(response['Content-Type'], 'text/html') def test_post(self): data = { 'file_format': '0', } response = self.client.post(self.url, data) self.assertContains(response, self.cat1.name, status_code=200) self.assertTrue(response.has_header("Content-Disposition")) self.assertTrue(response['Content-Type'], 'text/csv')
from core.models import Category from django.test.testcases import TestCase from django.urls import reverse class ExportViewMixinTest(TestCase): def setUp(self): self.url = reverse('export-category') self.cat1 = Category.objects.create(name='Cat 1') self.cat2 = Category.objects.create(name='Cat 2') def test_get(self): response = self.client.get(self.url) self.assertContains(response, self.cat1.name, status_code=200) self.assertEquals(response['Content-Type'], 'text/html; charset=utf-8') def test_post(self): data = { 'file_format': '0', } response = self.client.post(self.url, data) self.assertContains(response, self.cat1.name, status_code=200) self.assertTrue(response.has_header("Content-Disposition")) self.assertEquals(response['Content-Type'], 'text/csv')
Correct mistaken assertTrue() -> assertEquals()
Correct mistaken assertTrue() -> assertEquals()
Python
bsd-2-clause
bmihelac/django-import-export,bmihelac/django-import-export,bmihelac/django-import-export,jnns/django-import-export,jnns/django-import-export,jnns/django-import-export,django-import-export/django-import-export,django-import-export/django-import-export,django-import-export/django-import-export,django-import-export/django-import-export,jnns/django-import-export,bmihelac/django-import-export
python
## Code Before: from core.models import Category from django.test.testcases import TestCase from django.urls import reverse class ExportViewMixinTest(TestCase): def setUp(self): self.url = reverse('export-category') self.cat1 = Category.objects.create(name='Cat 1') self.cat2 = Category.objects.create(name='Cat 2') def test_get(self): response = self.client.get(self.url) self.assertContains(response, self.cat1.name, status_code=200) self.assertTrue(response['Content-Type'], 'text/html') def test_post(self): data = { 'file_format': '0', } response = self.client.post(self.url, data) self.assertContains(response, self.cat1.name, status_code=200) self.assertTrue(response.has_header("Content-Disposition")) self.assertTrue(response['Content-Type'], 'text/csv') ## Instruction: Correct mistaken assertTrue() -> assertEquals() ## Code After: from core.models import Category from django.test.testcases import TestCase from django.urls import reverse class ExportViewMixinTest(TestCase): def setUp(self): self.url = reverse('export-category') self.cat1 = Category.objects.create(name='Cat 1') self.cat2 = Category.objects.create(name='Cat 2') def test_get(self): response = self.client.get(self.url) self.assertContains(response, self.cat1.name, status_code=200) self.assertEquals(response['Content-Type'], 'text/html; charset=utf-8') def test_post(self): data = { 'file_format': '0', } response = self.client.post(self.url, data) self.assertContains(response, self.cat1.name, status_code=200) self.assertTrue(response.has_header("Content-Disposition")) self.assertEquals(response['Content-Type'], 'text/csv')
// ... existing code ... def test_get(self): response = self.client.get(self.url) self.assertContains(response, self.cat1.name, status_code=200) self.assertEquals(response['Content-Type'], 'text/html; charset=utf-8') def test_post(self): data = { // ... modified code ... response = self.client.post(self.url, data) self.assertContains(response, self.cat1.name, status_code=200) self.assertTrue(response.has_header("Content-Disposition")) self.assertEquals(response['Content-Type'], 'text/csv') // ... rest of the code ...
1ef1851e508295f6d4bf01289591f42c21656df7
test/on_yubikey/test_interfaces.py
test/on_yubikey/test_interfaces.py
import unittest from .framework import DestructiveYubikeyTestCase, exactly_one_yubikey_present from yubikit.core.otp import OtpConnection from yubikit.core.fido import FidoConnection from yubikit.core.smartcard import SmartCardConnection from ykman.device import connect_to_device from time import sleep @unittest.skipIf( not exactly_one_yubikey_present(), "Exactly one YubiKey must be present." ) class TestInterfaces(DestructiveYubikeyTestCase): def try_connection(self, conn_type): for _ in range(8): try: conn = connect_to_device(None, [conn_type])[0] conn.close() return except Exception: sleep(0.5) self.fail("Failed connecting to device over %s" % conn_type) def test_switch_interfaces(self): self.try_connection(FidoConnection) self.try_connection(OtpConnection) self.try_connection(FidoConnection) self.try_connection(SmartCardConnection) self.try_connection(OtpConnection) self.try_connection(SmartCardConnection) self.try_connection(OtpConnection) self.try_connection(FidoConnection) self.try_connection(SmartCardConnection) self.try_connection(FidoConnection) self.try_connection(SmartCardConnection) self.try_connection(OtpConnection)
import unittest from .framework import DestructiveYubikeyTestCase, exactly_one_yubikey_present from yubikit.core.otp import OtpConnection from yubikit.core.fido import FidoConnection from yubikit.core.smartcard import SmartCardConnection from ykman.base import YUBIKEY from ykman.device import connect_to_device from time import sleep @unittest.skipIf( not exactly_one_yubikey_present(), "Exactly one YubiKey must be present." ) class TestInterfaces(DestructiveYubikeyTestCase): def try_connection(self, conn_type): if self.key_type == YUBIKEY.NEO and conn_type == SmartCardConnection: sleep(3.5) conn, dev, info = connect_to_device(None, [conn_type]) conn.close() def setUp(self): conn, dev, info = connect_to_device() conn.close() self.key_type = dev.pid.get_type() def test_switch_interfaces(self): self.try_connection(FidoConnection) self.try_connection(OtpConnection) self.try_connection(FidoConnection) self.try_connection(SmartCardConnection) self.try_connection(OtpConnection) self.try_connection(SmartCardConnection) self.try_connection(FidoConnection)
Test handling of reclaim timeout.
Test handling of reclaim timeout.
Python
bsd-2-clause
Yubico/yubikey-manager,Yubico/yubikey-manager
python
## Code Before: import unittest from .framework import DestructiveYubikeyTestCase, exactly_one_yubikey_present from yubikit.core.otp import OtpConnection from yubikit.core.fido import FidoConnection from yubikit.core.smartcard import SmartCardConnection from ykman.device import connect_to_device from time import sleep @unittest.skipIf( not exactly_one_yubikey_present(), "Exactly one YubiKey must be present." ) class TestInterfaces(DestructiveYubikeyTestCase): def try_connection(self, conn_type): for _ in range(8): try: conn = connect_to_device(None, [conn_type])[0] conn.close() return except Exception: sleep(0.5) self.fail("Failed connecting to device over %s" % conn_type) def test_switch_interfaces(self): self.try_connection(FidoConnection) self.try_connection(OtpConnection) self.try_connection(FidoConnection) self.try_connection(SmartCardConnection) self.try_connection(OtpConnection) self.try_connection(SmartCardConnection) self.try_connection(OtpConnection) self.try_connection(FidoConnection) self.try_connection(SmartCardConnection) self.try_connection(FidoConnection) self.try_connection(SmartCardConnection) self.try_connection(OtpConnection) ## Instruction: Test handling of reclaim timeout. ## Code After: import unittest from .framework import DestructiveYubikeyTestCase, exactly_one_yubikey_present from yubikit.core.otp import OtpConnection from yubikit.core.fido import FidoConnection from yubikit.core.smartcard import SmartCardConnection from ykman.base import YUBIKEY from ykman.device import connect_to_device from time import sleep @unittest.skipIf( not exactly_one_yubikey_present(), "Exactly one YubiKey must be present." ) class TestInterfaces(DestructiveYubikeyTestCase): def try_connection(self, conn_type): if self.key_type == YUBIKEY.NEO and conn_type == SmartCardConnection: sleep(3.5) conn, dev, info = connect_to_device(None, [conn_type]) conn.close() def setUp(self): conn, dev, info = connect_to_device() conn.close() self.key_type = dev.pid.get_type() def test_switch_interfaces(self): self.try_connection(FidoConnection) self.try_connection(OtpConnection) self.try_connection(FidoConnection) self.try_connection(SmartCardConnection) self.try_connection(OtpConnection) self.try_connection(SmartCardConnection) self.try_connection(FidoConnection)
... from yubikit.core.otp import OtpConnection from yubikit.core.fido import FidoConnection from yubikit.core.smartcard import SmartCardConnection from ykman.base import YUBIKEY from ykman.device import connect_to_device from time import sleep ... ) class TestInterfaces(DestructiveYubikeyTestCase): def try_connection(self, conn_type): if self.key_type == YUBIKEY.NEO and conn_type == SmartCardConnection: sleep(3.5) conn, dev, info = connect_to_device(None, [conn_type]) conn.close() def setUp(self): conn, dev, info = connect_to_device() conn.close() self.key_type = dev.pid.get_type() def test_switch_interfaces(self): self.try_connection(FidoConnection) ... self.try_connection(SmartCardConnection) self.try_connection(OtpConnection) self.try_connection(SmartCardConnection) self.try_connection(FidoConnection) ...
5d9fa1838ffe7ffedb59453a0eca520b5f8d5849
pyscf/ci/__init__.py
pyscf/ci/__init__.py
from pyscf.ci.cisd import CISD
from pyscf.ci import cisd def CISD(mf, frozen=[], mo_coeff=None, mo_occ=None): from pyscf import scf if isinstance(mf, (scf.uhf.UHF, scf.rohf.ROHF)): raise NotImplementedError('RO-CISD, UCISD are not available in this pyscf version') return cisd.CISD(mf, frozen, mo_coeff, mo_occ)
Revert accidental changes to ci
Revert accidental changes to ci
Python
apache-2.0
gkc1000/pyscf,gkc1000/pyscf,gkc1000/pyscf,sunqm/pyscf,sunqm/pyscf,sunqm/pyscf,gkc1000/pyscf,gkc1000/pyscf,sunqm/pyscf
python
## Code Before: from pyscf.ci.cisd import CISD ## Instruction: Revert accidental changes to ci ## Code After: from pyscf.ci import cisd def CISD(mf, frozen=[], mo_coeff=None, mo_occ=None): from pyscf import scf if isinstance(mf, (scf.uhf.UHF, scf.rohf.ROHF)): raise NotImplementedError('RO-CISD, UCISD are not available in this pyscf version') return cisd.CISD(mf, frozen, mo_coeff, mo_occ)
... from pyscf.ci import cisd def CISD(mf, frozen=[], mo_coeff=None, mo_occ=None): from pyscf import scf if isinstance(mf, (scf.uhf.UHF, scf.rohf.ROHF)): raise NotImplementedError('RO-CISD, UCISD are not available in this pyscf version') return cisd.CISD(mf, frozen, mo_coeff, mo_occ) ...
004345f50edd4c4b08727efaf5de7ee60f1f1e48
caffe2/python/operator_test/softplus_op_test.py
caffe2/python/operator_test/softplus_op_test.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import unittest class TestSoftplus(hu.HypothesisTestCase): @given(X=hu.tensor(), **hu.gcs) def test_softplus(self, X, gc, dc): op = core.CreateOperator("Softplus", ["X"], ["Y"]) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=0.0005) if __name__ == "__main__": unittest.main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import unittest class TestSoftplus(hu.HypothesisTestCase): @given(X=hu.tensor(), **hu.gcs) def test_softplus(self, X, gc, dc): op = core.CreateOperator("Softplus", ["X"], ["Y"]) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) if __name__ == "__main__": unittest.main()
Fix gradient checking for softplus op
Fix gradient checking for softplus op Summary: kmatzen why did you set the stepsize in https://github.com/caffe2/caffe2/commit/ff84e7dea6e118710859d62a7207c06b87ae992e? The test is flaky before this change. Solid afterwards. Closes https://github.com/caffe2/caffe2/pull/841 Differential Revision: D5292112 Pulled By: akyrola fbshipit-source-id: c84715261194ff047606d4ec659b7f89dac3cbb1
Python
apache-2.0
sf-wind/caffe2,xzturn/caffe2,sf-wind/caffe2,pietern/caffe2,sf-wind/caffe2,xzturn/caffe2,Yangqing/caffe2,Yangqing/caffe2,davinwang/caffe2,sf-wind/caffe2,xzturn/caffe2,pietern/caffe2,bwasti/caffe2,sf-wind/caffe2,bwasti/caffe2,davinwang/caffe2,davinwang/caffe2,xzturn/caffe2,pietern/caffe2,pietern/caffe2,davinwang/caffe2,Yangqing/caffe2,Yangqing/caffe2,bwasti/caffe2,bwasti/caffe2,xzturn/caffe2,pietern/caffe2,caffe2/caffe2,davinwang/caffe2,Yangqing/caffe2,bwasti/caffe2
python
## Code Before: from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import unittest class TestSoftplus(hu.HypothesisTestCase): @given(X=hu.tensor(), **hu.gcs) def test_softplus(self, X, gc, dc): op = core.CreateOperator("Softplus", ["X"], ["Y"]) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0], stepsize=0.0005) if __name__ == "__main__": unittest.main() ## Instruction: Fix gradient checking for softplus op Summary: kmatzen why did you set the stepsize in https://github.com/caffe2/caffe2/commit/ff84e7dea6e118710859d62a7207c06b87ae992e? The test is flaky before this change. Solid afterwards. Closes https://github.com/caffe2/caffe2/pull/841 Differential Revision: D5292112 Pulled By: akyrola fbshipit-source-id: c84715261194ff047606d4ec659b7f89dac3cbb1 ## Code After: from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import unittest class TestSoftplus(hu.HypothesisTestCase): @given(X=hu.tensor(), **hu.gcs) def test_softplus(self, X, gc, dc): op = core.CreateOperator("Softplus", ["X"], ["Y"]) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) if __name__ == "__main__": unittest.main()
... def test_softplus(self, X, gc, dc): op = core.CreateOperator("Softplus", ["X"], ["Y"]) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) if __name__ == "__main__": ...
2d78a33b4402ebaac0f680109c1c98033ac08225
src/main/java/com/github/peterpaul/fn/Container.java
src/main/java/com/github/peterpaul/fn/Container.java
package com.github.peterpaul.fn; import javax.annotation.Nonnull; import java.util.function.*; public class Container<T> extends Supplier<Option<T>> { private T value; public void set(@Nonnull T value) { this.value = value; } public void reset() { this.value = null; } @Nonnull @Override public Option<T> get() { return Option.of(value); } @Override public String toString() { return "container(" + value + ')'; } /* * Container value is mutable, so use instance hashCode. */ @Override public int hashCode() { return super.hashCode(); } /* * Container value is mutable, so use instance equality. */ @Override public boolean equals(Object o) { return super.equals(o); } }
package com.github.peterpaul.fn; import javax.annotation.Nonnull; public class Container<T> extends Supplier<Option<T>> { private T value; public void set(@Nonnull T value) { this.value = value; } public void reset() { this.value = null; } @Nonnull @Override public Option<T> get() { return Option.of(value); } @Override public String toString() { return "container(" + value + ')'; } /* * Container value is mutable, so use instance hashCode. */ @Override public int hashCode() { return super.hashCode(); } /* * Container value is mutable, so use instance equality. */ @Override public boolean equals(Object o) { return super.equals(o); } }
Remove accidental use of java8 sdk.
Remove accidental use of java8 sdk.
Java
mit
peterpaul/fn
java
## Code Before: package com.github.peterpaul.fn; import javax.annotation.Nonnull; import java.util.function.*; public class Container<T> extends Supplier<Option<T>> { private T value; public void set(@Nonnull T value) { this.value = value; } public void reset() { this.value = null; } @Nonnull @Override public Option<T> get() { return Option.of(value); } @Override public String toString() { return "container(" + value + ')'; } /* * Container value is mutable, so use instance hashCode. */ @Override public int hashCode() { return super.hashCode(); } /* * Container value is mutable, so use instance equality. */ @Override public boolean equals(Object o) { return super.equals(o); } } ## Instruction: Remove accidental use of java8 sdk. ## Code After: package com.github.peterpaul.fn; import javax.annotation.Nonnull; public class Container<T> extends Supplier<Option<T>> { private T value; public void set(@Nonnull T value) { this.value = value; } public void reset() { this.value = null; } @Nonnull @Override public Option<T> get() { return Option.of(value); } @Override public String toString() { return "container(" + value + ')'; } /* * Container value is mutable, so use instance hashCode. */ @Override public int hashCode() { return super.hashCode(); } /* * Container value is mutable, so use instance equality. */ @Override public boolean equals(Object o) { return super.equals(o); } }
... package com.github.peterpaul.fn; import javax.annotation.Nonnull; public class Container<T> extends Supplier<Option<T>> { private T value; ...
525a9fcb14a1f91aa94508ca6dcc362d430d2969
__openerp__.py
__openerp__.py
{ 'name': "Project Logical Framework", 'category': 'Project', 'sequence': 1, 'description': """ Project Logical Framework ========================= """, 'version': '0.3', 'depends': ['project'], 'data': [ 'static/src/xml/create_project.xml', ], }
{ 'name': "Project Logical Framework", 'author' : 'Stéphane Codazzi @ TeMPO-consulting', 'category': 'Project', 'sequence': 1, 'description': """ Project Logical Framework ========================= """, 'version': '0.3', 'depends': ['project'], 'data': [ 'static/src/xml/create_project.xml', ], }
Add o2m between project and logical frameworks lines
Add o2m between project and logical frameworks lines
Python
mit
stephane-/project_logical_framework
python
## Code Before: { 'name': "Project Logical Framework", 'category': 'Project', 'sequence': 1, 'description': """ Project Logical Framework ========================= """, 'version': '0.3', 'depends': ['project'], 'data': [ 'static/src/xml/create_project.xml', ], } ## Instruction: Add o2m between project and logical frameworks lines ## Code After: { 'name': "Project Logical Framework", 'author' : 'Stéphane Codazzi @ TeMPO-consulting', 'category': 'Project', 'sequence': 1, 'description': """ Project Logical Framework ========================= """, 'version': '0.3', 'depends': ['project'], 'data': [ 'static/src/xml/create_project.xml', ], }
# ... existing code ... { 'name': "Project Logical Framework", 'author' : 'Stéphane Codazzi @ TeMPO-consulting', 'category': 'Project', 'sequence': 1, 'description': """ # ... rest of the code ...
a7449b94b4171e86cd0b5260464949bc4ece7883
src/sentry/api/serializers/models/project.py
src/sentry/api/serializers/models/project.py
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMemberType, Project, Team @register(Project) class ProjectSerializer(Serializer): def get_attrs(self, item_list, user): organization = item_list[0].team.organization team_map = dict( (t.id, t) for t in Team.objects.get_for_user( organization=organization, user=user, ) ) result = {} for project in item_list: try: team = team_map[project.team_id] except KeyError: access_type = None else: access_type = team.access_type result[project] = { 'access_type': access_type, } return result def serialize(self, obj, attrs, user): from sentry import features feature_list = [] if features.has('projects:quotas', obj, actor=user): feature_list.append('quotas') if features.has('projects:user-reports', obj, actor=user): feature_list.append('user-reports') return { 'id': str(obj.id), 'slug': obj.slug, 'name': obj.name, 'isPublic': obj.public, 'dateCreated': obj.date_added, 'features': feature_list, 'permission': { 'owner': attrs['access_type'] <= OrganizationMemberType.OWNER, 'admin': attrs['access_type'] <= OrganizationMemberType.ADMIN, }, }
from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMemberType, Project, Team @register(Project) class ProjectSerializer(Serializer): def get_attrs(self, item_list, user): organization = item_list[0].team.organization team_map = dict( (t.id, t) for t in Team.objects.get_for_user( organization=organization, user=user, ) ) result = {} for project in item_list: try: team = team_map[project.team_id] except KeyError: access_type = None else: access_type = team.access_type result[project] = { 'access_type': access_type, } return result def serialize(self, obj, attrs, user): from sentry import features feature_list = [] if features.has('projects:quotas', obj, actor=user): feature_list.append('quotas') if features.has('projects:user-reports', obj, actor=user): feature_list.append('user-reports') return { 'id': str(obj.id), 'slug': obj.slug, 'name': obj.name, 'isPublic': obj.public, 'dateCreated': obj.date_added, 'firstEvent': obj.first_event, 'features': feature_list, 'permission': { 'owner': attrs['access_type'] <= OrganizationMemberType.OWNER, 'admin': attrs['access_type'] <= OrganizationMemberType.ADMIN, }, }
Add Project.first_event to API serializer
Add Project.first_event to API serializer
Python
bsd-3-clause
mvaled/sentry,fotinakis/sentry,JamesMura/sentry,mvaled/sentry,BuildingLink/sentry,imankulov/sentry,JackDanger/sentry,looker/sentry,zenefits/sentry,daevaorn/sentry,nicholasserra/sentry,looker/sentry,JamesMura/sentry,mitsuhiko/sentry,looker/sentry,nicholasserra/sentry,nicholasserra/sentry,BuildingLink/sentry,JackDanger/sentry,zenefits/sentry,ifduyue/sentry,ifduyue/sentry,BayanGroup/sentry,daevaorn/sentry,fotinakis/sentry,gencer/sentry,daevaorn/sentry,JamesMura/sentry,JamesMura/sentry,gencer/sentry,alexm92/sentry,mvaled/sentry,zenefits/sentry,beeftornado/sentry,zenefits/sentry,fotinakis/sentry,gencer/sentry,imankulov/sentry,BayanGroup/sentry,jean/sentry,gencer/sentry,zenefits/sentry,gencer/sentry,mvaled/sentry,alexm92/sentry,ifduyue/sentry,fotinakis/sentry,BuildingLink/sentry,ifduyue/sentry,looker/sentry,BuildingLink/sentry,BayanGroup/sentry,jean/sentry,looker/sentry,BuildingLink/sentry,mitsuhiko/sentry,JamesMura/sentry,jean/sentry,imankulov/sentry,mvaled/sentry,ifduyue/sentry,mvaled/sentry,jean/sentry,jean/sentry,beeftornado/sentry,JackDanger/sentry,daevaorn/sentry,beeftornado/sentry,alexm92/sentry
python
## Code Before: from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMemberType, Project, Team @register(Project) class ProjectSerializer(Serializer): def get_attrs(self, item_list, user): organization = item_list[0].team.organization team_map = dict( (t.id, t) for t in Team.objects.get_for_user( organization=organization, user=user, ) ) result = {} for project in item_list: try: team = team_map[project.team_id] except KeyError: access_type = None else: access_type = team.access_type result[project] = { 'access_type': access_type, } return result def serialize(self, obj, attrs, user): from sentry import features feature_list = [] if features.has('projects:quotas', obj, actor=user): feature_list.append('quotas') if features.has('projects:user-reports', obj, actor=user): feature_list.append('user-reports') return { 'id': str(obj.id), 'slug': obj.slug, 'name': obj.name, 'isPublic': obj.public, 'dateCreated': obj.date_added, 'features': feature_list, 'permission': { 'owner': attrs['access_type'] <= OrganizationMemberType.OWNER, 'admin': attrs['access_type'] <= OrganizationMemberType.ADMIN, }, } ## Instruction: Add Project.first_event to API serializer ## Code After: from __future__ import absolute_import from sentry.api.serializers import Serializer, register from sentry.models import OrganizationMemberType, Project, Team @register(Project) class ProjectSerializer(Serializer): def get_attrs(self, item_list, user): organization = item_list[0].team.organization team_map = dict( (t.id, t) for t in Team.objects.get_for_user( organization=organization, user=user, ) ) result = {} for project in item_list: try: team = team_map[project.team_id] except KeyError: access_type = None else: access_type = team.access_type result[project] = { 'access_type': access_type, } return result def serialize(self, obj, attrs, user): from sentry import features feature_list = [] if features.has('projects:quotas', obj, actor=user): feature_list.append('quotas') if features.has('projects:user-reports', obj, actor=user): feature_list.append('user-reports') return { 'id': str(obj.id), 'slug': obj.slug, 'name': obj.name, 'isPublic': obj.public, 'dateCreated': obj.date_added, 'firstEvent': obj.first_event, 'features': feature_list, 'permission': { 'owner': attrs['access_type'] <= OrganizationMemberType.OWNER, 'admin': attrs['access_type'] <= OrganizationMemberType.ADMIN, }, }
... 'name': obj.name, 'isPublic': obj.public, 'dateCreated': obj.date_added, 'firstEvent': obj.first_event, 'features': feature_list, 'permission': { 'owner': attrs['access_type'] <= OrganizationMemberType.OWNER, ...
27c766d6417d952589d4e05213ad86aaa7528448
src/org/bouncycastle/crypto/params/GOST3410ValidationParameters.java
src/org/bouncycastle/crypto/params/GOST3410ValidationParameters.java
package org.bouncycastle.crypto.params; public class GOST3410ValidationParameters { private int x0; private int c; private long x0L; private long cL; public GOST3410ValidationParameters( int x0, int c) { this.x0 = x0; this.c = c; } public GOST3410ValidationParameters( long x0L, long cL) { this.x0L = x0L; this.cL = cL; } public int getC() { return c; } public int getX0() { return x0; } public long getCL() { return cL; } public long getX0L() { return x0L; } public boolean equals( Object o) { if (!(o instanceof GOST3410ValidationParameters)) { return false; } GOST3410ValidationParameters other = (GOST3410ValidationParameters)o; if (other.c != this.c) { return false; } if (other.x0 != this.x0) { return false; } if (other.cL != this.cL) { return false; } if (other.x0L != this.x0L) { return false; } return true; } }
package org.bouncycastle.crypto.params; public class GOST3410ValidationParameters { private int x0; private int c; private long x0L; private long cL; public GOST3410ValidationParameters( int x0, int c) { this.x0 = x0; this.c = c; } public GOST3410ValidationParameters( long x0L, long cL) { this.x0L = x0L; this.cL = cL; } public int getC() { return c; } public int getX0() { return x0; } public long getCL() { return cL; } public long getX0L() { return x0L; } public boolean equals( Object o) { if (!(o instanceof GOST3410ValidationParameters)) { return false; } GOST3410ValidationParameters other = (GOST3410ValidationParameters)o; if (other.c != this.c) { return false; } if (other.x0 != this.x0) { return false; } if (other.cL != this.cL) { return false; } if (other.x0L != this.x0L) { return false; } return true; } public int hashCode() { return x0 ^ c ^ (int) x0L ^ (int)(x0L >> 32) ^ (int) cL ^ (int)(cL >> 32); } }
Implement hashCode() corresponding to the equals() implementation
Implement hashCode() corresponding to the equals() implementation
Java
mit
sake/bouncycastle-java
java
## Code Before: package org.bouncycastle.crypto.params; public class GOST3410ValidationParameters { private int x0; private int c; private long x0L; private long cL; public GOST3410ValidationParameters( int x0, int c) { this.x0 = x0; this.c = c; } public GOST3410ValidationParameters( long x0L, long cL) { this.x0L = x0L; this.cL = cL; } public int getC() { return c; } public int getX0() { return x0; } public long getCL() { return cL; } public long getX0L() { return x0L; } public boolean equals( Object o) { if (!(o instanceof GOST3410ValidationParameters)) { return false; } GOST3410ValidationParameters other = (GOST3410ValidationParameters)o; if (other.c != this.c) { return false; } if (other.x0 != this.x0) { return false; } if (other.cL != this.cL) { return false; } if (other.x0L != this.x0L) { return false; } return true; } } ## Instruction: Implement hashCode() corresponding to the equals() implementation ## Code After: package org.bouncycastle.crypto.params; public class GOST3410ValidationParameters { private int x0; private int c; private long x0L; private long cL; public GOST3410ValidationParameters( int x0, int c) { this.x0 = x0; this.c = c; } public GOST3410ValidationParameters( long x0L, long cL) { this.x0L = x0L; this.cL = cL; } public int getC() { return c; } public int getX0() { return x0; } public long getCL() { return cL; } public long getX0L() { return x0L; } public boolean equals( Object o) { if (!(o instanceof GOST3410ValidationParameters)) { return false; } GOST3410ValidationParameters other = (GOST3410ValidationParameters)o; if (other.c != this.c) { return false; } if (other.x0 != this.x0) { return false; } if (other.cL != this.cL) { return false; } if (other.x0L != this.x0L) { return false; } return true; } public int hashCode() { return x0 ^ c ^ (int) x0L ^ (int)(x0L >> 32) ^ (int) cL ^ (int)(cL >> 32); } }
# ... existing code ... return true; } public int hashCode() { return x0 ^ c ^ (int) x0L ^ (int)(x0L >> 32) ^ (int) cL ^ (int)(cL >> 32); } } # ... rest of the code ...
0da4c663e8a48bb759a140ca304ce35d3a8b5dcf
pyconde/events/templatetags/event_tags.py
pyconde/events/templatetags/event_tags.py
import datetime from django import template from .. import models register = template.Library() @register.inclusion_tag('events/tags/list_events.html') def list_events(number_of_events=3): now = datetime.datetime.now() events = models.Event.objects.filter(date__gte=now).all()[:number_of_events] has_range = False for evt in events: if evt.end_date: has_range = True break return { 'events': events, 'has_range': has_range }
from django import template from .. import models register = template.Library() @register.inclusion_tag('events/tags/list_events.html') def list_events(number_of_events=None): events = models.Event.objects.all() if number_of_events is not None: events = events[:number_of_events] has_range = False for evt in events: if evt.end_date: has_range = True break return { 'events': events, 'has_range': has_range }
Remove future-restriction on list_events tag
Remove future-restriction on list_events tag
Python
bsd-3-clause
zerok/pyconde-website-mirror,EuroPython/djep,EuroPython/djep,EuroPython/djep,pysv/djep,pysv/djep,EuroPython/djep,zerok/pyconde-website-mirror,pysv/djep,pysv/djep,pysv/djep,zerok/pyconde-website-mirror
python
## Code Before: import datetime from django import template from .. import models register = template.Library() @register.inclusion_tag('events/tags/list_events.html') def list_events(number_of_events=3): now = datetime.datetime.now() events = models.Event.objects.filter(date__gte=now).all()[:number_of_events] has_range = False for evt in events: if evt.end_date: has_range = True break return { 'events': events, 'has_range': has_range } ## Instruction: Remove future-restriction on list_events tag ## Code After: from django import template from .. import models register = template.Library() @register.inclusion_tag('events/tags/list_events.html') def list_events(number_of_events=None): events = models.Event.objects.all() if number_of_events is not None: events = events[:number_of_events] has_range = False for evt in events: if evt.end_date: has_range = True break return { 'events': events, 'has_range': has_range }
// ... existing code ... from django import template from .. import models // ... modified code ... @register.inclusion_tag('events/tags/list_events.html') def list_events(number_of_events=None): events = models.Event.objects.all() if number_of_events is not None: events = events[:number_of_events] has_range = False for evt in events: if evt.end_date: // ... rest of the code ...
3023c01a0d6243e2dc1cbfb1469a5e55ce5a9fc5
ResultsWizard2/src/mathsquared/resultswizard2/EventResultsEditorDialog.java
ResultsWizard2/src/mathsquared/resultswizard2/EventResultsEditorDialog.java
package mathsquared.resultswizard2; import javax.swing.JDialog; /** * Runs the GUI by which an event administrator can input or edit {@link EventResults}. * * @author MathSquared * */ public class EventResultsEditorDialog extends JDialog { /** * Create the dialog. */ public EventResultsEditorDialog () { setBounds(100, 100, 450, 300); } }
package mathsquared.resultswizard2; import javax.swing.JDialog; /** * Runs the GUI by which an event administrator can input or edit {@link EventResults}. * * @author MathSquared * */ public class EventResultsEditorDialog extends JDialog { /** * Create the dialog. */ public EventResultsEditorDialog () { setTitle("Edit Event Results"); setBounds(100, 100, 450, 300); } }
Add a title to ERED
Add a title to ERED
Java
mit
MathSquared/ResultsWizard2
java
## Code Before: package mathsquared.resultswizard2; import javax.swing.JDialog; /** * Runs the GUI by which an event administrator can input or edit {@link EventResults}. * * @author MathSquared * */ public class EventResultsEditorDialog extends JDialog { /** * Create the dialog. */ public EventResultsEditorDialog () { setBounds(100, 100, 450, 300); } } ## Instruction: Add a title to ERED ## Code After: package mathsquared.resultswizard2; import javax.swing.JDialog; /** * Runs the GUI by which an event administrator can input or edit {@link EventResults}. * * @author MathSquared * */ public class EventResultsEditorDialog extends JDialog { /** * Create the dialog. */ public EventResultsEditorDialog () { setTitle("Edit Event Results"); setBounds(100, 100, 450, 300); } }
// ... existing code ... * Create the dialog. */ public EventResultsEditorDialog () { setTitle("Edit Event Results"); setBounds(100, 100, 450, 300); } // ... rest of the code ...
106833059bc2dad8a284de50e153bf673d2e3b4b
premis_event_service/urls.py
premis_event_service/urls.py
from django.conf.urls.defaults import * urlpatterns = patterns( 'premis_event_service.views', # begin CODA Family url structure > (r'^APP/$', 'app'), # node urls # (r'^APP/node/$', 'node'), # (r'^APP/node/(?P<identifier>.+?)/$', 'node'), # event urls (r'^APP/event/$', 'app_event'), (r'^APP/event/(?P<identifier>.+?)/$', 'app_event'), # agent urls (r'^APP/agent/$', 'app_agent'), (r'^APP/agent/(?P<identifier>.+?)/$', 'app_agent'), # html view urls (r'^event/$', 'recent_event_list'), (r'^event/search/$', 'event_search'), (r'^event/search.json$', 'json_event_search'), (r'^event/find/(?P<linked_identifier>.+?)/(?P<event_type>.+?)?/$', 'findEvent'), (r'^event/(?P<identifier>.+?)/$', 'humanEvent'), (r'^agent/$', 'humanAgent'), (r'^agent/(?P<identifier>.+?).xml$', 'agentXML'), (r'^agent/(?P<identifier>.+?).premis.xml$', 'agentXML'), (r'^agent/(?P<identifier>.+?).json$', 'json_agent'), (r'^agent/(?P<identifier>.+?)/$', 'humanAgent'), )
try: from django.conf.urls import patterns, url except ImportError: from django.conf.urls.defaults import * # In case of Django<=1.3 urlpatterns = patterns( 'premis_event_service.views', # begin CODA Family url structure > (r'^APP/$', 'app'), # node urls # (r'^APP/node/$', 'node'), # (r'^APP/node/(?P<identifier>.+?)/$', 'node'), # event urls (r'^APP/event/$', 'app_event'), (r'^APP/event/(?P<identifier>.+?)/$', 'app_event'), # agent urls (r'^APP/agent/$', 'app_agent'), (r'^APP/agent/(?P<identifier>.+?)/$', 'app_agent'), # html view urls (r'^event/$', 'recent_event_list'), (r'^event/search/$', 'event_search'), (r'^event/search.json$', 'json_event_search'), (r'^event/find/(?P<linked_identifier>.+?)/(?P<event_type>.+?)?/$', 'findEvent'), (r'^event/(?P<identifier>.+?)/$', 'humanEvent'), (r'^agent/$', 'humanAgent'), (r'^agent/(?P<identifier>.+?).xml$', 'agentXML'), (r'^agent/(?P<identifier>.+?).premis.xml$', 'agentXML'), (r'^agent/(?P<identifier>.+?).json$', 'json_agent'), (r'^agent/(?P<identifier>.+?)/$', 'humanAgent'), )
Support new and old Django urlconf imports
Support new and old Django urlconf imports
Python
bsd-3-clause
unt-libraries/django-premis-event-service,unt-libraries/django-premis-event-service,unt-libraries/django-premis-event-service
python
## Code Before: from django.conf.urls.defaults import * urlpatterns = patterns( 'premis_event_service.views', # begin CODA Family url structure > (r'^APP/$', 'app'), # node urls # (r'^APP/node/$', 'node'), # (r'^APP/node/(?P<identifier>.+?)/$', 'node'), # event urls (r'^APP/event/$', 'app_event'), (r'^APP/event/(?P<identifier>.+?)/$', 'app_event'), # agent urls (r'^APP/agent/$', 'app_agent'), (r'^APP/agent/(?P<identifier>.+?)/$', 'app_agent'), # html view urls (r'^event/$', 'recent_event_list'), (r'^event/search/$', 'event_search'), (r'^event/search.json$', 'json_event_search'), (r'^event/find/(?P<linked_identifier>.+?)/(?P<event_type>.+?)?/$', 'findEvent'), (r'^event/(?P<identifier>.+?)/$', 'humanEvent'), (r'^agent/$', 'humanAgent'), (r'^agent/(?P<identifier>.+?).xml$', 'agentXML'), (r'^agent/(?P<identifier>.+?).premis.xml$', 'agentXML'), (r'^agent/(?P<identifier>.+?).json$', 'json_agent'), (r'^agent/(?P<identifier>.+?)/$', 'humanAgent'), ) ## Instruction: Support new and old Django urlconf imports ## Code After: try: from django.conf.urls import patterns, url except ImportError: from django.conf.urls.defaults import * # In case of Django<=1.3 urlpatterns = patterns( 'premis_event_service.views', # begin CODA Family url structure > (r'^APP/$', 'app'), # node urls # (r'^APP/node/$', 'node'), # (r'^APP/node/(?P<identifier>.+?)/$', 'node'), # event urls (r'^APP/event/$', 'app_event'), (r'^APP/event/(?P<identifier>.+?)/$', 'app_event'), # agent urls (r'^APP/agent/$', 'app_agent'), (r'^APP/agent/(?P<identifier>.+?)/$', 'app_agent'), # html view urls (r'^event/$', 'recent_event_list'), (r'^event/search/$', 'event_search'), (r'^event/search.json$', 'json_event_search'), (r'^event/find/(?P<linked_identifier>.+?)/(?P<event_type>.+?)?/$', 'findEvent'), (r'^event/(?P<identifier>.+?)/$', 'humanEvent'), (r'^agent/$', 'humanAgent'), (r'^agent/(?P<identifier>.+?).xml$', 'agentXML'), (r'^agent/(?P<identifier>.+?).premis.xml$', 'agentXML'), (r'^agent/(?P<identifier>.+?).json$', 'json_agent'), (r'^agent/(?P<identifier>.+?)/$', 'humanAgent'), )
# ... existing code ... try: from django.conf.urls import patterns, url except ImportError: from django.conf.urls.defaults import * # In case of Django<=1.3 urlpatterns = patterns( 'premis_event_service.views', # ... rest of the code ...
53332dd8eae28e9a42ea213b8b3d482f09135ce3
setup.py
setup.py
import sys from setuptools import setup requires = ['six'] tests_require = ['mock', 'nose'] if sys.version_info[0] == 2: requires += ['python-dateutil>=1.0, != 2.0'] else: # Py3k requires += ['python-dateutil>=2.0'] with open('README.rst') as f: readme = f.read() setup( name='freezegun', version='0.3.10', description='Let your Python tests travel through time', long_desciption=readme, author='Steve Pulec', author_email='[email protected]', url='https://github.com/spulec/freezegun', packages=['freezegun'], install_requires=requires, tests_require=tests_require, include_package_data=True, license='Apache 2.0', classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
import sys from setuptools import setup requires = ['six'] tests_require = ['mock', 'nose'] if sys.version_info[0] == 2: requires += ['python-dateutil>=1.0, != 2.0'] else: # Py3k requires += ['python-dateutil>=2.0'] with open('README.rst') as f: readme = f.read() setup( name='freezegun', version='0.3.10', description='Let your Python tests travel through time', long_desciption=readme, author='Steve Pulec', author_email='[email protected]', url='https://github.com/spulec/freezegun', packages=['freezegun'], install_requires=requires, tests_require=tests_require, include_package_data=True, license='Apache 2.0', python_requires='>=2.6, !=3.0.*, !=3.1.*, !=3.2.*', classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
Add python_requires to help pip
Add python_requires to help pip
Python
apache-2.0
spulec/freezegun
python
## Code Before: import sys from setuptools import setup requires = ['six'] tests_require = ['mock', 'nose'] if sys.version_info[0] == 2: requires += ['python-dateutil>=1.0, != 2.0'] else: # Py3k requires += ['python-dateutil>=2.0'] with open('README.rst') as f: readme = f.read() setup( name='freezegun', version='0.3.10', description='Let your Python tests travel through time', long_desciption=readme, author='Steve Pulec', author_email='[email protected]', url='https://github.com/spulec/freezegun', packages=['freezegun'], install_requires=requires, tests_require=tests_require, include_package_data=True, license='Apache 2.0', classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], ) ## Instruction: Add python_requires to help pip ## Code After: import sys from setuptools import setup requires = ['six'] tests_require = ['mock', 'nose'] if sys.version_info[0] == 2: requires += ['python-dateutil>=1.0, != 2.0'] else: # Py3k requires += ['python-dateutil>=2.0'] with open('README.rst') as f: readme = f.read() setup( name='freezegun', version='0.3.10', description='Let your Python tests travel through time', long_desciption=readme, author='Steve Pulec', author_email='[email protected]', url='https://github.com/spulec/freezegun', packages=['freezegun'], install_requires=requires, tests_require=tests_require, include_package_data=True, license='Apache 2.0', python_requires='>=2.6, !=3.0.*, !=3.1.*, !=3.2.*', classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], )
# ... existing code ... tests_require=tests_require, include_package_data=True, license='Apache 2.0', python_requires='>=2.6, !=3.0.*, !=3.1.*, !=3.2.*', classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 2', # ... rest of the code ...
49580b5215f68bdff3428cee2ed257c83dcd1351
digdag-cli/src/main/java/io/digdag/cli/client/ShowProjects.java
digdag-cli/src/main/java/io/digdag/cli/client/ShowProjects.java
package io.digdag.cli.client; import io.digdag.cli.SystemExitException; import io.digdag.client.DigdagClient; import io.digdag.client.api.RestProject; import io.digdag.client.api.RestProjectCollection; import static io.digdag.cli.SystemExitException.systemExit; public class ShowProjects extends ClientCommand { @Override public void mainWithClientException() throws Exception { DigdagClient client = buildClient(); RestProjectCollection projects = client.getProjects(); for (RestProject proj : projects.getProjects()) { ln(proj.getName()); ln(" id: " + proj.getId()); ln(" revision: " + proj.getRevision()); ln(" archive type: " + proj.getArchiveType()); ln(" project created at: " + proj.getCreatedAt()); ln(" revision updated at: " + proj.getUpdatedAt()); ln(""); } err.println("Use `" + programName + " workflows <project-name>` to show details."); } public SystemExitException usage(String error) { err.println("Usage: " + programName + " projects"); showCommonOptions(); return systemExit(error); } }
package io.digdag.cli.client; import io.digdag.cli.SystemExitException; import io.digdag.cli.TimeUtil; import io.digdag.client.DigdagClient; import io.digdag.client.api.RestProject; import io.digdag.client.api.RestProjectCollection; import static io.digdag.cli.SystemExitException.systemExit; public class ShowProjects extends ClientCommand { @Override public void mainWithClientException() throws Exception { DigdagClient client = buildClient(); RestProjectCollection projects = client.getProjects(); ln("Projects"); for (RestProject proj : projects.getProjects()) { ln(" name: %s", proj.getName()); ln(" id: %s", proj.getId()); ln(" revision: %s", proj.getRevision()); ln(" archive type: %s", proj.getArchiveType()); ln(" project created at: %s", TimeUtil.formatTime(proj.getCreatedAt())); ln(" revision updated at: %s", TimeUtil.formatTime(proj.getUpdatedAt())); ln(""); } err.println("Use `" + programName + " workflows <project-name>` to show details."); } public SystemExitException usage(String error) { err.println("Usage: " + programName + " projects"); showCommonOptions(); return systemExit(error); } }
Change output format like digdag sessions
Change output format like digdag sessions
Java
apache-2.0
treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag
java
## Code Before: package io.digdag.cli.client; import io.digdag.cli.SystemExitException; import io.digdag.client.DigdagClient; import io.digdag.client.api.RestProject; import io.digdag.client.api.RestProjectCollection; import static io.digdag.cli.SystemExitException.systemExit; public class ShowProjects extends ClientCommand { @Override public void mainWithClientException() throws Exception { DigdagClient client = buildClient(); RestProjectCollection projects = client.getProjects(); for (RestProject proj : projects.getProjects()) { ln(proj.getName()); ln(" id: " + proj.getId()); ln(" revision: " + proj.getRevision()); ln(" archive type: " + proj.getArchiveType()); ln(" project created at: " + proj.getCreatedAt()); ln(" revision updated at: " + proj.getUpdatedAt()); ln(""); } err.println("Use `" + programName + " workflows <project-name>` to show details."); } public SystemExitException usage(String error) { err.println("Usage: " + programName + " projects"); showCommonOptions(); return systemExit(error); } } ## Instruction: Change output format like digdag sessions ## Code After: package io.digdag.cli.client; import io.digdag.cli.SystemExitException; import io.digdag.cli.TimeUtil; import io.digdag.client.DigdagClient; import io.digdag.client.api.RestProject; import io.digdag.client.api.RestProjectCollection; import static io.digdag.cli.SystemExitException.systemExit; public class ShowProjects extends ClientCommand { @Override public void mainWithClientException() throws Exception { DigdagClient client = buildClient(); RestProjectCollection projects = client.getProjects(); ln("Projects"); for (RestProject proj : projects.getProjects()) { ln(" name: %s", proj.getName()); ln(" id: %s", proj.getId()); ln(" revision: %s", proj.getRevision()); ln(" archive type: %s", proj.getArchiveType()); ln(" project created at: %s", TimeUtil.formatTime(proj.getCreatedAt())); ln(" revision updated at: %s", TimeUtil.formatTime(proj.getUpdatedAt())); ln(""); } err.println("Use `" + programName + " workflows <project-name>` to show details."); } public SystemExitException usage(String error) { err.println("Usage: " + programName + " projects"); showCommonOptions(); return systemExit(error); } }
... package io.digdag.cli.client; import io.digdag.cli.SystemExitException; import io.digdag.cli.TimeUtil; import io.digdag.client.DigdagClient; import io.digdag.client.api.RestProject; import io.digdag.client.api.RestProjectCollection; ... DigdagClient client = buildClient(); RestProjectCollection projects = client.getProjects(); ln("Projects"); for (RestProject proj : projects.getProjects()) { ln(" name: %s", proj.getName()); ln(" id: %s", proj.getId()); ln(" revision: %s", proj.getRevision()); ln(" archive type: %s", proj.getArchiveType()); ln(" project created at: %s", TimeUtil.formatTime(proj.getCreatedAt())); ln(" revision updated at: %s", TimeUtil.formatTime(proj.getUpdatedAt())); ln(""); } err.println("Use `" + programName + " workflows <project-name>` to show details."); ...
109fc84cb307083f6a01317bb5b5bea0578088d3
bloop/__init__.py
bloop/__init__.py
from bloop.engine import Engine, ObjectsNotFound, ConstraintViolation from bloop.column import Column, GlobalSecondaryIndex, LocalSecondaryIndex from bloop.types import ( String, Float, Integer, Binary, StringSet, FloatSet, IntegerSet, BinarySet, Null, Boolean, Map, List ) __all__ = [ "Engine", "ObjectsNotFound", "ConstraintViolation", "Column", "GlobalSecondaryIndex", "LocalSecondaryIndex", "String", "Float", "Integer", "Binary", "StringSet", "FloatSet", "IntegerSet", "BinarySet", "Null", "Boolean", "Map", "List" ]
from bloop.engine import Engine, ObjectsNotFound, ConstraintViolation from bloop.column import Column, GlobalSecondaryIndex, LocalSecondaryIndex from bloop.types import ( String, UUID, Float, Integer, Binary, StringSet, FloatSet, IntegerSet, BinarySet, Null, Boolean, Map, List ) __all__ = [ "Engine", "ObjectsNotFound", "ConstraintViolation", "Column", "GlobalSecondaryIndex", "LocalSecondaryIndex", "String", "UUID", "Float", "Integer", "Binary", "StringSet", "FloatSet", "IntegerSet", "BinarySet", "Null", "Boolean", "Map", "List" ]
Add UUID to bloop __all__
Add UUID to bloop __all__
Python
mit
numberoverzero/bloop,numberoverzero/bloop
python
## Code Before: from bloop.engine import Engine, ObjectsNotFound, ConstraintViolation from bloop.column import Column, GlobalSecondaryIndex, LocalSecondaryIndex from bloop.types import ( String, Float, Integer, Binary, StringSet, FloatSet, IntegerSet, BinarySet, Null, Boolean, Map, List ) __all__ = [ "Engine", "ObjectsNotFound", "ConstraintViolation", "Column", "GlobalSecondaryIndex", "LocalSecondaryIndex", "String", "Float", "Integer", "Binary", "StringSet", "FloatSet", "IntegerSet", "BinarySet", "Null", "Boolean", "Map", "List" ] ## Instruction: Add UUID to bloop __all__ ## Code After: from bloop.engine import Engine, ObjectsNotFound, ConstraintViolation from bloop.column import Column, GlobalSecondaryIndex, LocalSecondaryIndex from bloop.types import ( String, UUID, Float, Integer, Binary, StringSet, FloatSet, IntegerSet, BinarySet, Null, Boolean, Map, List ) __all__ = [ "Engine", "ObjectsNotFound", "ConstraintViolation", "Column", "GlobalSecondaryIndex", "LocalSecondaryIndex", "String", "UUID", "Float", "Integer", "Binary", "StringSet", "FloatSet", "IntegerSet", "BinarySet", "Null", "Boolean", "Map", "List" ]
# ... existing code ... from bloop.engine import Engine, ObjectsNotFound, ConstraintViolation from bloop.column import Column, GlobalSecondaryIndex, LocalSecondaryIndex from bloop.types import ( String, UUID, Float, Integer, Binary, StringSet, FloatSet, IntegerSet, BinarySet, Null, Boolean, Map, List ) # ... modified code ... __all__ = [ "Engine", "ObjectsNotFound", "ConstraintViolation", "Column", "GlobalSecondaryIndex", "LocalSecondaryIndex", "String", "UUID", "Float", "Integer", "Binary", "StringSet", "FloatSet", "IntegerSet", "BinarySet", "Null", "Boolean", "Map", "List" ] # ... rest of the code ...
5a310285c6e528555136a95221b628827d04cb81
l10n_br_base/__init__.py
l10n_br_base/__init__.py
from . import models from . import tests
from . import models from . import tests from odoo.addons import account from odoo import api, SUPERUSER_ID # Install Simple Chart of Account Template for Brazilian Companies _auto_install_l10n_original = account._auto_install_l10n def _auto_install_l10n_br_simple(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) country_code = env.user.company_id.country_id.code if country_code and country_code.upper() == "BR": module_ids = env["ir.module.module"].search( [("name", "in", ("l10n_br_simple",)), ("state", "=", "uninstalled")] ) module_ids.sudo().button_install() else: _auto_install_l10n_original(cr, registry) account._auto_install_l10n = _auto_install_l10n_br_simple
Define l10n_br_simple as default COA for brazilian companies
Define l10n_br_simple as default COA for brazilian companies
Python
agpl-3.0
akretion/l10n-brazil,akretion/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil
python
## Code Before: from . import models from . import tests ## Instruction: Define l10n_br_simple as default COA for brazilian companies ## Code After: from . import models from . import tests from odoo.addons import account from odoo import api, SUPERUSER_ID # Install Simple Chart of Account Template for Brazilian Companies _auto_install_l10n_original = account._auto_install_l10n def _auto_install_l10n_br_simple(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) country_code = env.user.company_id.country_id.code if country_code and country_code.upper() == "BR": module_ids = env["ir.module.module"].search( [("name", "in", ("l10n_br_simple",)), ("state", "=", "uninstalled")] ) module_ids.sudo().button_install() else: _auto_install_l10n_original(cr, registry) account._auto_install_l10n = _auto_install_l10n_br_simple
... from . import models from . import tests from odoo.addons import account from odoo import api, SUPERUSER_ID # Install Simple Chart of Account Template for Brazilian Companies _auto_install_l10n_original = account._auto_install_l10n def _auto_install_l10n_br_simple(cr, registry): env = api.Environment(cr, SUPERUSER_ID, {}) country_code = env.user.company_id.country_id.code if country_code and country_code.upper() == "BR": module_ids = env["ir.module.module"].search( [("name", "in", ("l10n_br_simple",)), ("state", "=", "uninstalled")] ) module_ids.sudo().button_install() else: _auto_install_l10n_original(cr, registry) account._auto_install_l10n = _auto_install_l10n_br_simple ...
03dee283f0cdbf917d2ff3cbee3fbe45e0b0e430
setup.py
setup.py
from setuptools import setup, find_packages setup( name='aweber_api', version='1.1.3', packages=find_packages(exclude=['tests']), url='https://github.com/aweber/AWeber-API-Python-Library', install_requires = [ 'httplib2>=0.7.0', 'oauth2>=1.2', ], tests_require = [ 'dingus', 'coverage', ], setup_requires = [ 'nose', ], include_package_data=True )
from setuptools import setup, find_packages from sys import version if version < '2.2.3': from distutils.dist import DistributionMetadata DistributionMetadata.classifiers = None DistributionMetadata.download_url = None setup( name='aweber_api', version='1.1.3', author='AWeber Dev Team', author_email='[email protected]', maintainer='AWeber API Team', maintainer_email='[email protected]', url='https://github.com/aweber/AWeber-API-Python-Library', download_url='http://pypi.python.org/pypi/aweber_api', description='The AWeber API Python Library allows you to quickly get up ' 'and running with integrating access to the AWeber API into your ' 'Python applications.', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Environment :: Web Environment', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: BSD License', ], packages=find_packages(exclude=['tests']), install_requires=[ 'httplib2>=0.7.0', 'oauth2>=1.2', ], tests_require=[ 'dingus', 'coverage', ], setup_requires=[ 'nose', ], include_package_data=True )
Update metadata used by pypi
Update metadata used by pypi
Python
bsd-3-clause
aweber/AWeber-API-Python-Library
python
## Code Before: from setuptools import setup, find_packages setup( name='aweber_api', version='1.1.3', packages=find_packages(exclude=['tests']), url='https://github.com/aweber/AWeber-API-Python-Library', install_requires = [ 'httplib2>=0.7.0', 'oauth2>=1.2', ], tests_require = [ 'dingus', 'coverage', ], setup_requires = [ 'nose', ], include_package_data=True ) ## Instruction: Update metadata used by pypi ## Code After: from setuptools import setup, find_packages from sys import version if version < '2.2.3': from distutils.dist import DistributionMetadata DistributionMetadata.classifiers = None DistributionMetadata.download_url = None setup( name='aweber_api', version='1.1.3', author='AWeber Dev Team', author_email='[email protected]', maintainer='AWeber API Team', maintainer_email='[email protected]', url='https://github.com/aweber/AWeber-API-Python-Library', download_url='http://pypi.python.org/pypi/aweber_api', description='The AWeber API Python Library allows you to quickly get up ' 'and running with integrating access to the AWeber API into your ' 'Python applications.', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Environment :: Web Environment', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: BSD License', ], packages=find_packages(exclude=['tests']), install_requires=[ 'httplib2>=0.7.0', 'oauth2>=1.2', ], tests_require=[ 'dingus', 'coverage', ], setup_requires=[ 'nose', ], include_package_data=True )
... from setuptools import setup, find_packages from sys import version if version < '2.2.3': from distutils.dist import DistributionMetadata DistributionMetadata.classifiers = None DistributionMetadata.download_url = None setup( name='aweber_api', version='1.1.3', author='AWeber Dev Team', author_email='[email protected]', maintainer='AWeber API Team', maintainer_email='[email protected]', url='https://github.com/aweber/AWeber-API-Python-Library', download_url='http://pypi.python.org/pypi/aweber_api', description='The AWeber API Python Library allows you to quickly get up ' 'and running with integrating access to the AWeber API into your ' 'Python applications.', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Environment :: Web Environment', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: BSD License', ], packages=find_packages(exclude=['tests']), install_requires=[ 'httplib2>=0.7.0', 'oauth2>=1.2', ], tests_require=[ 'dingus', 'coverage', ], setup_requires=[ 'nose', ], include_package_data=True ) ...
17627ac4677f49e805f14acb4ba768b74d43298a
py3-test/tests.py
py3-test/tests.py
import nose.tools as nt from asyncio import Future, gather, get_event_loop, sleep from pyee import EventEmitter def test_async_emit(): """Test that event_emitters can handle wrapping coroutines """ loop = get_event_loop() ee = EventEmitter(loop=loop) should_call = Future(loop=loop) @ee.on('event') async def event_handler(): should_call.set_result(True) async def create_timeout(loop=loop): await sleep(1, loop=loop) if not should_call.done(): raise Exception('should_call timed out!') return should_call.cancel() timeout = create_timeout(loop=loop) @should_call.add_done_callback def _done(result): nt.assert_true(result) ee.emit('event') loop.run_until_complete(gather(should_call, timeout))
import nose.tools as nt from asyncio import Future, gather, new_event_loop, sleep from pyee import EventEmitter def test_async_emit(): """Test that event_emitters can handle wrapping coroutines """ loop = new_event_loop() ee = EventEmitter(loop=loop) should_call = Future(loop=loop) @ee.on('event') async def event_handler(): should_call.set_result(True) async def create_timeout(loop=loop): await sleep(1, loop=loop) if not should_call.done(): raise Exception('should_call timed out!') return should_call.cancel() timeout = create_timeout(loop=loop) @should_call.add_done_callback def _done(result): nt.assert_true(result) ee.emit('event') loop.run_until_complete(gather(should_call, timeout, loop=loop))
Use fresh event loop for asyncio test
Use fresh event loop for asyncio test
Python
mit
jfhbrook/pyee
python
## Code Before: import nose.tools as nt from asyncio import Future, gather, get_event_loop, sleep from pyee import EventEmitter def test_async_emit(): """Test that event_emitters can handle wrapping coroutines """ loop = get_event_loop() ee = EventEmitter(loop=loop) should_call = Future(loop=loop) @ee.on('event') async def event_handler(): should_call.set_result(True) async def create_timeout(loop=loop): await sleep(1, loop=loop) if not should_call.done(): raise Exception('should_call timed out!') return should_call.cancel() timeout = create_timeout(loop=loop) @should_call.add_done_callback def _done(result): nt.assert_true(result) ee.emit('event') loop.run_until_complete(gather(should_call, timeout)) ## Instruction: Use fresh event loop for asyncio test ## Code After: import nose.tools as nt from asyncio import Future, gather, new_event_loop, sleep from pyee import EventEmitter def test_async_emit(): """Test that event_emitters can handle wrapping coroutines """ loop = new_event_loop() ee = EventEmitter(loop=loop) should_call = Future(loop=loop) @ee.on('event') async def event_handler(): should_call.set_result(True) async def create_timeout(loop=loop): await sleep(1, loop=loop) if not should_call.done(): raise Exception('should_call timed out!') return should_call.cancel() timeout = create_timeout(loop=loop) @should_call.add_done_callback def _done(result): nt.assert_true(result) ee.emit('event') loop.run_until_complete(gather(should_call, timeout, loop=loop))
... import nose.tools as nt from asyncio import Future, gather, new_event_loop, sleep from pyee import EventEmitter ... def test_async_emit(): """Test that event_emitters can handle wrapping coroutines """ loop = new_event_loop() ee = EventEmitter(loop=loop) should_call = Future(loop=loop) ... ee.emit('event') loop.run_until_complete(gather(should_call, timeout, loop=loop)) ...
0e48b2130cc53caa9beb9a5f8ce09edbcc40f1b8
ggplotx/tests/test_geom_point.py
ggplotx/tests/test_geom_point.py
from __future__ import absolute_import, division, print_function import pandas as pd from ggplotx import ggplot, aes, geom_point def test_aesthetics(): df = pd.DataFrame({ 'a': range(5), 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9 }) p = (ggplot(df, aes(y='a')) + geom_point(aes(x='b')) + geom_point(aes(x='c', size='a')) + geom_point(aes(x='d', alpha='a'), size=10, show_legend=False) + geom_point(aes(x='e', shape='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='f', color='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='g', fill='a'), stroke=0, size=10, show_legend=False) + geom_point(aes(x='h', stroke='a'), fill='white', color='green', size=10) + geom_point(aes(x='i', shape='factor(a)'), fill='brown', stroke=2, size=10, show_legend=False)) assert p == 'aesthetics'
from __future__ import absolute_import, division, print_function import pandas as pd from ggplotx import ggplot, aes, geom_point, theme def test_aesthetics(): df = pd.DataFrame({ 'a': range(5), 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9 }) p = (ggplot(df, aes(y='a')) + geom_point(aes(x='b')) + geom_point(aes(x='c', size='a')) + geom_point(aes(x='d', alpha='a'), size=10, show_legend=False) + geom_point(aes(x='e', shape='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='f', color='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='g', fill='a'), stroke=0, size=10, show_legend=False) + geom_point(aes(x='h', stroke='a'), fill='white', color='green', size=10) + geom_point(aes(x='i', shape='factor(a)'), fill='brown', stroke=2, size=10, show_legend=False) + theme(facet_spacing={'right': 0.85})) assert p == 'aesthetics'
Add space on the RHS of geom_point test
Add space on the RHS of geom_point test
Python
mit
has2k1/plotnine,has2k1/plotnine
python
## Code Before: from __future__ import absolute_import, division, print_function import pandas as pd from ggplotx import ggplot, aes, geom_point def test_aesthetics(): df = pd.DataFrame({ 'a': range(5), 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9 }) p = (ggplot(df, aes(y='a')) + geom_point(aes(x='b')) + geom_point(aes(x='c', size='a')) + geom_point(aes(x='d', alpha='a'), size=10, show_legend=False) + geom_point(aes(x='e', shape='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='f', color='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='g', fill='a'), stroke=0, size=10, show_legend=False) + geom_point(aes(x='h', stroke='a'), fill='white', color='green', size=10) + geom_point(aes(x='i', shape='factor(a)'), fill='brown', stroke=2, size=10, show_legend=False)) assert p == 'aesthetics' ## Instruction: Add space on the RHS of geom_point test ## Code After: from __future__ import absolute_import, division, print_function import pandas as pd from ggplotx import ggplot, aes, geom_point, theme def test_aesthetics(): df = pd.DataFrame({ 'a': range(5), 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9 }) p = (ggplot(df, aes(y='a')) + geom_point(aes(x='b')) + geom_point(aes(x='c', size='a')) + geom_point(aes(x='d', alpha='a'), size=10, show_legend=False) + geom_point(aes(x='e', shape='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='f', color='factor(a)'), size=10, show_legend=False) + geom_point(aes(x='g', fill='a'), stroke=0, size=10, show_legend=False) + geom_point(aes(x='h', stroke='a'), fill='white', color='green', size=10) + geom_point(aes(x='i', shape='factor(a)'), fill='brown', stroke=2, size=10, show_legend=False) + theme(facet_spacing={'right': 0.85})) assert p == 'aesthetics'
// ... existing code ... import pandas as pd from ggplotx import ggplot, aes, geom_point, theme def test_aesthetics(): // ... modified code ... geom_point(aes(x='h', stroke='a'), fill='white', color='green', size=10) + geom_point(aes(x='i', shape='factor(a)'), fill='brown', stroke=2, size=10, show_legend=False) + theme(facet_spacing={'right': 0.85})) assert p == 'aesthetics' // ... rest of the code ...
133bddf28eed38273eeb384b152ec35ae861a480
sunpy/__init__.py
sunpy/__init__.py
from __future__ import absolute_import try: from .version import version as __version__ except ImportError: __version__ = '' try: from .version import githash as __githash__ except ImportError: __githash__ = '' import os from sunpy.util.config import load_config, print_config from sunpy.util import system_info from sunpy.tests.runner import SunPyTestRunner self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__)) # Load user configuration config = load_config() __all__ = ['config', 'self_test', 'system_info']
from __future__ import absolute_import try: from .version import version as __version__ except ImportError: __version__ = '' try: from .version import githash as __githash__ except ImportError: __githash__ = '' try: _ASTROPY_SETUP_ except NameError: _ASTROPY_SETUP_ = False if not _ASTROPY_SETUP_: import os from sunpy.util.config import load_config, print_config from sunpy.util import system_info from sunpy.tests.runner import SunPyTestRunner self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__)) # Load user configuration config = load_config() __all__ = ['config', 'self_test', 'system_info']
Make sure package does not import itself during setup
Make sure package does not import itself during setup
Python
bsd-2-clause
dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy
python
## Code Before: from __future__ import absolute_import try: from .version import version as __version__ except ImportError: __version__ = '' try: from .version import githash as __githash__ except ImportError: __githash__ = '' import os from sunpy.util.config import load_config, print_config from sunpy.util import system_info from sunpy.tests.runner import SunPyTestRunner self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__)) # Load user configuration config = load_config() __all__ = ['config', 'self_test', 'system_info'] ## Instruction: Make sure package does not import itself during setup ## Code After: from __future__ import absolute_import try: from .version import version as __version__ except ImportError: __version__ = '' try: from .version import githash as __githash__ except ImportError: __githash__ = '' try: _ASTROPY_SETUP_ except NameError: _ASTROPY_SETUP_ = False if not _ASTROPY_SETUP_: import os from sunpy.util.config import load_config, print_config from sunpy.util import system_info from sunpy.tests.runner import SunPyTestRunner self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__)) # Load user configuration config = load_config() __all__ = ['config', 'self_test', 'system_info']
// ... existing code ... except ImportError: __githash__ = '' try: _ASTROPY_SETUP_ except NameError: _ASTROPY_SETUP_ = False if not _ASTROPY_SETUP_: import os from sunpy.util.config import load_config, print_config from sunpy.util import system_info from sunpy.tests.runner import SunPyTestRunner self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__)) # Load user configuration config = load_config() __all__ = ['config', 'self_test', 'system_info'] // ... rest of the code ...
d8e9201c627840c72a540a77425ec0c13ac48a22
tests/test_cmd.py
tests/test_cmd.py
import unittest from click.testing import CliRunner from scuevals_api.cmd import cli class CmdsTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.runner = CliRunner() def cli_run(self, *cmds): return self.runner.invoke(cli, cmds) cls.cli_run = cli_run def test_initdb(self): result = self.cli_run('initdb') self.assertEqual(0, result.exit_code)
import unittest from click.testing import CliRunner from scuevals_api.cmd import cli class CmdsTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.runner = CliRunner() def cli_run(self, *cmds): return self.runner.invoke(cli, cmds) cls.cli_run = cli_run def test_initdb(self): result = self.cli_run('initdb') self.assertEqual(0, result.exit_code, msg=result.output)
Add detailed error for CLI test failure
Add detailed error for CLI test failure
Python
agpl-3.0
SCUEvals/scuevals-api,SCUEvals/scuevals-api
python
## Code Before: import unittest from click.testing import CliRunner from scuevals_api.cmd import cli class CmdsTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.runner = CliRunner() def cli_run(self, *cmds): return self.runner.invoke(cli, cmds) cls.cli_run = cli_run def test_initdb(self): result = self.cli_run('initdb') self.assertEqual(0, result.exit_code) ## Instruction: Add detailed error for CLI test failure ## Code After: import unittest from click.testing import CliRunner from scuevals_api.cmd import cli class CmdsTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.runner = CliRunner() def cli_run(self, *cmds): return self.runner.invoke(cli, cmds) cls.cli_run = cli_run def test_initdb(self): result = self.cli_run('initdb') self.assertEqual(0, result.exit_code, msg=result.output)
# ... existing code ... def test_initdb(self): result = self.cli_run('initdb') self.assertEqual(0, result.exit_code, msg=result.output) # ... rest of the code ...
a835e62e608714541135f90a26f46e919e3e52aa
2018/clone/clone-vm-sample.c
2018/clone/clone-vm-sample.c
// We have to define the _GNU_SOURCE to get access to clone(2) and the CLONE_* // flags from sched.h #define _GNU_SOURCE #include <sched.h> #include <sys/syscall.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static int child_func(void* arg) { char* buf = (char*)arg; strcpy(buf, "hello"); return 0; } int main(int argc, char** argv) { // Allocate stack for child task. const int STACK_SIZE = 65536; char* stack = malloc(STACK_SIZE); if (!stack) { perror("malloc"); exit(1); } // When called with the command-line argument "vm", set the CLONE_VM flag on. unsigned long flags = 0; if (argc > 1 && !strcmp(argv[1], "vm")) { flags |= CLONE_VM; } char buf[100] = {0}; if (clone(child_func, stack + STACK_SIZE, flags | SIGCHLD, buf) == -1) { perror("clone"); exit(1); } int status; if (wait(&status) == -1) { perror("wait"); exit(1); } printf("Child exited with status %d. buf = \"%s\"\n", status, buf); return 0; }
// We have to define the _GNU_SOURCE to get access to clone(2) and the CLONE_* // flags from sched.h #define _GNU_SOURCE #include <sched.h> #include <sys/syscall.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static int child_func(void* arg) { char* buf = (char*)arg; printf("Child sees buf = \"%s\"\n", buf); strcpy(buf, "hello from child"); return 0; } int main(int argc, char** argv) { // Allocate stack for child task. const int STACK_SIZE = 65536; char* stack = malloc(STACK_SIZE); if (!stack) { perror("malloc"); exit(1); } // When called with the command-line argument "vm", set the CLONE_VM flag on. unsigned long flags = 0; if (argc > 1 && !strcmp(argv[1], "vm")) { flags |= CLONE_VM; } char buf[100]; strcpy(buf, "hello from parent"); if (clone(child_func, stack + STACK_SIZE, flags | SIGCHLD, buf) == -1) { perror("clone"); exit(1); } int status; if (wait(&status) == -1) { perror("wait"); exit(1); } printf("Child exited with status %d. buf = \"%s\"\n", status, buf); return 0; }
Change the sample to pass message from parent as well
Change the sample to pass message from parent as well
C
unlicense
eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog
c
## Code Before: // We have to define the _GNU_SOURCE to get access to clone(2) and the CLONE_* // flags from sched.h #define _GNU_SOURCE #include <sched.h> #include <sys/syscall.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static int child_func(void* arg) { char* buf = (char*)arg; strcpy(buf, "hello"); return 0; } int main(int argc, char** argv) { // Allocate stack for child task. const int STACK_SIZE = 65536; char* stack = malloc(STACK_SIZE); if (!stack) { perror("malloc"); exit(1); } // When called with the command-line argument "vm", set the CLONE_VM flag on. unsigned long flags = 0; if (argc > 1 && !strcmp(argv[1], "vm")) { flags |= CLONE_VM; } char buf[100] = {0}; if (clone(child_func, stack + STACK_SIZE, flags | SIGCHLD, buf) == -1) { perror("clone"); exit(1); } int status; if (wait(&status) == -1) { perror("wait"); exit(1); } printf("Child exited with status %d. buf = \"%s\"\n", status, buf); return 0; } ## Instruction: Change the sample to pass message from parent as well ## Code After: // We have to define the _GNU_SOURCE to get access to clone(2) and the CLONE_* // flags from sched.h #define _GNU_SOURCE #include <sched.h> #include <sys/syscall.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static int child_func(void* arg) { char* buf = (char*)arg; printf("Child sees buf = \"%s\"\n", buf); strcpy(buf, "hello from child"); return 0; } int main(int argc, char** argv) { // Allocate stack for child task. const int STACK_SIZE = 65536; char* stack = malloc(STACK_SIZE); if (!stack) { perror("malloc"); exit(1); } // When called with the command-line argument "vm", set the CLONE_VM flag on. unsigned long flags = 0; if (argc > 1 && !strcmp(argv[1], "vm")) { flags |= CLONE_VM; } char buf[100]; strcpy(buf, "hello from parent"); if (clone(child_func, stack + STACK_SIZE, flags | SIGCHLD, buf) == -1) { perror("clone"); exit(1); } int status; if (wait(&status) == -1) { perror("wait"); exit(1); } printf("Child exited with status %d. buf = \"%s\"\n", status, buf); return 0; }
# ... existing code ... static int child_func(void* arg) { char* buf = (char*)arg; printf("Child sees buf = \"%s\"\n", buf); strcpy(buf, "hello from child"); return 0; } # ... modified code ... flags |= CLONE_VM; } char buf[100]; strcpy(buf, "hello from parent"); if (clone(child_func, stack + STACK_SIZE, flags | SIGCHLD, buf) == -1) { perror("clone"); exit(1); # ... rest of the code ...
a248a2479fe8c4ad31d9b4535319cb39cf801d7f
src/main/kotlin/com/jgreubel/TreelineApplication.kt
src/main/kotlin/com/jgreubel/TreelineApplication.kt
package com.jgreubel import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication open class TreelineApplication fun main(args: Array<String>) { SpringApplication.run(TreelineApplication::class.java, *args) }
package com.jgreubel import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication open class TreelineApplication fun main(args: Array<String>) { val app = SpringApplication.run(TreelineApplication::class.java, *args) println("local server port: " + app.environment.getProperty("local.server.port")) println("server port" + app.environment.getProperty("server.port")) }
Print server port on app launch
Print server port on app launch [#29]
Kotlin
mit
Jgreub/treeline,Jgreub/treeline,Jgreub/treeline,Jgreub/treeline
kotlin
## Code Before: package com.jgreubel import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication open class TreelineApplication fun main(args: Array<String>) { SpringApplication.run(TreelineApplication::class.java, *args) } ## Instruction: Print server port on app launch [#29] ## Code After: package com.jgreubel import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication open class TreelineApplication fun main(args: Array<String>) { val app = SpringApplication.run(TreelineApplication::class.java, *args) println("local server port: " + app.environment.getProperty("local.server.port")) println("server port" + app.environment.getProperty("server.port")) }
// ... existing code ... open class TreelineApplication fun main(args: Array<String>) { val app = SpringApplication.run(TreelineApplication::class.java, *args) println("local server port: " + app.environment.getProperty("local.server.port")) println("server port" + app.environment.getProperty("server.port")) } // ... rest of the code ...
2eae88ca423a60579e9b8572b0d4bcecbe2d8631
utils/HTTPResponseParser.py
utils/HTTPResponseParser.py
from StringIO import StringIO from httplib import HTTPResponse class FakeSocket(StringIO): def makefile(self, *args, **kw): return self def parse_http_response(sock): try: # H4ck to standardize the API between sockets and SSLConnection objects # sock is a Python socket sock.read = sock.recv except AttributeError: # sock is an SSLConnection pass response = sock.read(4096) if 'HTTP/' not in response: # Try to get the rest of the response response += sock.read(4096) fake_sock = FakeSocket(response) response = HTTPResponse(fake_sock) response.begin() return response
from StringIO import StringIO from httplib import HTTPResponse class FakeSocket(StringIO): def makefile(self, *args, **kw): return self def parse_http_response(sock): try: # H4ck to standardize the API between sockets and SSLConnection objects response = sock.read(4096) except AttributeError: response = sock.recv(4096) if 'HTTP/' not in response: # Try to get the rest of the response try: response += sock.read(4096) except AttributeError: response += sock.recv(4096) fake_sock = FakeSocket(response) response = HTTPResponse(fake_sock) response.begin() return response
Tweak the hack to fix bug when scanning through a proxy
Tweak the hack to fix bug when scanning through a proxy
Python
agpl-3.0
nabla-c0d3/sslyze
python
## Code Before: from StringIO import StringIO from httplib import HTTPResponse class FakeSocket(StringIO): def makefile(self, *args, **kw): return self def parse_http_response(sock): try: # H4ck to standardize the API between sockets and SSLConnection objects # sock is a Python socket sock.read = sock.recv except AttributeError: # sock is an SSLConnection pass response = sock.read(4096) if 'HTTP/' not in response: # Try to get the rest of the response response += sock.read(4096) fake_sock = FakeSocket(response) response = HTTPResponse(fake_sock) response.begin() return response ## Instruction: Tweak the hack to fix bug when scanning through a proxy ## Code After: from StringIO import StringIO from httplib import HTTPResponse class FakeSocket(StringIO): def makefile(self, *args, **kw): return self def parse_http_response(sock): try: # H4ck to standardize the API between sockets and SSLConnection objects response = sock.read(4096) except AttributeError: response = sock.recv(4096) if 'HTTP/' not in response: # Try to get the rest of the response try: response += sock.read(4096) except AttributeError: response += sock.recv(4096) fake_sock = FakeSocket(response) response = HTTPResponse(fake_sock) response.begin() return response
# ... existing code ... try: # H4ck to standardize the API between sockets and SSLConnection objects response = sock.read(4096) except AttributeError: response = sock.recv(4096) if 'HTTP/' not in response: # Try to get the rest of the response try: response += sock.read(4096) except AttributeError: response += sock.recv(4096) fake_sock = FakeSocket(response) response = HTTPResponse(fake_sock) # ... rest of the code ...
5dc2ee040b5de973233ea04a310f7b6b3b0b9de9
mangacork/__init__.py
mangacork/__init__.py
import logging from flask import Flask log = logging.getLogger(__name__) app = Flask(__name__) import mangacork.views
import os import logging from flask import Flask log = logging.getLogger(__name__) app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) import mangacork.views
Add config for different env
Add config for different env
Python
mit
ma3lstrom/manga-cork,ma3lstrom/manga-cork,ma3lstrom/manga-cork
python
## Code Before: import logging from flask import Flask log = logging.getLogger(__name__) app = Flask(__name__) import mangacork.views ## Instruction: Add config for different env ## Code After: import os import logging from flask import Flask log = logging.getLogger(__name__) app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) import mangacork.views
// ... existing code ... import os import logging from flask import Flask // ... modified code ... log = logging.getLogger(__name__) app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) import mangacork.views // ... rest of the code ...
ea046e8996c3bbad95578ef3209b62972d88e720
opps/images/widgets.py
opps/images/widgets.py
from django import forms from django.conf import settings from django.template.loader import render_to_string class MultipleUpload(forms.FileInput): def render(self, name, value, attrs=None): _value = "" if value: _value = "{0}{1}".format(settings.MEDIA_URL, value) return render_to_string("admin/opps/images/multiupload.html", {"name": name, "value": _value, "STATIC_URL": settings.STATIC_URL}) class CropExample(forms.TextInput): def render(self, name, value, attrs=None): return render_to_string( "admin/opps/images/cropexample.html", {"name": name, "value": value, 'STATIC_URL': settings.STATIC_URL, "THUMBOR_SERVER": settings.THUMBOR_SERVER, "THUMBOR_MEDIA_URL": settings.THUMBOR_MEDIA_URL})
from django import forms from django.conf import settings from django.template.loader import render_to_string class MultipleUpload(forms.FileInput): def render(self, name, value, attrs=None): _value = "" _height = "" _width = "" if value: _value = "{0}{1}".format(settings.MEDIA_URL, value) _height = value.height _width = value.width return render_to_string("admin/opps/images/multiupload.html", {"name": name, "value": _value, 'height': _height, 'width': _width, "STATIC_URL": settings.STATIC_URL}) class CropExample(forms.TextInput): def render(self, name, value, attrs=None): return render_to_string( "admin/opps/images/cropexample.html", {"name": name, "value": value, 'STATIC_URL': settings.STATIC_URL, "THUMBOR_SERVER": settings.THUMBOR_SERVER, "THUMBOR_MEDIA_URL": settings.THUMBOR_MEDIA_URL})
Add _height/_width on widget MultipleUpload
Add _height/_width on widget MultipleUpload
Python
mit
jeanmask/opps,YACOWS/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,opps/opps,williamroot/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,opps/opps
python
## Code Before: from django import forms from django.conf import settings from django.template.loader import render_to_string class MultipleUpload(forms.FileInput): def render(self, name, value, attrs=None): _value = "" if value: _value = "{0}{1}".format(settings.MEDIA_URL, value) return render_to_string("admin/opps/images/multiupload.html", {"name": name, "value": _value, "STATIC_URL": settings.STATIC_URL}) class CropExample(forms.TextInput): def render(self, name, value, attrs=None): return render_to_string( "admin/opps/images/cropexample.html", {"name": name, "value": value, 'STATIC_URL': settings.STATIC_URL, "THUMBOR_SERVER": settings.THUMBOR_SERVER, "THUMBOR_MEDIA_URL": settings.THUMBOR_MEDIA_URL}) ## Instruction: Add _height/_width on widget MultipleUpload ## Code After: from django import forms from django.conf import settings from django.template.loader import render_to_string class MultipleUpload(forms.FileInput): def render(self, name, value, attrs=None): _value = "" _height = "" _width = "" if value: _value = "{0}{1}".format(settings.MEDIA_URL, value) _height = value.height _width = value.width return render_to_string("admin/opps/images/multiupload.html", {"name": name, "value": _value, 'height': _height, 'width': _width, "STATIC_URL": settings.STATIC_URL}) class CropExample(forms.TextInput): def render(self, name, value, attrs=None): return render_to_string( "admin/opps/images/cropexample.html", {"name": name, "value": value, 'STATIC_URL': settings.STATIC_URL, "THUMBOR_SERVER": settings.THUMBOR_SERVER, "THUMBOR_MEDIA_URL": settings.THUMBOR_MEDIA_URL})
// ... existing code ... class MultipleUpload(forms.FileInput): def render(self, name, value, attrs=None): _value = "" _height = "" _width = "" if value: _value = "{0}{1}".format(settings.MEDIA_URL, value) _height = value.height _width = value.width return render_to_string("admin/opps/images/multiupload.html", {"name": name, "value": _value, 'height': _height, 'width': _width, "STATIC_URL": settings.STATIC_URL}) // ... rest of the code ...
d3f0d83b0c783d2f15a6f5eaf6fd4ace426307a6
tests/__init__.py
tests/__init__.py
import os import sys import unittest def suite(): MODULE_DIR = os.path.join(os.path.dirname(__file__), '..') MODULE_DIR = os.path.abspath(MODULE_DIR) sys.path.insert(0, MODULE_DIR) sys.path.insert(0, os.path.dirname(__file__)) SUB_UNITS = os.path.dirname(__file__) SUB_UNITS = os.listdir(SUB_UNITS) SUB_UNITS = [ filename[:-3] for filename in SUB_UNITS if filename.startswith('test_') ] os.chdir(os.path.dirname(__file__)) loader = unittest.TestLoader() return loader.loadTestsFromNames(SUB_UNITS)
from os import walk, chdir from os.path import join, dirname, splitext, abspath, relpath import sys import unittest MODULE_DIR = join(dirname(__file__), '..') MODULE_DIR = abspath(MODULE_DIR) def walker(opath='.'): for path, folders, files in walk(opath): for filename in files: if filename.startswith('test_') and filename.endswith('.py'): rpath = relpath(path, opath) yield (rpath + '.' + splitext(filename)[0]).strip('.') def suite(): sys.path.insert(0, MODULE_DIR) sys.path.insert(0, dirname(__file__)) SUB_UNITS = dirname(__file__) SUB_UNITS = walker(SUB_UNITS) chdir(dirname(__file__)) return unittest.TestLoader().loadTestsFromNames(SUB_UNITS)
Rework for tests in subdirectories
Rework for tests in subdirectories
Python
mit
Mause/pytransperth,Mause/pytransperth
python
## Code Before: import os import sys import unittest def suite(): MODULE_DIR = os.path.join(os.path.dirname(__file__), '..') MODULE_DIR = os.path.abspath(MODULE_DIR) sys.path.insert(0, MODULE_DIR) sys.path.insert(0, os.path.dirname(__file__)) SUB_UNITS = os.path.dirname(__file__) SUB_UNITS = os.listdir(SUB_UNITS) SUB_UNITS = [ filename[:-3] for filename in SUB_UNITS if filename.startswith('test_') ] os.chdir(os.path.dirname(__file__)) loader = unittest.TestLoader() return loader.loadTestsFromNames(SUB_UNITS) ## Instruction: Rework for tests in subdirectories ## Code After: from os import walk, chdir from os.path import join, dirname, splitext, abspath, relpath import sys import unittest MODULE_DIR = join(dirname(__file__), '..') MODULE_DIR = abspath(MODULE_DIR) def walker(opath='.'): for path, folders, files in walk(opath): for filename in files: if filename.startswith('test_') and filename.endswith('.py'): rpath = relpath(path, opath) yield (rpath + '.' + splitext(filename)[0]).strip('.') def suite(): sys.path.insert(0, MODULE_DIR) sys.path.insert(0, dirname(__file__)) SUB_UNITS = dirname(__file__) SUB_UNITS = walker(SUB_UNITS) chdir(dirname(__file__)) return unittest.TestLoader().loadTestsFromNames(SUB_UNITS)
# ... existing code ... from os import walk, chdir from os.path import join, dirname, splitext, abspath, relpath import sys import unittest MODULE_DIR = join(dirname(__file__), '..') MODULE_DIR = abspath(MODULE_DIR) def walker(opath='.'): for path, folders, files in walk(opath): for filename in files: if filename.startswith('test_') and filename.endswith('.py'): rpath = relpath(path, opath) yield (rpath + '.' + splitext(filename)[0]).strip('.') def suite(): sys.path.insert(0, MODULE_DIR) sys.path.insert(0, dirname(__file__)) SUB_UNITS = dirname(__file__) SUB_UNITS = walker(SUB_UNITS) chdir(dirname(__file__)) return unittest.TestLoader().loadTestsFromNames(SUB_UNITS) # ... rest of the code ...
dd45649d55a60797d3d8b4fe665862df0cbf6a79
examples/c/plcdemos.h
examples/c/plcdemos.h
/* $Id$ Everything needed by the C demo programs. Created to avoid junking up plplot.h with this stuff. */ #ifndef __PLCDEMOS_H__ #define __PLCDEMOS_H__ #include "plConfig.h" #include "plplot.h" #include <math.h> #include <string.h> #include <ctype.h> /* define PI if not defined by math.h */ /* Actually M_PI seems to be more widely used so we deprecate PI. */ #ifndef PI #define PI 3.1415926535897932384 #endif #ifndef M_PI #define M_PI 3.1415926535897932384 #endif /* various utility macros */ #ifndef MAX #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #endif #ifndef MIN #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #endif #ifndef ROUND #define ROUND(a) (PLINT)((a)<0. ? ((a)-.5) : ((a)+.5)) #endif #endif /* __PLCDEMOS_H__ */
/* $Id$ Everything needed by the C demo programs. Created to avoid junking up plplot.h with this stuff. */ #ifndef __PLCDEMOS_H__ #define __PLCDEMOS_H__ #include <math.h> #include <string.h> #include <ctype.h> #include "plConfig.h" #include "plplot.h" /* define PI if not defined by math.h */ /* Actually M_PI seems to be more widely used so we deprecate PI. */ #ifndef PI #define PI 3.1415926535897932384 #endif #ifndef M_PI #define M_PI 3.1415926535897932384 #endif /* various utility macros */ #ifndef MAX #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #endif #ifndef MIN #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #endif #ifndef ROUND #define ROUND(a) (PLINT)((a)<0. ? ((a)-.5) : ((a)+.5)) #endif #endif /* __PLCDEMOS_H__ */
Move system header files to top in order to get rid of redefine warnings for Visual C++.
Move system header files to top in order to get rid of redefine warnings for Visual C++. svn path=/trunk/; revision=9609
C
lgpl-2.1
FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot,FreeScienceCommunity/PLPlot
c
## Code Before: /* $Id$ Everything needed by the C demo programs. Created to avoid junking up plplot.h with this stuff. */ #ifndef __PLCDEMOS_H__ #define __PLCDEMOS_H__ #include "plConfig.h" #include "plplot.h" #include <math.h> #include <string.h> #include <ctype.h> /* define PI if not defined by math.h */ /* Actually M_PI seems to be more widely used so we deprecate PI. */ #ifndef PI #define PI 3.1415926535897932384 #endif #ifndef M_PI #define M_PI 3.1415926535897932384 #endif /* various utility macros */ #ifndef MAX #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #endif #ifndef MIN #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #endif #ifndef ROUND #define ROUND(a) (PLINT)((a)<0. ? ((a)-.5) : ((a)+.5)) #endif #endif /* __PLCDEMOS_H__ */ ## Instruction: Move system header files to top in order to get rid of redefine warnings for Visual C++. svn path=/trunk/; revision=9609 ## Code After: /* $Id$ Everything needed by the C demo programs. Created to avoid junking up plplot.h with this stuff. */ #ifndef __PLCDEMOS_H__ #define __PLCDEMOS_H__ #include <math.h> #include <string.h> #include <ctype.h> #include "plConfig.h" #include "plplot.h" /* define PI if not defined by math.h */ /* Actually M_PI seems to be more widely used so we deprecate PI. */ #ifndef PI #define PI 3.1415926535897932384 #endif #ifndef M_PI #define M_PI 3.1415926535897932384 #endif /* various utility macros */ #ifndef MAX #define MAX(a,b) (((a) > (b)) ? (a) : (b)) #endif #ifndef MIN #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #endif #ifndef ROUND #define ROUND(a) (PLINT)((a)<0. ? ((a)-.5) : ((a)+.5)) #endif #endif /* __PLCDEMOS_H__ */
# ... existing code ... #ifndef __PLCDEMOS_H__ #define __PLCDEMOS_H__ #include <math.h> #include <string.h> #include <ctype.h> #include "plConfig.h" #include "plplot.h" /* define PI if not defined by math.h */ # ... rest of the code ...
704439e7ae99d215948c94a5dfa61ee1f3f57971
fireplace/cards/tgt/neutral_legendary.py
fireplace/cards/tgt/neutral_legendary.py
from ..utils import * ## # Minions # Confessor Paletress class AT_018: inspire = Summon(CONTROLLER, RandomMinion(rarity=Rarity.LEGENDARY)) # Skycap'n Kragg class AT_070: cost = lambda self, i: i - len(self.controller.field.filter(race=Race.PIRATE))
from ..utils import * ## # Minions # Confessor Paletress class AT_018: inspire = Summon(CONTROLLER, RandomMinion(rarity=Rarity.LEGENDARY)) # Skycap'n Kragg class AT_070: cost = lambda self, i: i - len(self.controller.field.filter(race=Race.PIRATE)) # Gormok the Impaler class AT_122: play = Hit(TARGET, 4) # Chillmaw class AT_123: deathrattle = HOLDING_DRAGON & Hit(ALL_MINIONS, 3) # Nexus-Champion Saraad class AT_127: inspire = Give(CONTROLLER, RandomSpell()) # The Skeleton Knight class AT_128: deathrattle = JOUST & Bounce(SELF) # Fjola Lightbane class AT_129: events = Play(CONTROLLER, SPELL, SELF).on(SetTag(SELF, {GameTag.DIVINE_SHIELD: True})) # Eydis Darkbane class AT_131: events = Play(CONTROLLER, SPELL, SELF).on(Hit(RANDOM_ENEMY_CHARACTER, 3))
Implement more TGT Neutral Legendaries
Implement more TGT Neutral Legendaries
Python
agpl-3.0
Ragowit/fireplace,liujimj/fireplace,oftc-ftw/fireplace,amw2104/fireplace,amw2104/fireplace,beheh/fireplace,smallnamespace/fireplace,smallnamespace/fireplace,NightKev/fireplace,liujimj/fireplace,oftc-ftw/fireplace,jleclanche/fireplace,Ragowit/fireplace,Meerkov/fireplace,Meerkov/fireplace
python
## Code Before: from ..utils import * ## # Minions # Confessor Paletress class AT_018: inspire = Summon(CONTROLLER, RandomMinion(rarity=Rarity.LEGENDARY)) # Skycap'n Kragg class AT_070: cost = lambda self, i: i - len(self.controller.field.filter(race=Race.PIRATE)) ## Instruction: Implement more TGT Neutral Legendaries ## Code After: from ..utils import * ## # Minions # Confessor Paletress class AT_018: inspire = Summon(CONTROLLER, RandomMinion(rarity=Rarity.LEGENDARY)) # Skycap'n Kragg class AT_070: cost = lambda self, i: i - len(self.controller.field.filter(race=Race.PIRATE)) # Gormok the Impaler class AT_122: play = Hit(TARGET, 4) # Chillmaw class AT_123: deathrattle = HOLDING_DRAGON & Hit(ALL_MINIONS, 3) # Nexus-Champion Saraad class AT_127: inspire = Give(CONTROLLER, RandomSpell()) # The Skeleton Knight class AT_128: deathrattle = JOUST & Bounce(SELF) # Fjola Lightbane class AT_129: events = Play(CONTROLLER, SPELL, SELF).on(SetTag(SELF, {GameTag.DIVINE_SHIELD: True})) # Eydis Darkbane class AT_131: events = Play(CONTROLLER, SPELL, SELF).on(Hit(RANDOM_ENEMY_CHARACTER, 3))
... # Skycap'n Kragg class AT_070: cost = lambda self, i: i - len(self.controller.field.filter(race=Race.PIRATE)) # Gormok the Impaler class AT_122: play = Hit(TARGET, 4) # Chillmaw class AT_123: deathrattle = HOLDING_DRAGON & Hit(ALL_MINIONS, 3) # Nexus-Champion Saraad class AT_127: inspire = Give(CONTROLLER, RandomSpell()) # The Skeleton Knight class AT_128: deathrattle = JOUST & Bounce(SELF) # Fjola Lightbane class AT_129: events = Play(CONTROLLER, SPELL, SELF).on(SetTag(SELF, {GameTag.DIVINE_SHIELD: True})) # Eydis Darkbane class AT_131: events = Play(CONTROLLER, SPELL, SELF).on(Hit(RANDOM_ENEMY_CHARACTER, 3)) ...
78fcadb41808b1ab9e3dae7c78d8ee5a8c2f36aa
presto-main/src/main/java/com/facebook/presto/cli/Help.java
presto-main/src/main/java/com/facebook/presto/cli/Help.java
package com.facebook.presto.cli; public final class Help { private Help() {} public static String getHelpText() { return "" + "Supported commands:\n" + "QUIT\n" + "DESCRIBE <table>\n" + "SHOW COLUMNS FROM <table>\n" + "SHOW FUNCTIONS\n" + "SHOW PARTITIONS FROM <table>\n" + "SHOW TABLES\n" + ""; } }
package com.facebook.presto.cli; public final class Help { private Help() {} public static String getHelpText() { return "" + "Supported commands:\n" + "QUIT\n" + "DESCRIBE <table>\n" + "SHOW COLUMNS FROM <table>\n" + "SHOW FUNCTIONS\n" + "SHOW PARTITIONS FROM <table>\n" + "SHOW TABLES [LIKE <pattern>]\n" + ""; } }
Add full syntax for SHOW TABLES to help
Add full syntax for SHOW TABLES to help
Java
apache-2.0
bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto,bd-dev-mobileum/presto
java
## Code Before: package com.facebook.presto.cli; public final class Help { private Help() {} public static String getHelpText() { return "" + "Supported commands:\n" + "QUIT\n" + "DESCRIBE <table>\n" + "SHOW COLUMNS FROM <table>\n" + "SHOW FUNCTIONS\n" + "SHOW PARTITIONS FROM <table>\n" + "SHOW TABLES\n" + ""; } } ## Instruction: Add full syntax for SHOW TABLES to help ## Code After: package com.facebook.presto.cli; public final class Help { private Help() {} public static String getHelpText() { return "" + "Supported commands:\n" + "QUIT\n" + "DESCRIBE <table>\n" + "SHOW COLUMNS FROM <table>\n" + "SHOW FUNCTIONS\n" + "SHOW PARTITIONS FROM <table>\n" + "SHOW TABLES [LIKE <pattern>]\n" + ""; } }
... "SHOW COLUMNS FROM <table>\n" + "SHOW FUNCTIONS\n" + "SHOW PARTITIONS FROM <table>\n" + "SHOW TABLES [LIKE <pattern>]\n" + ""; } } ...
e09af91b45355294c16249bcd3c0bf07982cd39c
websaver/parsed_data/models.py
websaver/parsed_data/models.py
from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userName
from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) solofppkd = models.CharField(max_length=5, null=True) duofppkd = models.CharField(max_length=5, null=True) squadfppkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userName
Add fpp k/d data to the model.
Add fpp k/d data to the model.
Python
mit
aiirohituzi/myWebCrawler,aiirohituzi/myWebCrawler,aiirohituzi/myWebCrawler
python
## Code Before: from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userName ## Instruction: Add fpp k/d data to the model. ## Code After: from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) solofppkd = models.CharField(max_length=5, null=True) duofppkd = models.CharField(max_length=5, null=True) squadfppkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userName
// ... existing code ... # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) solofppkd = models.CharField(max_length=5, null=True) duofppkd = models.CharField(max_length=5, null=True) squadfppkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: // ... rest of the code ...
1c5769b1fddd50e55edcce45f2e8c0b5116f4f9a
app/src/main/java/com/hewgill/android/nzsldict/BaseActivity.java
app/src/main/java/com/hewgill/android/nzsldict/BaseActivity.java
package com.hewgill.android.nzsldict; import android.content.Context; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.MenuItem; import io.github.inflationx.viewpump.ViewPumpContextWrapper; public class BaseActivity extends AppCompatActivity { protected void setupAppToolbar() { Toolbar appToolbar = (Toolbar) findViewById(R.id.app_toolbar); setSupportActionBar(appToolbar); // add back arrow to toolbar if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the toolbar's NavigationIcon as up/home button case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase)); } }
package com.hewgill.android.nzsldict; import android.content.Context; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.MenuItem; import io.github.inflationx.viewpump.ViewPumpContextWrapper; public class BaseActivity extends AppCompatActivity { protected void setupAppToolbar() { Toolbar appToolbar = (Toolbar) findViewById(R.id.app_toolbar); setSupportActionBar(appToolbar); // add back arrow to toolbar if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the toolbar's NavigationIcon as up/home button case android.R.id.home: finish(); return true; case R.id.action_vocab_sheet: startActivity(new Intent(this, VocabSheetActivity.class)); break; } return super.onOptionsItemSelected(item); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase)); } }
Add menu item handler to base activity to launch vocab sheet
Add menu item handler to base activity to launch vocab sheet
Java
mit
rabid/nzsl-dictionary-android,rabid/nzsl-dictionary-android
java
## Code Before: package com.hewgill.android.nzsldict; import android.content.Context; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.MenuItem; import io.github.inflationx.viewpump.ViewPumpContextWrapper; public class BaseActivity extends AppCompatActivity { protected void setupAppToolbar() { Toolbar appToolbar = (Toolbar) findViewById(R.id.app_toolbar); setSupportActionBar(appToolbar); // add back arrow to toolbar if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the toolbar's NavigationIcon as up/home button case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase)); } } ## Instruction: Add menu item handler to base activity to launch vocab sheet ## Code After: package com.hewgill.android.nzsldict; import android.content.Context; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.MenuItem; import io.github.inflationx.viewpump.ViewPumpContextWrapper; public class BaseActivity extends AppCompatActivity { protected void setupAppToolbar() { Toolbar appToolbar = (Toolbar) findViewById(R.id.app_toolbar); setSupportActionBar(appToolbar); // add back arrow to toolbar if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the toolbar's NavigationIcon as up/home button case android.R.id.home: finish(); return true; case R.id.action_vocab_sheet: startActivity(new Intent(this, VocabSheetActivity.class)); break; } return super.onOptionsItemSelected(item); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase)); } }
// ... existing code ... } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // ... modified code ... case android.R.id.home: finish(); return true; case R.id.action_vocab_sheet: startActivity(new Intent(this, VocabSheetActivity.class)); break; } return super.onOptionsItemSelected(item); } // ... rest of the code ...
cb7170785af4bf853ff8495aaade520d3b133332
casexml/apps/stock/admin.py
casexml/apps/stock/admin.py
from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin)
from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] search_fields = ['form_id'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] search_fields = ['case_id', 'product_id'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin)
Add search fields to stock models
Add search fields to stock models
Python
bsd-3-clause
dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,SEL-Columbia/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq
python
## Code Before: from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin) ## Instruction: Add search fields to stock models ## Code After: from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] search_fields = ['form_id'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] search_fields = ['case_id', 'product_id'] def report_date(self, obj): return obj.report.date report_date.admin_order_field = 'report__date' admin.site.register(StockReport, StockReportAdmin) admin.site.register(StockTransaction, StockTransactionAdmin)
// ... existing code ... from django.contrib import admin from .models import * class StockReportAdmin(admin.ModelAdmin): model = StockReport list_display = ['date', 'type', 'form_id'] list_filter = ['date', 'type'] search_fields = ['form_id'] class StockTransactionAdmin(admin.ModelAdmin): model = StockTransaction list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand'] list_filter = ['report__date', 'section_id', 'type', 'subtype'] search_fields = ['case_id', 'product_id'] def report_date(self, obj): return obj.report.date // ... rest of the code ...
fe442d84140b0a588c6a8490b58a10995df58f17
tests/optimizers/test_constant_optimizer.py
tests/optimizers/test_constant_optimizer.py
"""Test suite for optimizers.constant.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import ast import pytest from pycc.asttools import parse from pycc.optimizers import constant source = """ ONE = 1 TWO = 2 THREE = ONE + TWO FOUR = THREE + ONE FIVE = THREE + TWO def return_const(): return FOUR def return_var(): return FIVE FIVE = FIVE + ONE FIVE -= ONE """ @pytest.fixture def node(): """Get as AST node from the source.""" return parse.parse(source) def test_constant_inliner(node): """Test that constant values are inlined.""" constant.ConstantOptimizer()(node) # Check assignment values using constants. assert node.body[2].value.n == 3 assert node.body[3].value.n == 4 assert node.body[4].value.n == 5 # Check return val of const function. assert isinstance(node.body[5].body[0].value, ast.Num) assert node.body[5].body[0].value.n == 4 # Check return val of var function. assert isinstance(node.body[6].body[0].value, ast.Name) assert node.body[6].body[0].value.id == 'FIVE'
"""Test suite for optimizers.constant.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import ast import pytest from pycc.asttools import parse from pycc.optimizers import constant source = """ ONE = 1 TWO = 2 THREE = ONE + TWO FOUR = THREE + ONE FIVE = THREE + TWO def return_const(): return FOUR def return_var(): return FIVE FIVE = FIVE + ONE FIVE -= ONE """ @pytest.fixture def node(): """Get as AST node from the source.""" return parse.parse(source) def test_constant_inliner(node): """Test that constant values are inlined.""" constant.optimize(node) # Check assignment values using constants. assert node.body[2].value.n == 3 assert node.body[3].value.n == 4 assert node.body[4].value.n == 5 # Check return val of const function. assert isinstance(node.body[5].body[0].value, ast.Num) assert node.body[5].body[0].value.n == 4 # Check return val of var function. assert isinstance(node.body[6].body[0].value, ast.Name) assert node.body[6].body[0].value.id == 'FIVE'
Fix test to use new optimizer interface
Fix test to use new optimizer interface Signed-off-by: Kevin Conway <[email protected]>
Python
apache-2.0
kevinconway/pycc,kevinconway/pycc
python
## Code Before: """Test suite for optimizers.constant.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import ast import pytest from pycc.asttools import parse from pycc.optimizers import constant source = """ ONE = 1 TWO = 2 THREE = ONE + TWO FOUR = THREE + ONE FIVE = THREE + TWO def return_const(): return FOUR def return_var(): return FIVE FIVE = FIVE + ONE FIVE -= ONE """ @pytest.fixture def node(): """Get as AST node from the source.""" return parse.parse(source) def test_constant_inliner(node): """Test that constant values are inlined.""" constant.ConstantOptimizer()(node) # Check assignment values using constants. assert node.body[2].value.n == 3 assert node.body[3].value.n == 4 assert node.body[4].value.n == 5 # Check return val of const function. assert isinstance(node.body[5].body[0].value, ast.Num) assert node.body[5].body[0].value.n == 4 # Check return val of var function. assert isinstance(node.body[6].body[0].value, ast.Name) assert node.body[6].body[0].value.id == 'FIVE' ## Instruction: Fix test to use new optimizer interface Signed-off-by: Kevin Conway <[email protected]> ## Code After: """Test suite for optimizers.constant.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import ast import pytest from pycc.asttools import parse from pycc.optimizers import constant source = """ ONE = 1 TWO = 2 THREE = ONE + TWO FOUR = THREE + ONE FIVE = THREE + TWO def return_const(): return FOUR def return_var(): return FIVE FIVE = FIVE + ONE FIVE -= ONE """ @pytest.fixture def node(): """Get as AST node from the source.""" return parse.parse(source) def test_constant_inliner(node): """Test that constant values are inlined.""" constant.optimize(node) # Check assignment values using constants. assert node.body[2].value.n == 3 assert node.body[3].value.n == 4 assert node.body[4].value.n == 5 # Check return val of const function. assert isinstance(node.body[5].body[0].value, ast.Num) assert node.body[5].body[0].value.n == 4 # Check return val of var function. assert isinstance(node.body[6].body[0].value, ast.Name) assert node.body[6].body[0].value.id == 'FIVE'
# ... existing code ... def test_constant_inliner(node): """Test that constant values are inlined.""" constant.optimize(node) # Check assignment values using constants. assert node.body[2].value.n == 3 # ... rest of the code ...
9addb88d7d3b9067a0581cb46b048ad693bbb720
setup.py
setup.py
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'Description': 'A simple Finite Element Modeling (FEM) library', 'author': 'Greg Hamel (MrJarv1s)', 'url': 'https://github.com/MrJarv1s/FEMur', 'download_url': 'https://github.com/MrJarv1s/FEMur', 'author_email': '[email protected]', 'version': '0.1', 'install_requires': ['nose', 'numpy', 'scipy', 'sympy'], 'packages': ['FEMur'], 'scripts': [], 'name': 'FEMur', 'classifiers': [ "Development Status :: 2 - Pre-Alpha", "Environment :: Console", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python :: 3.6", "Topic :: Scientific/Engineering" ] } setup(**config)
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'Description': 'A simple Finite Element Modeling (FEM) library', 'author': 'Greg Hamel (MrJarv1s)', 'url': 'https://github.com/MrJarv1s/FEMur', 'download_url': 'https://github.com/MrJarv1s/FEMur', 'author_email': '[email protected]', 'version': '0.1', 'install_requires': ['nose', 'numpy', 'scipy', 'sympy', 'matplotlib'], 'packages': ['FEMur'], 'scripts': [], 'name': 'FEMur', 'classifiers': [ "Development Status :: 2 - Pre-Alpha", "Environment :: Console", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python :: 3.6", "Topic :: Scientific/Engineering" ] } setup(**config)
Add matplotlib as a dependency
Add matplotlib as a dependency
Python
mit
MrJarv1s/FEMur
python
## Code Before: try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'Description': 'A simple Finite Element Modeling (FEM) library', 'author': 'Greg Hamel (MrJarv1s)', 'url': 'https://github.com/MrJarv1s/FEMur', 'download_url': 'https://github.com/MrJarv1s/FEMur', 'author_email': '[email protected]', 'version': '0.1', 'install_requires': ['nose', 'numpy', 'scipy', 'sympy'], 'packages': ['FEMur'], 'scripts': [], 'name': 'FEMur', 'classifiers': [ "Development Status :: 2 - Pre-Alpha", "Environment :: Console", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python :: 3.6", "Topic :: Scientific/Engineering" ] } setup(**config) ## Instruction: Add matplotlib as a dependency ## Code After: try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'Description': 'A simple Finite Element Modeling (FEM) library', 'author': 'Greg Hamel (MrJarv1s)', 'url': 'https://github.com/MrJarv1s/FEMur', 'download_url': 'https://github.com/MrJarv1s/FEMur', 'author_email': '[email protected]', 'version': '0.1', 'install_requires': ['nose', 'numpy', 'scipy', 'sympy', 'matplotlib'], 'packages': ['FEMur'], 'scripts': [], 'name': 'FEMur', 'classifiers': [ "Development Status :: 2 - Pre-Alpha", "Environment :: Console", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python :: 3.6", "Topic :: Scientific/Engineering" ] } setup(**config)
... 'download_url': 'https://github.com/MrJarv1s/FEMur', 'author_email': '[email protected]', 'version': '0.1', 'install_requires': ['nose', 'numpy', 'scipy', 'sympy', 'matplotlib'], 'packages': ['FEMur'], 'scripts': [], 'name': 'FEMur', ...
253daeb2e826a9fe87cd93c9bc1a2060d9b8fead
tests/project/settings.py
tests/project/settings.py
DATABASES = { 'default': { 'ENGINE': 'sqlite3', 'NAME': ':memory:' } } MIDDLEWARE_CLASSES = [ 'fandjango.middleware.FacebookMiddleware' ] INSTALLED_APPS = [ 'fandjango', 'south', 'tests.project.app' ] ROOT_URLCONF = 'tests.project.urls' FACEBOOK_APPLICATION_ID = 181259711925270 FACEBOOK_APPLICATION_SECRET_KEY = '214e4cb484c28c35f18a70a3d735999b' FACEBOOK_APPLICATION_NAMESPACE = 'fandjango-test' FACEBOOK_APPLICATION_CANVAS_URL = 'http://example.org/foo'
DATABASES = { 'default': { 'ENGINE': 'sqlite3', 'NAME': ':memory:' } } MIDDLEWARE_CLASSES = [ 'fandjango.middleware.FacebookMiddleware' ] INSTALLED_APPS = [ 'fandjango', 'south', 'tests.project.app' ] SOUTH_TESTS_MIGRATE = False ROOT_URLCONF = 'tests.project.urls' FACEBOOK_APPLICATION_ID = 181259711925270 FACEBOOK_APPLICATION_SECRET_KEY = '214e4cb484c28c35f18a70a3d735999b' FACEBOOK_APPLICATION_NAMESPACE = 'fandjango-test' FACEBOOK_APPLICATION_CANVAS_URL = 'http://example.org/foo'
Disable South migrations for tests.
Disable South migrations for tests.
Python
mit
jgorset/fandjango,jgorset/fandjango
python
## Code Before: DATABASES = { 'default': { 'ENGINE': 'sqlite3', 'NAME': ':memory:' } } MIDDLEWARE_CLASSES = [ 'fandjango.middleware.FacebookMiddleware' ] INSTALLED_APPS = [ 'fandjango', 'south', 'tests.project.app' ] ROOT_URLCONF = 'tests.project.urls' FACEBOOK_APPLICATION_ID = 181259711925270 FACEBOOK_APPLICATION_SECRET_KEY = '214e4cb484c28c35f18a70a3d735999b' FACEBOOK_APPLICATION_NAMESPACE = 'fandjango-test' FACEBOOK_APPLICATION_CANVAS_URL = 'http://example.org/foo' ## Instruction: Disable South migrations for tests. ## Code After: DATABASES = { 'default': { 'ENGINE': 'sqlite3', 'NAME': ':memory:' } } MIDDLEWARE_CLASSES = [ 'fandjango.middleware.FacebookMiddleware' ] INSTALLED_APPS = [ 'fandjango', 'south', 'tests.project.app' ] SOUTH_TESTS_MIGRATE = False ROOT_URLCONF = 'tests.project.urls' FACEBOOK_APPLICATION_ID = 181259711925270 FACEBOOK_APPLICATION_SECRET_KEY = '214e4cb484c28c35f18a70a3d735999b' FACEBOOK_APPLICATION_NAMESPACE = 'fandjango-test' FACEBOOK_APPLICATION_CANVAS_URL = 'http://example.org/foo'
# ... existing code ... 'tests.project.app' ] SOUTH_TESTS_MIGRATE = False ROOT_URLCONF = 'tests.project.urls' FACEBOOK_APPLICATION_ID = 181259711925270 # ... rest of the code ...
43a515ddfbe38686672fe00d4765d3f2e1bc5346
scarlet/assets/settings.py
scarlet/assets/settings.py
from django.conf import settings # Main Assets Directory. This will be a subdirectory within MEDIA_ROOT. # Set to None to use MEDIA_ROOT directly DIRECTORY = getattr(settings, "ASSETS_DIR", 'assets') # Which size should be used as CMS thumbnail for images. CMS_THUMBNAIL_SIZE = getattr(settings, 'ASSETS_CMS_THUMBNAIL_SIZE', '80x80') # EXTRA SETTINGS # Convert Filename (UUID) HASH_FILENAME = getattr(settings, "ASSETS_HASH_FILENAME", True) # Append a qs to assets urls for cache busting USE_CACHE_BUST = getattr(settings, "ASSETS_USE_CACHE_BUST", True) ASSET_MODEL = getattr(settings, "ASSET_MODEL", "assets.Asset") ASSET_TYPES = getattr(settings, "ASSET_TYPES", None) DEFAULT_IMAGE_SIZES = { 'admin' : { 'width' : 100, 'height' : 100, 'editable': False } } IMAGE_SIZES = getattr(settings, "IMAGE_SIZES", DEFAULT_IMAGE_SIZES) IMAGE_CROPPER = '.crops.cropper' CELERY = getattr(settings, "ASSET_CELERY", None) USE_CELERY_DECORATOR = getattr(settings, "ASSET_USE_CELERY_DECORATOR", False)
from django.conf import settings # Main Assets Directory. This will be a subdirectory within MEDIA_ROOT. # Set to None to use MEDIA_ROOT directly DIRECTORY = getattr(settings, "ASSETS_DIR", 'assets') # Which size should be used as CMS thumbnail for images. CMS_THUMBNAIL_SIZE = getattr(settings, 'ASSETS_CMS_THUMBNAIL_SIZE', '80x80') # EXTRA SETTINGS # Convert Filename (UUID) HASH_FILENAME = getattr(settings, "ASSETS_HASH_FILENAME", True) # Append a qs to assets urls for cache busting USE_CACHE_BUST = getattr(settings, "ASSETS_USE_CACHE_BUST", True) ASSET_MODEL = getattr(settings, "ASSET_MODEL", "assets.Asset") ASSET_TYPES = getattr(settings, "ASSET_TYPES", None) DEFAULT_IMAGE_SIZES = { 'admin' : { 'width' : 100, 'height' : 100, 'editable': False, 'upscale': True, }, } IMAGE_SIZES = getattr(settings, "IMAGE_SIZES", DEFAULT_IMAGE_SIZES) IMAGE_CROPPER = '.crops.cropper' CELERY = getattr(settings, "ASSET_CELERY", None) USE_CELERY_DECORATOR = getattr(settings, "ASSET_USE_CELERY_DECORATOR", False)
Set upscale to True by default for admin asset
Set upscale to True by default for admin asset
Python
mit
ff0000/scarlet,ff0000/scarlet,ff0000/scarlet,ff0000/scarlet,ff0000/scarlet
python
## Code Before: from django.conf import settings # Main Assets Directory. This will be a subdirectory within MEDIA_ROOT. # Set to None to use MEDIA_ROOT directly DIRECTORY = getattr(settings, "ASSETS_DIR", 'assets') # Which size should be used as CMS thumbnail for images. CMS_THUMBNAIL_SIZE = getattr(settings, 'ASSETS_CMS_THUMBNAIL_SIZE', '80x80') # EXTRA SETTINGS # Convert Filename (UUID) HASH_FILENAME = getattr(settings, "ASSETS_HASH_FILENAME", True) # Append a qs to assets urls for cache busting USE_CACHE_BUST = getattr(settings, "ASSETS_USE_CACHE_BUST", True) ASSET_MODEL = getattr(settings, "ASSET_MODEL", "assets.Asset") ASSET_TYPES = getattr(settings, "ASSET_TYPES", None) DEFAULT_IMAGE_SIZES = { 'admin' : { 'width' : 100, 'height' : 100, 'editable': False } } IMAGE_SIZES = getattr(settings, "IMAGE_SIZES", DEFAULT_IMAGE_SIZES) IMAGE_CROPPER = '.crops.cropper' CELERY = getattr(settings, "ASSET_CELERY", None) USE_CELERY_DECORATOR = getattr(settings, "ASSET_USE_CELERY_DECORATOR", False) ## Instruction: Set upscale to True by default for admin asset ## Code After: from django.conf import settings # Main Assets Directory. This will be a subdirectory within MEDIA_ROOT. # Set to None to use MEDIA_ROOT directly DIRECTORY = getattr(settings, "ASSETS_DIR", 'assets') # Which size should be used as CMS thumbnail for images. CMS_THUMBNAIL_SIZE = getattr(settings, 'ASSETS_CMS_THUMBNAIL_SIZE', '80x80') # EXTRA SETTINGS # Convert Filename (UUID) HASH_FILENAME = getattr(settings, "ASSETS_HASH_FILENAME", True) # Append a qs to assets urls for cache busting USE_CACHE_BUST = getattr(settings, "ASSETS_USE_CACHE_BUST", True) ASSET_MODEL = getattr(settings, "ASSET_MODEL", "assets.Asset") ASSET_TYPES = getattr(settings, "ASSET_TYPES", None) DEFAULT_IMAGE_SIZES = { 'admin' : { 'width' : 100, 'height' : 100, 'editable': False, 'upscale': True, }, } IMAGE_SIZES = getattr(settings, "IMAGE_SIZES", DEFAULT_IMAGE_SIZES) IMAGE_CROPPER = '.crops.cropper' CELERY = getattr(settings, "ASSET_CELERY", None) USE_CELERY_DECORATOR = getattr(settings, "ASSET_USE_CELERY_DECORATOR", False)
# ... existing code ... ASSET_TYPES = getattr(settings, "ASSET_TYPES", None) DEFAULT_IMAGE_SIZES = { 'admin' : { 'width' : 100, 'height' : 100, 'editable': False, 'upscale': True, }, } IMAGE_SIZES = getattr(settings, "IMAGE_SIZES", DEFAULT_IMAGE_SIZES) # ... rest of the code ...
bc9c0120523548d5a28c6a21f48831c1daa39af3
tests/test_data_structures.py
tests/test_data_structures.py
try: import unittest2 as unittest except ImportError: import unittest import zstd class TestCompressionParameters(unittest.TestCase): def test_init_bad_arg_type(self): with self.assertRaises(TypeError): zstd.CompressionParameters() with self.assertRaises(TypeError): zstd.CompressionParameters((0, 1)) def test_get_compression_parameters(self): p = zstd.get_compression_parameters(1) self.assertIsInstance(p, zstd.CompressionParameters) self.assertEqual(p[0], 19)
try: import unittest2 as unittest except ImportError: import unittest try: import hypothesis import hypothesis.strategies as strategies except ImportError: hypothesis = None import zstd class TestCompressionParameters(unittest.TestCase): def test_init_bad_arg_type(self): with self.assertRaises(TypeError): zstd.CompressionParameters() with self.assertRaises(TypeError): zstd.CompressionParameters((0, 1)) def test_get_compression_parameters(self): p = zstd.get_compression_parameters(1) self.assertIsInstance(p, zstd.CompressionParameters) self.assertEqual(p[0], 19) if hypothesis: s_windowlog = strategies.integers(min_value=zstd.WINDOWLOG_MIN, max_value=zstd.WINDOWLOG_MAX) s_chainlog = strategies.integers(min_value=zstd.CHAINLOG_MIN, max_value=zstd.CHAINLOG_MAX) s_hashlog = strategies.integers(min_value=zstd.HASHLOG_MIN, max_value=zstd.HASHLOG_MAX) s_searchlog = strategies.integers(min_value=zstd.SEARCHLOG_MIN, max_value=zstd.SEARCHLOG_MAX) s_searchlength = strategies.integers(min_value=zstd.SEARCHLENGTH_MIN, max_value=zstd.SEARCHLENGTH_MAX) s_targetlength = strategies.integers(min_value=zstd.TARGETLENGTH_MIN, max_value=zstd.TARGETLENGTH_MAX) s_strategy = strategies.sampled_from((zstd.STRATEGY_FAST, zstd.STRATEGY_DFAST, zstd.STRATEGY_GREEDY, zstd.STRATEGY_LAZY, zstd.STRATEGY_LAZY2, zstd.STRATEGY_BTLAZY2, zstd.STRATEGY_BTOPT)) class TestCompressionParametersHypothesis(unittest.TestCase): @hypothesis.given(s_windowlog, s_chainlog, s_hashlog, s_searchlog, s_searchlength, s_targetlength, s_strategy) def test_valid_init(self, windowlog, chainlog, hashlog, searchlog, searchlength, targetlength, strategy): p = zstd.CompressionParameters(windowlog, chainlog, hashlog, searchlog, searchlength, targetlength, strategy) self.assertEqual(tuple(p), (windowlog, chainlog, hashlog, searchlog, searchlength, targetlength, strategy))
Add hypothesis test to randomly generate CompressionParameters
Add hypothesis test to randomly generate CompressionParameters
Python
bsd-3-clause
terrelln/python-zstandard,indygreg/python-zstandard,terrelln/python-zstandard,terrelln/python-zstandard,indygreg/python-zstandard,indygreg/python-zstandard,indygreg/python-zstandard,terrelln/python-zstandard
python
## Code Before: try: import unittest2 as unittest except ImportError: import unittest import zstd class TestCompressionParameters(unittest.TestCase): def test_init_bad_arg_type(self): with self.assertRaises(TypeError): zstd.CompressionParameters() with self.assertRaises(TypeError): zstd.CompressionParameters((0, 1)) def test_get_compression_parameters(self): p = zstd.get_compression_parameters(1) self.assertIsInstance(p, zstd.CompressionParameters) self.assertEqual(p[0], 19) ## Instruction: Add hypothesis test to randomly generate CompressionParameters ## Code After: try: import unittest2 as unittest except ImportError: import unittest try: import hypothesis import hypothesis.strategies as strategies except ImportError: hypothesis = None import zstd class TestCompressionParameters(unittest.TestCase): def test_init_bad_arg_type(self): with self.assertRaises(TypeError): zstd.CompressionParameters() with self.assertRaises(TypeError): zstd.CompressionParameters((0, 1)) def test_get_compression_parameters(self): p = zstd.get_compression_parameters(1) self.assertIsInstance(p, zstd.CompressionParameters) self.assertEqual(p[0], 19) if hypothesis: s_windowlog = strategies.integers(min_value=zstd.WINDOWLOG_MIN, max_value=zstd.WINDOWLOG_MAX) s_chainlog = strategies.integers(min_value=zstd.CHAINLOG_MIN, max_value=zstd.CHAINLOG_MAX) s_hashlog = strategies.integers(min_value=zstd.HASHLOG_MIN, max_value=zstd.HASHLOG_MAX) s_searchlog = strategies.integers(min_value=zstd.SEARCHLOG_MIN, max_value=zstd.SEARCHLOG_MAX) s_searchlength = strategies.integers(min_value=zstd.SEARCHLENGTH_MIN, max_value=zstd.SEARCHLENGTH_MAX) s_targetlength = strategies.integers(min_value=zstd.TARGETLENGTH_MIN, max_value=zstd.TARGETLENGTH_MAX) s_strategy = strategies.sampled_from((zstd.STRATEGY_FAST, zstd.STRATEGY_DFAST, zstd.STRATEGY_GREEDY, zstd.STRATEGY_LAZY, zstd.STRATEGY_LAZY2, zstd.STRATEGY_BTLAZY2, zstd.STRATEGY_BTOPT)) class TestCompressionParametersHypothesis(unittest.TestCase): @hypothesis.given(s_windowlog, s_chainlog, s_hashlog, s_searchlog, s_searchlength, s_targetlength, s_strategy) def test_valid_init(self, windowlog, chainlog, hashlog, searchlog, searchlength, targetlength, strategy): p = zstd.CompressionParameters(windowlog, chainlog, hashlog, searchlog, searchlength, targetlength, strategy) self.assertEqual(tuple(p), (windowlog, chainlog, hashlog, searchlog, searchlength, targetlength, strategy))
# ... existing code ... import unittest2 as unittest except ImportError: import unittest try: import hypothesis import hypothesis.strategies as strategies except ImportError: hypothesis = None import zstd # ... modified code ... self.assertIsInstance(p, zstd.CompressionParameters) self.assertEqual(p[0], 19) if hypothesis: s_windowlog = strategies.integers(min_value=zstd.WINDOWLOG_MIN, max_value=zstd.WINDOWLOG_MAX) s_chainlog = strategies.integers(min_value=zstd.CHAINLOG_MIN, max_value=zstd.CHAINLOG_MAX) s_hashlog = strategies.integers(min_value=zstd.HASHLOG_MIN, max_value=zstd.HASHLOG_MAX) s_searchlog = strategies.integers(min_value=zstd.SEARCHLOG_MIN, max_value=zstd.SEARCHLOG_MAX) s_searchlength = strategies.integers(min_value=zstd.SEARCHLENGTH_MIN, max_value=zstd.SEARCHLENGTH_MAX) s_targetlength = strategies.integers(min_value=zstd.TARGETLENGTH_MIN, max_value=zstd.TARGETLENGTH_MAX) s_strategy = strategies.sampled_from((zstd.STRATEGY_FAST, zstd.STRATEGY_DFAST, zstd.STRATEGY_GREEDY, zstd.STRATEGY_LAZY, zstd.STRATEGY_LAZY2, zstd.STRATEGY_BTLAZY2, zstd.STRATEGY_BTOPT)) class TestCompressionParametersHypothesis(unittest.TestCase): @hypothesis.given(s_windowlog, s_chainlog, s_hashlog, s_searchlog, s_searchlength, s_targetlength, s_strategy) def test_valid_init(self, windowlog, chainlog, hashlog, searchlog, searchlength, targetlength, strategy): p = zstd.CompressionParameters(windowlog, chainlog, hashlog, searchlog, searchlength, targetlength, strategy) self.assertEqual(tuple(p), (windowlog, chainlog, hashlog, searchlog, searchlength, targetlength, strategy)) # ... rest of the code ...
20cc4bd113bc60ec757f4ac980cefa71efb7e401
setup.py
setup.py
from setuptools import setup setup( name='jupyterhub-ldapauthenticator', version='1.0', description='LDAP Authenticator for JupyterHub', url='https://github.com/yuvipanda/ldapauthenticator', author='Yuvi Panda', author_email='[email protected]', license='3 Clause BSD', packages=['ldapauthenticator'], install_requires=[ 'ldap3', ] )
from setuptools import setup setup( name='jupyterhub-ldapauthenticator', version='1.0', description='LDAP Authenticator for JupyterHub', url='https://github.com/yuvipanda/ldapauthenticator', author='Yuvi Panda', author_email='[email protected]', license='3 Clause BSD', packages=['ldapauthenticator'], install_requires=[ 'ldap3', 'jupyterhub', ] )
Add jupyterhub as a requirement
Add jupyterhub as a requirement
Python
bsd-3-clause
yuvipanda/ldapauthenticator
python
## Code Before: from setuptools import setup setup( name='jupyterhub-ldapauthenticator', version='1.0', description='LDAP Authenticator for JupyterHub', url='https://github.com/yuvipanda/ldapauthenticator', author='Yuvi Panda', author_email='[email protected]', license='3 Clause BSD', packages=['ldapauthenticator'], install_requires=[ 'ldap3', ] ) ## Instruction: Add jupyterhub as a requirement ## Code After: from setuptools import setup setup( name='jupyterhub-ldapauthenticator', version='1.0', description='LDAP Authenticator for JupyterHub', url='https://github.com/yuvipanda/ldapauthenticator', author='Yuvi Panda', author_email='[email protected]', license='3 Clause BSD', packages=['ldapauthenticator'], install_requires=[ 'ldap3', 'jupyterhub', ] )
# ... existing code ... packages=['ldapauthenticator'], install_requires=[ 'ldap3', 'jupyterhub', ] ) # ... rest of the code ...
5cf66e26259f5b4c78e61530822fa19dfc117206
settings_test.py
settings_test.py
INSTALLED_APPS = ( 'oauth_tokens', 'taggit', 'vkontakte_groups', ) OAUTH_TOKENS_VKONTAKTE_CLIENT_ID = 3430034 OAUTH_TOKENS_VKONTAKTE_CLIENT_SECRET = 'b0FwzyKtO8QiQmgWQMTz' OAUTH_TOKENS_VKONTAKTE_SCOPE = ['ads,wall,photos,friends,stats'] OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715' OAUTH_TOKENS_VKONTAKTE_PASSWORD = 'githubovich' OAUTH_TOKENS_VKONTAKTE_PHONE_END = '96652237'
INSTALLED_APPS = ( 'oauth_tokens', 'taggit', 'vkontakte_groups', ) OAUTH_TOKENS_VKONTAKTE_CLIENT_ID = 3430034 OAUTH_TOKENS_VKONTAKTE_CLIENT_SECRET = 'b0FwzyKtO8QiQmgWQMTz' OAUTH_TOKENS_VKONTAKTE_SCOPE = ['ads,wall,photos,friends,stats'] OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715' OAUTH_TOKENS_VKONTAKTE_PASSWORD = 'githubovich' OAUTH_TOKENS_VKONTAKTE_PHONE_END = '96652237' # Set VK API Timeout VKONTAKTE_API_REQUEST_TIMEOUT = 7
Fix RuntimeError: maximum recursion depth
Fix RuntimeError: maximum recursion depth
Python
bsd-3-clause
ramusus/django-vkontakte-groups-statistic,ramusus/django-vkontakte-groups-statistic,ramusus/django-vkontakte-groups-statistic
python
## Code Before: INSTALLED_APPS = ( 'oauth_tokens', 'taggit', 'vkontakte_groups', ) OAUTH_TOKENS_VKONTAKTE_CLIENT_ID = 3430034 OAUTH_TOKENS_VKONTAKTE_CLIENT_SECRET = 'b0FwzyKtO8QiQmgWQMTz' OAUTH_TOKENS_VKONTAKTE_SCOPE = ['ads,wall,photos,friends,stats'] OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715' OAUTH_TOKENS_VKONTAKTE_PASSWORD = 'githubovich' OAUTH_TOKENS_VKONTAKTE_PHONE_END = '96652237' ## Instruction: Fix RuntimeError: maximum recursion depth ## Code After: INSTALLED_APPS = ( 'oauth_tokens', 'taggit', 'vkontakte_groups', ) OAUTH_TOKENS_VKONTAKTE_CLIENT_ID = 3430034 OAUTH_TOKENS_VKONTAKTE_CLIENT_SECRET = 'b0FwzyKtO8QiQmgWQMTz' OAUTH_TOKENS_VKONTAKTE_SCOPE = ['ads,wall,photos,friends,stats'] OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715' OAUTH_TOKENS_VKONTAKTE_PASSWORD = 'githubovich' OAUTH_TOKENS_VKONTAKTE_PHONE_END = '96652237' # Set VK API Timeout VKONTAKTE_API_REQUEST_TIMEOUT = 7
# ... existing code ... OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715' OAUTH_TOKENS_VKONTAKTE_PASSWORD = 'githubovich' OAUTH_TOKENS_VKONTAKTE_PHONE_END = '96652237' # Set VK API Timeout VKONTAKTE_API_REQUEST_TIMEOUT = 7 # ... rest of the code ...
c2dd89ae852c80bcbd23988f3e62acdc8f1a8568
app/src/main/java/com/annimon/hotarufx/visual/PropertyType.java
app/src/main/java/com/annimon/hotarufx/visual/PropertyType.java
package com.annimon.hotarufx.visual; import com.annimon.hotarufx.lib.NumberValue; import com.annimon.hotarufx.lib.StringValue; import com.annimon.hotarufx.lib.Types; import com.annimon.hotarufx.lib.Value; import java.util.function.Function; import javafx.scene.paint.Color; import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor(access = AccessLevel.PACKAGE) @Getter public enum PropertyType { NUMBER(toNumber(), o -> NumberValue.of((Number) o)), PAINT(v -> Color.valueOf(v.asString()), o -> new StringValue(o.toString())); private final Function<Value, Object> fromHFX; private final Function<Object, Value> toHFX; private static Function<Value, Object> toNumber() { return value -> { if (value.type() == Types.NUMBER) { return ((NumberValue) value).raw(); } return value.asNumber(); }; } }
package com.annimon.hotarufx.visual; import com.annimon.hotarufx.lib.NumberValue; import com.annimon.hotarufx.lib.StringValue; import com.annimon.hotarufx.lib.Types; import com.annimon.hotarufx.lib.Value; import java.util.function.Function; import javafx.scene.paint.Color; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor(access = AccessLevel.PACKAGE) public enum PropertyType { NUMBER(toNumber(), o -> NumberValue.of((Number) o)), PAINT(v -> Color.valueOf(v.asString()), o -> new StringValue(o.toString())); private final Function<Value, Object> fromHFX; private final Function<Object, Value> toHFX; @SuppressWarnings("unchecked") public <T> Function<Value, T> getFromHFX() { return (Function<Value, T>) fromHFX; } @SuppressWarnings("unchecked") public <T> Function<T, Value> getToHFX() { return (Function<T, Value>) toHFX; } private static Function<Value, Object> toNumber() { return value -> { if (value.type() == Types.NUMBER) { return ((NumberValue) value).raw(); } return value.asNumber(); }; } }
Add generic type to converters signature
Add generic type to converters signature
Java
apache-2.0
aNNiMON/HotaruFX
java
## Code Before: package com.annimon.hotarufx.visual; import com.annimon.hotarufx.lib.NumberValue; import com.annimon.hotarufx.lib.StringValue; import com.annimon.hotarufx.lib.Types; import com.annimon.hotarufx.lib.Value; import java.util.function.Function; import javafx.scene.paint.Color; import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor(access = AccessLevel.PACKAGE) @Getter public enum PropertyType { NUMBER(toNumber(), o -> NumberValue.of((Number) o)), PAINT(v -> Color.valueOf(v.asString()), o -> new StringValue(o.toString())); private final Function<Value, Object> fromHFX; private final Function<Object, Value> toHFX; private static Function<Value, Object> toNumber() { return value -> { if (value.type() == Types.NUMBER) { return ((NumberValue) value).raw(); } return value.asNumber(); }; } } ## Instruction: Add generic type to converters signature ## Code After: package com.annimon.hotarufx.visual; import com.annimon.hotarufx.lib.NumberValue; import com.annimon.hotarufx.lib.StringValue; import com.annimon.hotarufx.lib.Types; import com.annimon.hotarufx.lib.Value; import java.util.function.Function; import javafx.scene.paint.Color; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor(access = AccessLevel.PACKAGE) public enum PropertyType { NUMBER(toNumber(), o -> NumberValue.of((Number) o)), PAINT(v -> Color.valueOf(v.asString()), o -> new StringValue(o.toString())); private final Function<Value, Object> fromHFX; private final Function<Object, Value> toHFX; @SuppressWarnings("unchecked") public <T> Function<Value, T> getFromHFX() { return (Function<Value, T>) fromHFX; } @SuppressWarnings("unchecked") public <T> Function<T, Value> getToHFX() { return (Function<T, Value>) toHFX; } private static Function<Value, Object> toNumber() { return value -> { if (value.type() == Types.NUMBER) { return ((NumberValue) value).raw(); } return value.asNumber(); }; } }
// ... existing code ... import java.util.function.Function; import javafx.scene.paint.Color; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor(access = AccessLevel.PACKAGE) public enum PropertyType { NUMBER(toNumber(), o -> NumberValue.of((Number) o)), // ... modified code ... private final Function<Value, Object> fromHFX; private final Function<Object, Value> toHFX; @SuppressWarnings("unchecked") public <T> Function<Value, T> getFromHFX() { return (Function<Value, T>) fromHFX; } @SuppressWarnings("unchecked") public <T> Function<T, Value> getToHFX() { return (Function<T, Value>) toHFX; } private static Function<Value, Object> toNumber() { return value -> { // ... rest of the code ...
f4d1cebe889e4c55bab104f9a2c993c8ed153d34
ubitflashtool/__main__.py
ubitflashtool/__main__.py
import sys from ubitflashtool.cli import main from ubitflashtool.gui import open_editor if __name__ == "__main__": if len(sys.argv) > 1 and (sys.argv[1] == '-g' or sys.argv[1] == '--gui'): open_editor() else: main(sys.argv[1:])
import sys from ubitflashtool.cli import main as cli_main from ubitflashtool.gui import open_editor def main(): if len(sys.argv) > 1 and (sys.argv[1] == '-g' or sys.argv[1] == '--gui'): open_editor() else: cli_main(sys.argv[1:]) if __name__ == "__main__": main()
Fix command line entry point
Fix command line entry point
Python
mit
carlosperate/ubitflashtool
python
## Code Before: import sys from ubitflashtool.cli import main from ubitflashtool.gui import open_editor if __name__ == "__main__": if len(sys.argv) > 1 and (sys.argv[1] == '-g' or sys.argv[1] == '--gui'): open_editor() else: main(sys.argv[1:]) ## Instruction: Fix command line entry point ## Code After: import sys from ubitflashtool.cli import main as cli_main from ubitflashtool.gui import open_editor def main(): if len(sys.argv) > 1 and (sys.argv[1] == '-g' or sys.argv[1] == '--gui'): open_editor() else: cli_main(sys.argv[1:]) if __name__ == "__main__": main()
... import sys from ubitflashtool.cli import main as cli_main from ubitflashtool.gui import open_editor def main(): if len(sys.argv) > 1 and (sys.argv[1] == '-g' or sys.argv[1] == '--gui'): open_editor() else: cli_main(sys.argv[1:]) if __name__ == "__main__": main() ...
879fdecdf38a2647c9a4793fbffedeaf150adfbd
src/utils/image_persister.h
src/utils/image_persister.h
/** * \brief Provides static functions to load and save images * */ class ImagePersister { public: template <class T> static void saveRGBA32F(T *data, int width, int height, std::string filename) { Magick::InitializeMagick(""); Magick::Image image(width, height, "RGBA", Magick::StorageType::FloatPixel, data); image.write(filename); } static std::vector<Eigen::Vector4f> loadRGBA32F(std::string filename) { Magick::Image image(filename); std::vector<Eigen::Vector4f> result(image.columns() * image.rows()); image.write(0, 0, image.columns(), image.rows(), "RGBA", Magick::StorageType::FloatPixel, result.data()); return result; } }; #endif // SRC_UTILS_IMAGE_PERSISTER_H_
/** * \brief Provides static functions to load and save images * */ class ImagePersister { public: template <class T> static void saveRGBA32F(T *data, int width, int height, std::string filename) { Magick::InitializeMagick(""); Magick::Image image(width, height, "RGBA", Magick::StorageType::FloatPixel, data); image.write(filename); } static void saveR32F(float *data, int width, int height, std::string filename) { Magick::InitializeMagick(""); Magick::Image image(width, height, "R", Magick::StorageType::FloatPixel, data); image.write(filename); } static std::vector<Eigen::Vector4f> loadRGBA32F(std::string filename) { Magick::Image image(filename); std::vector<Eigen::Vector4f> result(image.columns() * image.rows()); image.write(0, 0, image.columns(), image.rows(), "RGBA", Magick::StorageType::FloatPixel, result.data()); return result; } }; #endif // SRC_UTILS_IMAGE_PERSISTER_H_
Add method to save a single component float image.
Add method to save a single component float image.
C
mit
Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller
c
## Code Before: /** * \brief Provides static functions to load and save images * */ class ImagePersister { public: template <class T> static void saveRGBA32F(T *data, int width, int height, std::string filename) { Magick::InitializeMagick(""); Magick::Image image(width, height, "RGBA", Magick::StorageType::FloatPixel, data); image.write(filename); } static std::vector<Eigen::Vector4f> loadRGBA32F(std::string filename) { Magick::Image image(filename); std::vector<Eigen::Vector4f> result(image.columns() * image.rows()); image.write(0, 0, image.columns(), image.rows(), "RGBA", Magick::StorageType::FloatPixel, result.data()); return result; } }; #endif // SRC_UTILS_IMAGE_PERSISTER_H_ ## Instruction: Add method to save a single component float image. ## Code After: /** * \brief Provides static functions to load and save images * */ class ImagePersister { public: template <class T> static void saveRGBA32F(T *data, int width, int height, std::string filename) { Magick::InitializeMagick(""); Magick::Image image(width, height, "RGBA", Magick::StorageType::FloatPixel, data); image.write(filename); } static void saveR32F(float *data, int width, int height, std::string filename) { Magick::InitializeMagick(""); Magick::Image image(width, height, "R", Magick::StorageType::FloatPixel, data); image.write(filename); } static std::vector<Eigen::Vector4f> loadRGBA32F(std::string filename) { Magick::Image image(filename); std::vector<Eigen::Vector4f> result(image.columns() * image.rows()); image.write(0, 0, image.columns(), image.rows(), "RGBA", Magick::StorageType::FloatPixel, result.data()); return result; } }; #endif // SRC_UTILS_IMAGE_PERSISTER_H_
// ... existing code ... image.write(filename); } static void saveR32F(float *data, int width, int height, std::string filename) { Magick::InitializeMagick(""); Magick::Image image(width, height, "R", Magick::StorageType::FloatPixel, data); image.write(filename); } static std::vector<Eigen::Vector4f> loadRGBA32F(std::string filename) { Magick::Image image(filename); // ... rest of the code ...
d9e17f30737a71df4ccc6b784f237a15484803f4
libspell.h
libspell.h
char *spell(sqlite3*, char *); char *get_suggestions(char *); #endif
char *spell(char *); char *get_suggestions(char *); #endif
Remove sqlite3 * parameter from the spell function's declaration.
Remove sqlite3 * parameter from the spell function's declaration.
C
bsd-2-clause
abhinav-upadhyay/spell,abhinav-upadhyay/spell
c
## Code Before: char *spell(sqlite3*, char *); char *get_suggestions(char *); #endif ## Instruction: Remove sqlite3 * parameter from the spell function's declaration. ## Code After: char *spell(char *); char *get_suggestions(char *); #endif
... char *spell(char *); char *get_suggestions(char *); #endif ...
b11ef81b180cc18acb44988f3e269af6b54f4c89
timewreport/interval.py
timewreport/interval.py
import dateutil.parser from datetime import datetime from dateutil.tz import tz class TimeWarriorInterval(object): def __init__(self, start, end, tags): self.__start = self.__get_local_datetime(start) self.__end = self.__get_local_datetime(end) if end is not None else None self.__tags = tags def __eq__(self, other): return self.__start == other.get_start() \ and self.__end == other.get_end() \ and self.__tags == other.get_tags() def get_start(self): return self.__start def get_end(self): return self.__end def get_tags(self): return self.__tags def is_open(self): return self.__end is None def get_duration(self): if self.is_open(): return datetime.now(tz=tz.tzlocal()) - self.__start else: return self.__end - self.__start def get_date(self): return datetime(self.__start.year, self.__start.month, self.__start.day) def __get_local_datetime(self, datetime_string): from_zone = tz.tzutc() to_zone = tz.tzlocal() date = dateutil.parser.parse(datetime_string) date.replace(tzinfo=from_zone) return date.astimezone(to_zone)
import dateutil.parser from datetime import datetime, date from dateutil.tz import tz class TimeWarriorInterval(object): def __init__(self, start, end, tags): self.__start = self.__get_local_datetime(start) self.__end = self.__get_local_datetime(end) if end is not None else None self.__tags = tags def __eq__(self, other): return self.__start == other.get_start() \ and self.__end == other.get_end() \ and self.__tags == other.get_tags() def get_start(self): return self.__start def get_end(self): return self.__end def get_tags(self): return self.__tags def is_open(self): return self.__end is None def get_duration(self): if self.is_open(): return datetime.now(tz=tz.tzlocal()) - self.__start else: return self.__end - self.__start def get_date(self): return date(self.__start.year, self.__start.month, self.__start.day) def __get_local_datetime(self, datetime_string): from_zone = tz.tzutc() to_zone = tz.tzlocal() date = dateutil.parser.parse(datetime_string) date.replace(tzinfo=from_zone) return date.astimezone(to_zone)
Make get_date() return date object instead of datetime
Make get_date() return date object instead of datetime
Python
mit
lauft/timew-report
python
## Code Before: import dateutil.parser from datetime import datetime from dateutil.tz import tz class TimeWarriorInterval(object): def __init__(self, start, end, tags): self.__start = self.__get_local_datetime(start) self.__end = self.__get_local_datetime(end) if end is not None else None self.__tags = tags def __eq__(self, other): return self.__start == other.get_start() \ and self.__end == other.get_end() \ and self.__tags == other.get_tags() def get_start(self): return self.__start def get_end(self): return self.__end def get_tags(self): return self.__tags def is_open(self): return self.__end is None def get_duration(self): if self.is_open(): return datetime.now(tz=tz.tzlocal()) - self.__start else: return self.__end - self.__start def get_date(self): return datetime(self.__start.year, self.__start.month, self.__start.day) def __get_local_datetime(self, datetime_string): from_zone = tz.tzutc() to_zone = tz.tzlocal() date = dateutil.parser.parse(datetime_string) date.replace(tzinfo=from_zone) return date.astimezone(to_zone) ## Instruction: Make get_date() return date object instead of datetime ## Code After: import dateutil.parser from datetime import datetime, date from dateutil.tz import tz class TimeWarriorInterval(object): def __init__(self, start, end, tags): self.__start = self.__get_local_datetime(start) self.__end = self.__get_local_datetime(end) if end is not None else None self.__tags = tags def __eq__(self, other): return self.__start == other.get_start() \ and self.__end == other.get_end() \ and self.__tags == other.get_tags() def get_start(self): return self.__start def get_end(self): return self.__end def get_tags(self): return self.__tags def is_open(self): return self.__end is None def get_duration(self): if self.is_open(): return datetime.now(tz=tz.tzlocal()) - self.__start else: return self.__end - self.__start def get_date(self): return date(self.__start.year, self.__start.month, self.__start.day) def __get_local_datetime(self, datetime_string): from_zone = tz.tzutc() to_zone = tz.tzlocal() date = dateutil.parser.parse(datetime_string) date.replace(tzinfo=from_zone) return date.astimezone(to_zone)
... import dateutil.parser from datetime import datetime, date from dateutil.tz import tz ... return self.__end - self.__start def get_date(self): return date(self.__start.year, self.__start.month, self.__start.day) def __get_local_datetime(self, datetime_string): from_zone = tz.tzutc() ...
1bc38da6f283f940ba0c08ae5c2a6ab1e5ce513d
src/main/java/edu/northwestern/bioinformatics/studycalendar/restlets/TemplateResource.java
src/main/java/edu/northwestern/bioinformatics/studycalendar/restlets/TemplateResource.java
package edu.northwestern.bioinformatics.studycalendar.restlets; import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao; import edu.northwestern.bioinformatics.studycalendar.domain.Study; import edu.northwestern.bioinformatics.studycalendar.domain.Role; import edu.northwestern.bioinformatics.studycalendar.xml.writers.StudyXmlSerializer; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Method; import org.restlet.Context; import org.springframework.beans.factory.annotation.Required; /** * Resource representing a study and its planned calendar, including all amendments. * * @author Rhett Sutphin */ public class TemplateResource extends AbstractStorableDomainObjectResource<Study> { private StudyDao studyDao; @Override public void init(Context context, Request request, Response response) { super.init(context, request, response); setAllAuthorizedFor(Method.GET); setAuthorizedFor(Method.PUT, Role.STUDY_ADMIN); // TODO: temporary setXmlSerializer(new StudyXmlSerializer()); } @Override protected Study loadRequestedObject(Request request) { String studyIdent = UriTemplateParameters.STUDY_IDENTIFIER.extractFrom(request); return studyDao.getByAssignedIdentifier(studyIdent); } ////// CONFIGURATION @Required public void setStudyDao(StudyDao studyDao) { this.studyDao = studyDao; } }
package edu.northwestern.bioinformatics.studycalendar.restlets; import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao; import edu.northwestern.bioinformatics.studycalendar.domain.Study; import edu.northwestern.bioinformatics.studycalendar.domain.Role; import edu.northwestern.bioinformatics.studycalendar.xml.writers.StudyXmlSerializer; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Method; import org.restlet.Context; import org.springframework.beans.factory.annotation.Required; /** * Resource representing a study and its planned calendar, including all amendments. * * @author Rhett Sutphin */ public class TemplateResource extends AbstractStorableDomainObjectResource<Study> { private StudyDao studyDao; @Override public void init(Context context, Request request, Response response) { super.init(context, request, response); setAllAuthorizedFor(Method.GET); setAuthorizedFor(Method.PUT, Role.STUDY_ADMIN); } @Override protected Study loadRequestedObject(Request request) { String studyIdent = UriTemplateParameters.STUDY_IDENTIFIER.extractFrom(request); return studyDao.getByAssignedIdentifier(studyIdent); } ////// CONFIGURATION @Required public void setStudyDao(StudyDao studyDao) { this.studyDao = studyDao; } }
Remove mistakenly committed manual XML serializer injection
Remove mistakenly committed manual XML serializer injection
Java
bsd-3-clause
NCIP/psc,NCIP/psc,NCIP/psc,NCIP/psc
java
## Code Before: package edu.northwestern.bioinformatics.studycalendar.restlets; import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao; import edu.northwestern.bioinformatics.studycalendar.domain.Study; import edu.northwestern.bioinformatics.studycalendar.domain.Role; import edu.northwestern.bioinformatics.studycalendar.xml.writers.StudyXmlSerializer; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Method; import org.restlet.Context; import org.springframework.beans.factory.annotation.Required; /** * Resource representing a study and its planned calendar, including all amendments. * * @author Rhett Sutphin */ public class TemplateResource extends AbstractStorableDomainObjectResource<Study> { private StudyDao studyDao; @Override public void init(Context context, Request request, Response response) { super.init(context, request, response); setAllAuthorizedFor(Method.GET); setAuthorizedFor(Method.PUT, Role.STUDY_ADMIN); // TODO: temporary setXmlSerializer(new StudyXmlSerializer()); } @Override protected Study loadRequestedObject(Request request) { String studyIdent = UriTemplateParameters.STUDY_IDENTIFIER.extractFrom(request); return studyDao.getByAssignedIdentifier(studyIdent); } ////// CONFIGURATION @Required public void setStudyDao(StudyDao studyDao) { this.studyDao = studyDao; } } ## Instruction: Remove mistakenly committed manual XML serializer injection ## Code After: package edu.northwestern.bioinformatics.studycalendar.restlets; import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao; import edu.northwestern.bioinformatics.studycalendar.domain.Study; import edu.northwestern.bioinformatics.studycalendar.domain.Role; import edu.northwestern.bioinformatics.studycalendar.xml.writers.StudyXmlSerializer; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Method; import org.restlet.Context; import org.springframework.beans.factory.annotation.Required; /** * Resource representing a study and its planned calendar, including all amendments. * * @author Rhett Sutphin */ public class TemplateResource extends AbstractStorableDomainObjectResource<Study> { private StudyDao studyDao; @Override public void init(Context context, Request request, Response response) { super.init(context, request, response); setAllAuthorizedFor(Method.GET); setAuthorizedFor(Method.PUT, Role.STUDY_ADMIN); } @Override protected Study loadRequestedObject(Request request) { String studyIdent = UriTemplateParameters.STUDY_IDENTIFIER.extractFrom(request); return studyDao.getByAssignedIdentifier(studyIdent); } ////// CONFIGURATION @Required public void setStudyDao(StudyDao studyDao) { this.studyDao = studyDao; } }
# ... existing code ... super.init(context, request, response); setAllAuthorizedFor(Method.GET); setAuthorizedFor(Method.PUT, Role.STUDY_ADMIN); } @Override # ... rest of the code ...
e1467dbfd5d1068c2dd69511f16bc218475a9396
test/Sema/align-arm-apcs-gnu.c
test/Sema/align-arm-apcs-gnu.c
// RUN: %clang_cc1 -triple arm-unknown-unknown -target-abi apcs-gnu -fsyntax-only -verify %s struct s0 { double f0; int f1; }; char chk0[__alignof__(struct s0) == 4 ? 1 : -1]; double g1; short chk1[__alignof__(g1) == 4 ? 1 : -1]; short chk2[__alignof__(double) == 4 ? 1 : -1]; long long g2; short chk1[__alignof__(g2) == 4 ? 1 : -1]; short chk2[__alignof__(long long) == 4 ? 1 : -1]; _Complex double g3; short chk1[__alignof__(g3) == 4 ? 1 : -1]; short chk2[__alignof__(_Complex double) == 4 ? 1 : -1];
// RUN: %clang_cc1 -triple arm-unknown-unknown -target-abi apcs-gnu -fsyntax-only -verify %s struct s0 { double f0; int f1; }; char chk0[__alignof__(struct s0) == 4 ? 1 : -1];
Fix r135934. Rename was intended, but without additional tests for double.
Fix r135934. Rename was intended, but without additional tests for double. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@135935 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang
c
## Code Before: // RUN: %clang_cc1 -triple arm-unknown-unknown -target-abi apcs-gnu -fsyntax-only -verify %s struct s0 { double f0; int f1; }; char chk0[__alignof__(struct s0) == 4 ? 1 : -1]; double g1; short chk1[__alignof__(g1) == 4 ? 1 : -1]; short chk2[__alignof__(double) == 4 ? 1 : -1]; long long g2; short chk1[__alignof__(g2) == 4 ? 1 : -1]; short chk2[__alignof__(long long) == 4 ? 1 : -1]; _Complex double g3; short chk1[__alignof__(g3) == 4 ? 1 : -1]; short chk2[__alignof__(_Complex double) == 4 ? 1 : -1]; ## Instruction: Fix r135934. Rename was intended, but without additional tests for double. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@135935 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: // RUN: %clang_cc1 -triple arm-unknown-unknown -target-abi apcs-gnu -fsyntax-only -verify %s struct s0 { double f0; int f1; }; char chk0[__alignof__(struct s0) == 4 ? 1 : -1];
# ... existing code ... // RUN: %clang_cc1 -triple arm-unknown-unknown -target-abi apcs-gnu -fsyntax-only -verify %s struct s0 { double f0; int f1; }; char chk0[__alignof__(struct s0) == 4 ? 1 : -1]; # ... rest of the code ...
37170b156e6a284d5e5df671875070a3fcac9310
commands/join.py
commands/join.py
from CommandTemplate import CommandTemplate from IrcMessage import IrcMessage class Command(CommandTemplate): triggers = ['join'] helptext = "Makes me join another channel, if I'm allowed to at least" def execute(self, message): """ :type message: IrcMessage """ replytext = "" if message.messagePartsLength < 1: replytext = "Please provide a channel for me to join" else: channel = message.messageParts[0] if channel.replace('#', '') not in message.bot.factory.settings['allowedChannels'] and not message.bot.factory.isUserAdmin(message.user, message.userNickname, message.userAddress): replytext = "I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission" else: replytext = "All right, I'll go to {}. See you there!".format(channel) message.bot.join(channel) message.reply(replytext, "say")
from CommandTemplate import CommandTemplate from IrcMessage import IrcMessage class Command(CommandTemplate): triggers = ['join'] helptext = "Makes me join another channel, if I'm allowed to at least" def execute(self, message): """ :type message: IrcMessage """ replytext = "" if message.messagePartsLength < 1: replytext = "Please provide a channel for me to join" else: channel = message.messageParts[0].lower() if channel.startswith('#'): channel = channel.lstrip('#') if '#' + channel in message.bot.channelsUserList: replytext = "I'm already there, waiting for you. You're welcome!" elif channel not in message.bot.factory.settings['allowedChannels'] and not message.bot.factory.isUserAdmin(message.user, message.userNickname, message.userAddress): replytext = "I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission" else: replytext = "All right, I'll go to #{}. See you there!".format(channel) message.bot.join(channel) message.reply(replytext, "say")
Check if we're already in the channel; Improved parameter parsing
[Join] Check if we're already in the channel; Improved parameter parsing
Python
mit
Didero/DideRobot
python
## Code Before: from CommandTemplate import CommandTemplate from IrcMessage import IrcMessage class Command(CommandTemplate): triggers = ['join'] helptext = "Makes me join another channel, if I'm allowed to at least" def execute(self, message): """ :type message: IrcMessage """ replytext = "" if message.messagePartsLength < 1: replytext = "Please provide a channel for me to join" else: channel = message.messageParts[0] if channel.replace('#', '') not in message.bot.factory.settings['allowedChannels'] and not message.bot.factory.isUserAdmin(message.user, message.userNickname, message.userAddress): replytext = "I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission" else: replytext = "All right, I'll go to {}. See you there!".format(channel) message.bot.join(channel) message.reply(replytext, "say") ## Instruction: [Join] Check if we're already in the channel; Improved parameter parsing ## Code After: from CommandTemplate import CommandTemplate from IrcMessage import IrcMessage class Command(CommandTemplate): triggers = ['join'] helptext = "Makes me join another channel, if I'm allowed to at least" def execute(self, message): """ :type message: IrcMessage """ replytext = "" if message.messagePartsLength < 1: replytext = "Please provide a channel for me to join" else: channel = message.messageParts[0].lower() if channel.startswith('#'): channel = channel.lstrip('#') if '#' + channel in message.bot.channelsUserList: replytext = "I'm already there, waiting for you. You're welcome!" elif channel not in message.bot.factory.settings['allowedChannels'] and not message.bot.factory.isUserAdmin(message.user, message.userNickname, message.userAddress): replytext = "I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission" else: replytext = "All right, I'll go to #{}. See you there!".format(channel) message.bot.join(channel) message.reply(replytext, "say")
// ... existing code ... if message.messagePartsLength < 1: replytext = "Please provide a channel for me to join" else: channel = message.messageParts[0].lower() if channel.startswith('#'): channel = channel.lstrip('#') if '#' + channel in message.bot.channelsUserList: replytext = "I'm already there, waiting for you. You're welcome!" elif channel not in message.bot.factory.settings['allowedChannels'] and not message.bot.factory.isUserAdmin(message.user, message.userNickname, message.userAddress): replytext = "I'm sorry, I'm not allowed to go there. Please ask my admin(s) for permission" else: replytext = "All right, I'll go to #{}. See you there!".format(channel) message.bot.join(channel) message.reply(replytext, "say") // ... rest of the code ...
347853290ebc4f5c47430ffce7d603eb4fead2d9
cpt/test/integration/update_python_reqs_test.py
cpt/test/integration/update_python_reqs_test.py
import unittest from conans.test.utils.tools import TestClient from cpt.test.test_client.tools import get_patched_multipackager class PythonRequiresTest(unittest.TestCase): def test_python_requires(self): base_conanfile = """from conans import ConanFile myvar = 123 def myfunct(): return 234 class Pkg(ConanFile): pass """ conanfile = """from conans import ConanFile class Pkg(ConanFile): name = "pyreq" version = "1.0.0" python_requires = "pyreq_base/0.1@user/channel" def build(self): v = self.python_requires["pyreq_base"].module.myvar f = self.python_requires["pyreq_base"].module.myfunct() self.output.info("%s,%s" % (v, f)) """ client = TestClient() client.save({"conanfile_base.py": base_conanfile}) client.run("export conanfile_base.py pyreq_base/0.1@user/channel") client.save({"conanfile.py": conanfile}) mulitpackager = get_patched_multipackager(client, username="user", channel="testing", exclude_vcvars_precommand=True) mulitpackager.add({}, {}) mulitpackager.run() self.assertIn("pyreq/1.0.0@user/testing: 123,234", client.out)
import unittest from conans.test.utils.tools import TestClient from cpt.test.test_client.tools import get_patched_multipackager class PythonRequiresTest(unittest.TestCase): def test_python_requires(self): base_conanfile = """from conans import ConanFile myvar = 123 def myfunct(): return 234 class Pkg(ConanFile): pass """ conanfile = """from conans import ConanFile class Pkg(ConanFile): name = "pyreq" version = "1.0.0" python_requires = "pyreq_base/0.1@user/channel" def build(self): v = self.python_requires["pyreq_base"].module.myvar f = self.python_requires["pyreq_base"].module.myfunct() self.output.info("%s,%s" % (v, f)) """ client = TestClient() client.save({"conanfile_base.py": base_conanfile}) client.run("export conanfile_base.py pyreq_base/0.1@user/channel") client.save({"conanfile.py": conanfile}) mulitpackager = get_patched_multipackager(client, username="user", channel="testing", exclude_vcvars_precommand=True) mulitpackager.add({}, {}) mulitpackager.run() self.assertIn("pyreq/1.0.0@user/", client.out) self.assertIn(": 123,234", client.out)
Fix pyreq test on Windows
Fix pyreq test on Windows Signed-off-by: Uilian Ries <[email protected]>
Python
mit
conan-io/conan-package-tools
python
## Code Before: import unittest from conans.test.utils.tools import TestClient from cpt.test.test_client.tools import get_patched_multipackager class PythonRequiresTest(unittest.TestCase): def test_python_requires(self): base_conanfile = """from conans import ConanFile myvar = 123 def myfunct(): return 234 class Pkg(ConanFile): pass """ conanfile = """from conans import ConanFile class Pkg(ConanFile): name = "pyreq" version = "1.0.0" python_requires = "pyreq_base/0.1@user/channel" def build(self): v = self.python_requires["pyreq_base"].module.myvar f = self.python_requires["pyreq_base"].module.myfunct() self.output.info("%s,%s" % (v, f)) """ client = TestClient() client.save({"conanfile_base.py": base_conanfile}) client.run("export conanfile_base.py pyreq_base/0.1@user/channel") client.save({"conanfile.py": conanfile}) mulitpackager = get_patched_multipackager(client, username="user", channel="testing", exclude_vcvars_precommand=True) mulitpackager.add({}, {}) mulitpackager.run() self.assertIn("pyreq/1.0.0@user/testing: 123,234", client.out) ## Instruction: Fix pyreq test on Windows Signed-off-by: Uilian Ries <[email protected]> ## Code After: import unittest from conans.test.utils.tools import TestClient from cpt.test.test_client.tools import get_patched_multipackager class PythonRequiresTest(unittest.TestCase): def test_python_requires(self): base_conanfile = """from conans import ConanFile myvar = 123 def myfunct(): return 234 class Pkg(ConanFile): pass """ conanfile = """from conans import ConanFile class Pkg(ConanFile): name = "pyreq" version = "1.0.0" python_requires = "pyreq_base/0.1@user/channel" def build(self): v = self.python_requires["pyreq_base"].module.myvar f = self.python_requires["pyreq_base"].module.myfunct() self.output.info("%s,%s" % (v, f)) """ client = TestClient() client.save({"conanfile_base.py": base_conanfile}) client.run("export conanfile_base.py pyreq_base/0.1@user/channel") client.save({"conanfile.py": conanfile}) mulitpackager = get_patched_multipackager(client, username="user", channel="testing", exclude_vcvars_precommand=True) mulitpackager.add({}, {}) mulitpackager.run() self.assertIn("pyreq/1.0.0@user/", client.out) self.assertIn(": 123,234", client.out)
// ... existing code ... exclude_vcvars_precommand=True) mulitpackager.add({}, {}) mulitpackager.run() self.assertIn("pyreq/1.0.0@user/", client.out) self.assertIn(": 123,234", client.out) // ... rest of the code ...
d0e139d286b18c9dcdc8c46161c4ebdf0f0f8d96
examples/cooperative_binding.py
examples/cooperative_binding.py
import sys import os sys.path.insert(0, os.path.join( os.path.dirname(os.path.realpath(__file__)), '..')) from crnpy.crn import CRN, from_react_file __author__ = "Elisa Tonello" __copyright__ = "Copyright (c) 2016, Elisa Tonello" __license__ = "BSD" __version__ = "0.0.1" # Cooperative binding print "Creating model..." crn = from_react_file("data/reactions/cooperative_binding") crn.inspect(True) print print("Remove ps1, ps2 and ps3 by qss") crn.remove(qss = ['ps1', 'ps2', 'ps3'], debug = True) for s, f in crn.removed_species: print(s + " = " + str(f)) crn.inspect(True)
import sys import os sys.path.insert(0, os.path.join( os.path.dirname(os.path.realpath(__file__)), '..')) from crnpy.crn import CRN, from_react_file __author__ = "Elisa Tonello" __copyright__ = "Copyright (c) 2016, Elisa Tonello" __license__ = "BSD" __version__ = "0.0.1" # Cooperative binding print "Creating model..." crn = from_react_file("data/reactions/cooperative_binding") crn.inspect(True) print("") print("Remove ps1, ps2 and ps3 by qssa") crn.remove(qss = ['ps1', 'ps2', 'ps3']) for s, f in crn.removed_species: print(s + " = " + str(f)) crn.inspect(True)
Remove debug and adjusted print.
Remove debug and adjusted print.
Python
bsd-3-clause
etonello/crnpy
python
## Code Before: import sys import os sys.path.insert(0, os.path.join( os.path.dirname(os.path.realpath(__file__)), '..')) from crnpy.crn import CRN, from_react_file __author__ = "Elisa Tonello" __copyright__ = "Copyright (c) 2016, Elisa Tonello" __license__ = "BSD" __version__ = "0.0.1" # Cooperative binding print "Creating model..." crn = from_react_file("data/reactions/cooperative_binding") crn.inspect(True) print print("Remove ps1, ps2 and ps3 by qss") crn.remove(qss = ['ps1', 'ps2', 'ps3'], debug = True) for s, f in crn.removed_species: print(s + " = " + str(f)) crn.inspect(True) ## Instruction: Remove debug and adjusted print. ## Code After: import sys import os sys.path.insert(0, os.path.join( os.path.dirname(os.path.realpath(__file__)), '..')) from crnpy.crn import CRN, from_react_file __author__ = "Elisa Tonello" __copyright__ = "Copyright (c) 2016, Elisa Tonello" __license__ = "BSD" __version__ = "0.0.1" # Cooperative binding print "Creating model..." crn = from_react_file("data/reactions/cooperative_binding") crn.inspect(True) print("") print("Remove ps1, ps2 and ps3 by qssa") crn.remove(qss = ['ps1', 'ps2', 'ps3']) for s, f in crn.removed_species: print(s + " = " + str(f)) crn.inspect(True)
// ... existing code ... crn = from_react_file("data/reactions/cooperative_binding") crn.inspect(True) print("") print("Remove ps1, ps2 and ps3 by qssa") crn.remove(qss = ['ps1', 'ps2', 'ps3']) for s, f in crn.removed_species: print(s + " = " + str(f)) crn.inspect(True) // ... rest of the code ...
cb4421529e9564f110b84f590f14057eda8746c8
setup.py
setup.py
from setuptools import setup from setuptools.command.install import install as _install class install(_install): def run(self): _install.run(self) setup( cmdclass = { 'install' : install }, name = 'hydra', version = '0.1', author = 'tatsy', author_email = '[email protected]', url = 'https://github.com/tatsy/hydra.git', description = 'Python HDR image processing library.', license = 'MIT', classifiers = [ 'Development Status :: 1 - Planning', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ], packages = [ 'hydra', 'hydra.core', 'hydra.gen', 'hydra.io', 'hydra.filters', 'hydra.tonemap' ] )
from setuptools import setup from setuptools.command.install import install as _install class install(_install): def run(self): _install.run(self) setup( cmdclass = { 'install' : install }, name = 'hydra', version = '0.1', author = 'tatsy', author_email = '[email protected]', url = 'https://github.com/tatsy/hydra.git', description = 'Python HDR image processing library.', license = 'MIT', classifiers = [ 'Development Status :: 1 - Planning', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ], packages = [ 'hydra', 'hydra.core', 'hydra.eo', 'hydra.filters', 'hydra.gen', 'hydra.io', 'hydra.tonemap' ] )
Add eo to installed packages.
Add eo to installed packages.
Python
mit
tatsy/hydra
python
## Code Before: from setuptools import setup from setuptools.command.install import install as _install class install(_install): def run(self): _install.run(self) setup( cmdclass = { 'install' : install }, name = 'hydra', version = '0.1', author = 'tatsy', author_email = '[email protected]', url = 'https://github.com/tatsy/hydra.git', description = 'Python HDR image processing library.', license = 'MIT', classifiers = [ 'Development Status :: 1 - Planning', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ], packages = [ 'hydra', 'hydra.core', 'hydra.gen', 'hydra.io', 'hydra.filters', 'hydra.tonemap' ] ) ## Instruction: Add eo to installed packages. ## Code After: from setuptools import setup from setuptools.command.install import install as _install class install(_install): def run(self): _install.run(self) setup( cmdclass = { 'install' : install }, name = 'hydra', version = '0.1', author = 'tatsy', author_email = '[email protected]', url = 'https://github.com/tatsy/hydra.git', description = 'Python HDR image processing library.', license = 'MIT', classifiers = [ 'Development Status :: 1 - Planning', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4' ], packages = [ 'hydra', 'hydra.core', 'hydra.eo', 'hydra.filters', 'hydra.gen', 'hydra.io', 'hydra.tonemap' ] )
... packages = [ 'hydra', 'hydra.core', 'hydra.eo', 'hydra.filters', 'hydra.gen', 'hydra.io', 'hydra.tonemap' ] ) ...
4509716a95ca16e7121534fa6a4b23f59d57782f
github-android/src/main/java/com/github/mobile/android/GitHubApplication.java
github-android/src/main/java/com/github/mobile/android/GitHubApplication.java
package com.github.mobile.android; import static java.util.Arrays.asList; import android.app.Application; import android.app.Instrumentation; import android.content.Context; import android.util.Log; import com.google.inject.Module; import java.util.List; /** * Main GitHub application */ public class GitHubApplication extends Application { private static final String TAG = "GHA"; /** * Create main application */ public GitHubApplication() { } /** * Create main application * * @param context */ public GitHubApplication(Context context) { attachBaseContext(context); } /** * Create main application * * @param instrumentation */ public GitHubApplication(Instrumentation instrumentation) { attachBaseContext(instrumentation.getTargetContext()); } protected void addApplicationModules(List<Module> modules) { Log.i(TAG, "Adding application modules..."); modules.addAll(asList(new GitHubModule())); } }
package com.github.mobile.android; import android.app.Application; import android.app.Instrumentation; import android.content.Context; import android.util.Log; import com.google.inject.Module; import java.util.List; /** * Main GitHub application */ public class GitHubApplication extends Application { private static final String TAG = "GHA"; /** * Create main application */ public GitHubApplication() { } /** * Create main application * * @param context */ public GitHubApplication(Context context) { attachBaseContext(context); } /** * Create main application * * @param instrumentation */ public GitHubApplication(Instrumentation instrumentation) { attachBaseContext(instrumentation.getTargetContext()); } /** * Add modules * * @param modules */ protected void addApplicationModules(List<Module> modules) { Log.d(TAG, "Adding application modules..."); modules.add(new GitHubModule()); } }
Remove unneeded list creation to add single item
Remove unneeded list creation to add single item
Java
apache-2.0
yummy222/PocketHub,micrologic/PocketHub,erpragatisingh/android-1,kostaskoukouvis/android,danielferecatu/android,mishin/ForkHub,forkhubs/android,KingLiuDao/android,PKRoma/github-android,work4life/PocketHub,karllindmark/PocketHub,generalzou/PocketHub,erpragatisingh/android-1,yytang2012/PocketHub,huangsongyan/PocketHub,LeoLamCY/PocketHub,condda/android,wubin28/android,vfs1234/android,soztzfsnf/PocketHub,common2015/PocketHub,ywk248248/Forkhub_cloned,chaoallsome/PocketHub,erpragatisingh/android-1,micrologic/PocketHub,bineanzhou/android_github,repanda/PocketHub,soztzfsnf/PocketHub,gvaish/PocketHub,simple88/PocketHub,yongjhih/PocketHub,Meisolsson/PocketHub,condda/android,fadils/android,hgl888/PocketHub,chaoallsome/PocketHub,wang0818/android,DeLaSalleUniversity-Manila/forkhub-JJCpro10,pockethub/PocketHub,reproio/github-for-android,Cl3Kener/darkhub,Damonzh/PocketHub,wubin28/android,Tadakatsu/android,xfumihiro/PocketHub,Calamus-Cajan/PocketHub,navychang/android,KishorAndroid/PocketHub,theiven70/PocketHub,PKRoma/PocketHub,larsgrefer/github-android-app,yuanhuihui/PocketHub,Meisolsson/PocketHub,roadrunner1987/PocketHub,JosephYao/android,micrologic/PocketHub,Calamus-Cajan/PocketHub,larsgrefer/pocket-hub,funsociety/PocketHub,huangsongyan/PocketHub,pockethub/PocketHub,mishin/ForkHub,kebenxiaoming/android-1,jchenga/android,lzy-h2o2/PocketHub,wang0818/android,tsdl2013/android,kebenxiaoming/android-1,wshh08/PocketHub,Liyue1314/PocketHub,samuelralak/ForkHub,Kevin16Wang/PocketHub,LeoLamCY/PocketHub,ISkyLove/PocketHub,Damonzh/PocketHub,arcivanov/ForkHub,JLLK/PocketHub-scala,danielferecatu/android,rmad17/PocketHub,rmad17/PocketHub,jonan/ForkHub,sam14305/bhoot.life,PeterDaveHello/PocketHub,abhishekbm/android,pockethub/PocketHub,liqk2014/PocketHub,sydneyagcaoili/PocketHub,zhangtianqiu/githubandroid,sudosurootdev/packages_apps_Github,work4life/PocketHub,mishin/ForkHub,zhuxiaohao/PocketHub,wang0818/android,xen0n/android,esironal/PocketHub,sudosurootdev/packages_apps_Github,navychang/android,tempbottle/PocketHub,yongjhih/PocketHub,condda/android,marceloneil/PocketHub,Leaking/android,Kevin16Wang/PocketHub,acemaster/android,xiaoleigua/PocketHub,xiaopengs/PocketHub,tempbottle/PocketHub,Calamus-Cajan/PocketHub,supercocoa/PocketHub,wshh08/PocketHub,larsgrefer/github-android-app,Tadakatsu/android,KishorAndroid/PocketHub,theiven70/PocketHub,roadrunner1987/PocketHub,yummy222/PocketHub,zhengxiaopeng/github-app,karllindmark/PocketHub,nvoron23/android,hufsm/PocketHub,larsgrefer/github-android-app,qiancy/PocketHub,common2015/PocketHub,xiaopengs/PocketHub,lzy-h2o2/PocketHub,tempbottle/PocketHub,ISkyLove/PocketHub,xiaopengs/PocketHub,bineanzhou/android_github,abhishekbm/android,danielferecatu/android,Androidbsw/android,JosephYao/android,reproio/github-for-android,sam14305/bhoot.life,Bloody-Badboy/PocketHub,gvaish/PocketHub,PeterDaveHello/PocketHub,jchenga/android,xfumihiro/PocketHub,gmyboy/android,PKRoma/PocketHub,JosephYao/android,xen0n/android,Liyue1314/PocketHub,marceloneil/PocketHub,vfs1234/android,gmyboy/android,supercocoa/PocketHub,sam14305/bhoot.life,generalzou/PocketHub,songful/PocketHub,cnoldtree/PocketHub,roadrunner1987/PocketHub,GeekHades/PocketHub,arcivanov/ForkHub,DeLaSalleUniversity-Manila/forkhub-JJCpro10,generalzou/PocketHub,simple88/PocketHub,kebenxiaoming/android-1,acemaster/android,songful/PocketHub,tsdl2013/android,songful/PocketHub,supercocoa/PocketHub,soztzfsnf/PocketHub,fadils/android,weiyihz/PocketHub,ISkyLove/PocketHub,yuanhuihui/PocketHub,usr80/Android,huangsongyan/PocketHub,larsgrefer/pocket-hub,Androidbsw/android,yytang2012/PocketHub,simple88/PocketHub,Bloody-Badboy/PocketHub,xiaoleigua/PocketHub,yytang2012/PocketHub,usr80/Android,Meisolsson/PocketHub,repanda/PocketHub,liqk2014/PocketHub,Tadakatsu/android,wubin28/android,navychang/android,cnoldtree/PocketHub,Katariaa/PocketHub,cnoldtree/PocketHub,vfs1234/android,karllindmark/PocketHub,qiancy/PocketHub,DeLaSalleUniversity-Manila/forkhub-JJCpro10,M13Kd/PocketHub,sydneyagcaoili/PocketHub,rmad17/PocketHub,nvoron23/android,fadils/android,funsociety/PocketHub,GeekHades/PocketHub,xfumihiro/ForkHub,njucsyyh/android,songful/PocketHub,funsociety/PocketHub,chaoallsome/PocketHub,tsdl2013/android,ywk248248/Forkhub_cloned,xfumihiro/PocketHub,M13Kd/PocketHub,hufsm/PocketHub,abhishekbm/android,xfumihiro/ForkHub,zhengxiaopeng/github-app,xen0n/android,ywk248248/Forkhub_cloned,qiancy/PocketHub,forkhubs/android,yuanhuihui/PocketHub,work4life/PocketHub,bineanzhou/android_github,Katariaa/PocketHub,gmyboy/android,acemaster/android,xfumihiro/ForkHub,esironal/PocketHub,Katariaa/PocketHub,samuelralak/ForkHub,weiyihz/PocketHub,sydneyagcaoili/PocketHub,hgl888/PocketHub,zhuxiaohao/PocketHub,PeterDaveHello/PocketHub,shekibobo/android,PKRoma/PocketHub,njucsyyh/android,jonan/ForkHub,Bloody-Badboy/PocketHub,njucsyyh/android,Cl3Kener/darkhub,GeekHades/PocketHub,KingLiuDao/android,shekibobo/android,Chalmers-SEP-GitHubApp-Group/android,reproio/github-for-android,KingLiuDao/android,repanda/PocketHub,theiven70/PocketHub,zhengxiaopeng/github-app,Chalmers-SEP-GitHubApp-Group/android,jonan/ForkHub,nvoron23/android,yongjhih/PocketHub,Cl3Kener/darkhub,yummy222/PocketHub,zhuxiaohao/PocketHub,Damonzh/PocketHub,weiyihz/PocketHub,LeoLamCY/PocketHub,PKRoma/github-android,wshh08/PocketHub,zhangtianqiu/githubandroid,Liyue1314/PocketHub,zhangtianqiu/githubandroid,esironal/PocketHub,arcivanov/ForkHub,marceloneil/PocketHub,pockethub/PocketHub,hufsm/PocketHub,PKRoma/github-android,PKRoma/PocketHub,Meisolsson/PocketHub,jchenga/android,forkhubs/android,lzy-h2o2/PocketHub,samuelralak/ForkHub,larsgrefer/pocket-hub,liqk2014/PocketHub,Androidbsw/android,xiaoleigua/PocketHub,gvaish/PocketHub,Leaking/android,shekibobo/android,kostaskoukouvis/android,Kevin16Wang/PocketHub,M13Kd/PocketHub,common2015/PocketHub,hgl888/PocketHub,KishorAndroid/PocketHub
java
## Code Before: package com.github.mobile.android; import static java.util.Arrays.asList; import android.app.Application; import android.app.Instrumentation; import android.content.Context; import android.util.Log; import com.google.inject.Module; import java.util.List; /** * Main GitHub application */ public class GitHubApplication extends Application { private static final String TAG = "GHA"; /** * Create main application */ public GitHubApplication() { } /** * Create main application * * @param context */ public GitHubApplication(Context context) { attachBaseContext(context); } /** * Create main application * * @param instrumentation */ public GitHubApplication(Instrumentation instrumentation) { attachBaseContext(instrumentation.getTargetContext()); } protected void addApplicationModules(List<Module> modules) { Log.i(TAG, "Adding application modules..."); modules.addAll(asList(new GitHubModule())); } } ## Instruction: Remove unneeded list creation to add single item ## Code After: package com.github.mobile.android; import android.app.Application; import android.app.Instrumentation; import android.content.Context; import android.util.Log; import com.google.inject.Module; import java.util.List; /** * Main GitHub application */ public class GitHubApplication extends Application { private static final String TAG = "GHA"; /** * Create main application */ public GitHubApplication() { } /** * Create main application * * @param context */ public GitHubApplication(Context context) { attachBaseContext(context); } /** * Create main application * * @param instrumentation */ public GitHubApplication(Instrumentation instrumentation) { attachBaseContext(instrumentation.getTargetContext()); } /** * Add modules * * @param modules */ protected void addApplicationModules(List<Module> modules) { Log.d(TAG, "Adding application modules..."); modules.add(new GitHubModule()); } }
# ... existing code ... package com.github.mobile.android; import android.app.Application; import android.app.Instrumentation; import android.content.Context; # ... modified code ... attachBaseContext(instrumentation.getTargetContext()); } /** * Add modules * * @param modules */ protected void addApplicationModules(List<Module> modules) { Log.d(TAG, "Adding application modules..."); modules.add(new GitHubModule()); } } # ... rest of the code ...
c6dae4cbd8d8dcbcd323526c2811fea9525bcb74
__init__.py
__init__.py
import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import pygame director = scene.Director() def init(): pygame.init() pygame.font.init()
import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import spyral.event import pygame director = scene.Director() def init(): pygame.init() pygame.font.init()
Add an event module import
Add an event module import
Python
lgpl-2.1
platipy/spyral
python
## Code Before: import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import pygame director = scene.Director() def init(): pygame.init() pygame.font.init() ## Instruction: Add an event module import ## Code After: import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import spyral.event import pygame director = scene.Director() def init(): pygame.init() pygame.font.init()
# ... existing code ... import spyral.gui import spyral.scene import spyral._lib import spyral.event import pygame director = scene.Director() # ... rest of the code ...
fecaf76acfde9223b0066c6a01dc51a19b95c766
api/src/main/java/net/md_5/bungee/api/plugin/PluginDescription.java
api/src/main/java/net/md_5/bungee/api/plugin/PluginDescription.java
package net.md_5.bungee.api.plugin; import java.util.Set; import lombok.AllArgsConstructor; import lombok.Data; /** * POJO representing the plugin.yml file. */ @Data @AllArgsConstructor public class PluginDescription { /** * Friendly name of the plugin. */ private String name; /** * Plugin main class. Needs to extend {@link Plugin}. */ private String main; /** * Plugin version. */ private String version; /** * Plugin author. */ private String author; /** * Plugin hard dependencies. */ private Set<String> depends; public PluginDescription() { } }
package net.md_5.bungee.api.plugin; import java.util.HashSet; import java.util.Set; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * POJO representing the plugin.yml file. */ @Data @NoArgsConstructor @AllArgsConstructor public class PluginDescription { /** * Friendly name of the plugin. */ private String name; /** * Plugin main class. Needs to extend {@link Plugin}. */ private String main; /** * Plugin version. */ private String version; /** * Plugin author. */ private String author; /** * Plugin hard dependencies. */ private Set<String> depends = new HashSet<>(); }
Initialize depends set to an empty set to prevent a NPE when no depends given.
Initialize depends set to an empty set to prevent a NPE when no depends given.
Java
bsd-3-clause
Yive/BungeeCord,mariolars/BungeeCord,LinEvil/BungeeCord,Xetius/BungeeCord,LetsPlayOnline/BungeeJumper,mariolars/BungeeCord,GamesConMCGames/Bungeecord,PrisonPvP/BungeeCord,starlis/BungeeCord,ConnorLinfoot/BungeeCord,LetsPlayOnline/BungeeJumper,Yive/BungeeCord,xxyy/BungeeCord,LolnetModPack/BungeeCord,GingerGeek/BungeeCord,LolnetModPack/BungeeCord,xxyy/BungeeCord,ewized/BungeeCord,PrisonPvP/BungeeCord,ConnorLinfoot/BungeeCord,btilm305/BungeeCord,PrisonPvP/BungeeCord,LolnetModPack/BungeeCord,XMeowTW/BungeeCord,TCPR/BungeeCord,TCPR/BungeeCord,mariolars/BungeeCord,BlueAnanas/BungeeCord,ConnorLinfoot/BungeeCord,Xetius/BungeeCord,btilm305/BungeeCord,TCPR/BungeeCord,BlueAnanas/BungeeCord,GamesConMCGames/Bungeecord,starlis/BungeeCord,GamesConMCGames/Bungeecord,LinEvil/BungeeCord,XMeowTW/BungeeCord,btilm305/BungeeCord,starlis/BungeeCord,LetsPlayOnline/BungeeJumper,dentmaged/BungeeCord,ewized/BungeeCord,Yive/BungeeCord,ewized/BungeeCord,XMeowTW/BungeeCord,dentmaged/BungeeCord,xxyy/BungeeCord,dentmaged/BungeeCord,GingerGeek/BungeeCord,GingerGeek/BungeeCord,Xetius/BungeeCord,LinEvil/BungeeCord,BlueAnanas/BungeeCord
java
## Code Before: package net.md_5.bungee.api.plugin; import java.util.Set; import lombok.AllArgsConstructor; import lombok.Data; /** * POJO representing the plugin.yml file. */ @Data @AllArgsConstructor public class PluginDescription { /** * Friendly name of the plugin. */ private String name; /** * Plugin main class. Needs to extend {@link Plugin}. */ private String main; /** * Plugin version. */ private String version; /** * Plugin author. */ private String author; /** * Plugin hard dependencies. */ private Set<String> depends; public PluginDescription() { } } ## Instruction: Initialize depends set to an empty set to prevent a NPE when no depends given. ## Code After: package net.md_5.bungee.api.plugin; import java.util.HashSet; import java.util.Set; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * POJO representing the plugin.yml file. */ @Data @NoArgsConstructor @AllArgsConstructor public class PluginDescription { /** * Friendly name of the plugin. */ private String name; /** * Plugin main class. Needs to extend {@link Plugin}. */ private String main; /** * Plugin version. */ private String version; /** * Plugin author. */ private String author; /** * Plugin hard dependencies. */ private Set<String> depends = new HashSet<>(); }
// ... existing code ... package net.md_5.bungee.api.plugin; import java.util.HashSet; import java.util.Set; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * POJO representing the plugin.yml file. */ @Data @NoArgsConstructor @AllArgsConstructor public class PluginDescription { // ... modified code ... /** * Plugin hard dependencies. */ private Set<String> depends = new HashSet<>(); } // ... rest of the code ...
b347423f3d9063b36374e73f31aba4f92b2b1d32
src/main/java/no/javazone/VertxHttpServer.java
src/main/java/no/javazone/VertxHttpServer.java
package no.javazone; import io.vertx.core.Vertx; import io.vertx.core.json.Json; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; public class VertxHttpServer { public static void main(String[] args) { Vertx vertx = Vertx.vertx(); Router router = Router.router(vertx); router.get("/person/:id").handler(VertxHttpServer::returnPerson); router.get("/address/:id").handler(VertxHttpServer::returnAddress); router.get("/").handler(ctx -> ctx.response().end("Hello world")); vertx.createHttpServer().requestHandler(router::accept).listen(8080); } private static void returnPerson(RoutingContext ctx) { String id = ctx.request().getParam("id"); ctx.response() .setStatusCode(200) .end(Json.encode(new TypicalExamples.Person(id, "Me", 29))); System.out.println("requested person " + id); } private static void returnAddress(RoutingContext ctx) { String id = ctx.request().getParam("id"); ctx.response() .setStatusCode(200) .end(Json.encode(new TypicalExamples.Address(id, "House 1", "Street 2", "1337", "Sandvika"))); System.out.println("requested address " + id); } }
package no.javazone; import io.vertx.core.Vertx; import io.vertx.core.json.Json; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; public class VertxHttpServer { public static void main(String[] args) { Vertx vertx = Vertx.vertx(); Router router = Router.router(vertx); router.get("/person/:id").handler(VertxHttpServer::returnPerson); router.get("/address/:id").handler(VertxHttpServer::returnAddress); router.get("/").handler(ctx -> ctx.response().end("Hello world")); vertx.createHttpServer().requestHandler(router::accept).listen(8080); System.out.println("Server started on port 8080"); } private static void returnPerson(RoutingContext ctx) { String id = ctx.request().getParam("id"); ctx.response() .setStatusCode(200) .end(Json.encode(new TypicalExamples.Person(id, "Me", 29))); System.out.println("requested person " + id); } private static void returnAddress(RoutingContext ctx) { String id = ctx.request().getParam("id"); ctx.response() .setStatusCode(200) .end(Json.encode(new TypicalExamples.Address(id, "House 1", "Street 2", "1337", "Sandvika"))); System.out.println("requested address " + id); } }
Add output when server has started.
Add output when server has started.
Java
mit
ChristinGorman/javazone2016
java
## Code Before: package no.javazone; import io.vertx.core.Vertx; import io.vertx.core.json.Json; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; public class VertxHttpServer { public static void main(String[] args) { Vertx vertx = Vertx.vertx(); Router router = Router.router(vertx); router.get("/person/:id").handler(VertxHttpServer::returnPerson); router.get("/address/:id").handler(VertxHttpServer::returnAddress); router.get("/").handler(ctx -> ctx.response().end("Hello world")); vertx.createHttpServer().requestHandler(router::accept).listen(8080); } private static void returnPerson(RoutingContext ctx) { String id = ctx.request().getParam("id"); ctx.response() .setStatusCode(200) .end(Json.encode(new TypicalExamples.Person(id, "Me", 29))); System.out.println("requested person " + id); } private static void returnAddress(RoutingContext ctx) { String id = ctx.request().getParam("id"); ctx.response() .setStatusCode(200) .end(Json.encode(new TypicalExamples.Address(id, "House 1", "Street 2", "1337", "Sandvika"))); System.out.println("requested address " + id); } } ## Instruction: Add output when server has started. ## Code After: package no.javazone; import io.vertx.core.Vertx; import io.vertx.core.json.Json; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; public class VertxHttpServer { public static void main(String[] args) { Vertx vertx = Vertx.vertx(); Router router = Router.router(vertx); router.get("/person/:id").handler(VertxHttpServer::returnPerson); router.get("/address/:id").handler(VertxHttpServer::returnAddress); router.get("/").handler(ctx -> ctx.response().end("Hello world")); vertx.createHttpServer().requestHandler(router::accept).listen(8080); System.out.println("Server started on port 8080"); } private static void returnPerson(RoutingContext ctx) { String id = ctx.request().getParam("id"); ctx.response() .setStatusCode(200) .end(Json.encode(new TypicalExamples.Person(id, "Me", 29))); System.out.println("requested person " + id); } private static void returnAddress(RoutingContext ctx) { String id = ctx.request().getParam("id"); ctx.response() .setStatusCode(200) .end(Json.encode(new TypicalExamples.Address(id, "House 1", "Street 2", "1337", "Sandvika"))); System.out.println("requested address " + id); } }
# ... existing code ... router.get("/address/:id").handler(VertxHttpServer::returnAddress); router.get("/").handler(ctx -> ctx.response().end("Hello world")); vertx.createHttpServer().requestHandler(router::accept).listen(8080); System.out.println("Server started on port 8080"); } private static void returnPerson(RoutingContext ctx) { # ... rest of the code ...
f643e1931ce8e0c4d11db4d8b9eb9ac75b683a80
tests/test_credentials.py
tests/test_credentials.py
from pyutrack import Credentials from tests import PyutrackTest class CredentialsTests(PyutrackTest): def test_empty(self): c = Credentials('root') self.assertIsNone(c.password) self.assertIsNone(c.cookies)
import json import keyring from pyutrack import Credentials from tests import PyutrackTest class CredentialsTests(PyutrackTest): def test_empty(self): c = Credentials('root') self.assertIsNone(c.password) self.assertIsNone(c.cookies) def test_persistence(self): c = Credentials('root', 'passwd', {"key": "value"}) c.persist() self.assertEqual( keyring.get_password(Credentials.KEYRING_PASSWORD, 'root'), 'passwd' ) self.assertEqual( json.loads(keyring.get_password(Credentials.KEYRING_COOKIE, 'root')), {"key": "value"} )
Add test for credential persistence
Add test for credential persistence
Python
mit
alisaifee/pyutrack,alisaifee/pyutrack
python
## Code Before: from pyutrack import Credentials from tests import PyutrackTest class CredentialsTests(PyutrackTest): def test_empty(self): c = Credentials('root') self.assertIsNone(c.password) self.assertIsNone(c.cookies) ## Instruction: Add test for credential persistence ## Code After: import json import keyring from pyutrack import Credentials from tests import PyutrackTest class CredentialsTests(PyutrackTest): def test_empty(self): c = Credentials('root') self.assertIsNone(c.password) self.assertIsNone(c.cookies) def test_persistence(self): c = Credentials('root', 'passwd', {"key": "value"}) c.persist() self.assertEqual( keyring.get_password(Credentials.KEYRING_PASSWORD, 'root'), 'passwd' ) self.assertEqual( json.loads(keyring.get_password(Credentials.KEYRING_COOKIE, 'root')), {"key": "value"} )
// ... existing code ... import json import keyring from pyutrack import Credentials from tests import PyutrackTest // ... modified code ... c = Credentials('root') self.assertIsNone(c.password) self.assertIsNone(c.cookies) def test_persistence(self): c = Credentials('root', 'passwd', {"key": "value"}) c.persist() self.assertEqual( keyring.get_password(Credentials.KEYRING_PASSWORD, 'root'), 'passwd' ) self.assertEqual( json.loads(keyring.get_password(Credentials.KEYRING_COOKIE, 'root')), {"key": "value"} ) // ... rest of the code ...
89b14bd0add6a56d9128f2ce3fa4ca710f64d5d7
opal/tests/test_utils.py
opal/tests/test_utils.py
from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html']))
from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) def test_import_no_period(self): with self.assertRaises(ImportError): utils.stringport('wotcha') def test_import_perioded_thing(self): self.assertEqual(TestCase, utils.stringport('django.test.TestCase')) def test_empty_name_is_valueerror(self): with self.assertRaises(ValueError): utils.stringport('') class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html']))
Add some tests for stringport
Add some tests for stringport
Python
agpl-3.0
khchine5/opal,khchine5/opal,khchine5/opal
python
## Code Before: from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html'])) ## Instruction: Add some tests for stringport ## Code After: from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) def test_import_no_period(self): with self.assertRaises(ImportError): utils.stringport('wotcha') def test_import_perioded_thing(self): self.assertEqual(TestCase, utils.stringport('django.test.TestCase')) def test_empty_name_is_valueerror(self): with self.assertRaises(ValueError): utils.stringport('') class ItersubclassesTestCase(TestCase): def test_tree_structure(self): class A(object): pass class B(A): pass class C(B, utils.AbstractBase): pass class D(C): pass results = {i for i in utils._itersubclasses(A)} self.assertEqual(results, set([B, D])) class FindTemplateTestCase(TestCase): def test_find_template_first_exists(self): self.assertEqual('base.html', utils.find_template(['base.html', 'baser.html', 'basest.html'])) def test_find_template_one_exists(self): self.assertEqual('base.html', utils.find_template(['baser.html', 'base.html', 'basest.html'])) def test_find_template_none_exists(self): self.assertEqual(None, utils.find_template(['baser.html', 'basest.html']))
// ... existing code ... def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) def test_import_no_period(self): with self.assertRaises(ImportError): utils.stringport('wotcha') def test_import_perioded_thing(self): self.assertEqual(TestCase, utils.stringport('django.test.TestCase')) def test_empty_name_is_valueerror(self): with self.assertRaises(ValueError): utils.stringport('') class ItersubclassesTestCase(TestCase): // ... rest of the code ...
d192eda9cf103f88468acdf40dc77114d30bde67
lib/src/lib.c
lib/src/lib.c
// The Tree-sitter runtime library can be built by compiling this // one source file. // // The following directories must be added to the include path: // - src // - include // - externals/utf8proc #include "./get_changed_ranges.c" #include "./language.c" #include "./lexer.c" #include "./node.c" #include "./parser.c" #include "./stack.c" #include "./subtree.c" #include "./tree_cursor.c" #include "./tree.c" #include "./utf16.c" #include "utf8proc.c"
// The Tree-sitter library can be built by compiling this one source file. // // The following directories must be added to the include path: // - src // - include // - externals/utf8proc #include "./get_changed_ranges.c" #include "./language.c" #include "./lexer.c" #include "./node.c" #include "./parser.c" #include "./stack.c" #include "./subtree.c" #include "./tree_cursor.c" #include "./tree.c" #include "./utf16.c" #include "utf8proc.c"
Remove stray word 'runtime' from comment
Remove stray word 'runtime' from comment
C
mit
tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter,tree-sitter/tree-sitter
c
## Code Before: // The Tree-sitter runtime library can be built by compiling this // one source file. // // The following directories must be added to the include path: // - src // - include // - externals/utf8proc #include "./get_changed_ranges.c" #include "./language.c" #include "./lexer.c" #include "./node.c" #include "./parser.c" #include "./stack.c" #include "./subtree.c" #include "./tree_cursor.c" #include "./tree.c" #include "./utf16.c" #include "utf8proc.c" ## Instruction: Remove stray word 'runtime' from comment ## Code After: // The Tree-sitter library can be built by compiling this one source file. // // The following directories must be added to the include path: // - src // - include // - externals/utf8proc #include "./get_changed_ranges.c" #include "./language.c" #include "./lexer.c" #include "./node.c" #include "./parser.c" #include "./stack.c" #include "./subtree.c" #include "./tree_cursor.c" #include "./tree.c" #include "./utf16.c" #include "utf8proc.c"
... // The Tree-sitter library can be built by compiling this one source file. // // The following directories must be added to the include path: // - src ...
e3d00e6c3e62e5cfa457529fc2dddfb814382db6
packages/dcos-integration-test/extra/test_metronome.py
packages/dcos-integration-test/extra/test_metronome.py
def test_metronome(dcos_api_session): job = { 'description': 'Test Metronome API regressions', 'id': 'test.metronome', 'run': { 'cmd': 'ls', 'docker': {'image': 'busybox:latest'}, 'cpus': 1, 'mem': 512, 'user': 'nobody', 'restart': {'policy': 'ON_FAILURE'} } } dcos_api_session.metronome_one_off(job)
def test_metronome(dcos_api_session): job = { 'description': 'Test Metronome API regressions', 'id': 'test.metronome', 'run': { 'cmd': 'ls', 'docker': {'image': 'busybox:latest'}, 'cpus': 1, 'mem': 512, 'disk' 0, 'user': 'nobody', 'restart': {'policy': 'ON_FAILURE'} } } dcos_api_session.metronome_one_off(job)
Fix the Metronome integration test
Fix the Metronome integration test
Python
apache-2.0
dcos/dcos,amitaekbote/dcos,branden/dcos,mesosphere-mergebot/mergebot-test-dcos,surdy/dcos,mesosphere-mergebot/mergebot-test-dcos,surdy/dcos,kensipe/dcos,mellenburg/dcos,mellenburg/dcos,GoelDeepak/dcos,dcos/dcos,mellenburg/dcos,mesosphere-mergebot/dcos,kensipe/dcos,amitaekbote/dcos,kensipe/dcos,GoelDeepak/dcos,mesosphere-mergebot/dcos,branden/dcos,branden/dcos,mesosphere-mergebot/dcos,mellenburg/dcos,branden/dcos,dcos/dcos,mesosphere-mergebot/mergebot-test-dcos,kensipe/dcos,mesosphere-mergebot/dcos,amitaekbote/dcos,dcos/dcos,dcos/dcos,GoelDeepak/dcos,surdy/dcos,amitaekbote/dcos,surdy/dcos,GoelDeepak/dcos,mesosphere-mergebot/mergebot-test-dcos
python
## Code Before: def test_metronome(dcos_api_session): job = { 'description': 'Test Metronome API regressions', 'id': 'test.metronome', 'run': { 'cmd': 'ls', 'docker': {'image': 'busybox:latest'}, 'cpus': 1, 'mem': 512, 'user': 'nobody', 'restart': {'policy': 'ON_FAILURE'} } } dcos_api_session.metronome_one_off(job) ## Instruction: Fix the Metronome integration test ## Code After: def test_metronome(dcos_api_session): job = { 'description': 'Test Metronome API regressions', 'id': 'test.metronome', 'run': { 'cmd': 'ls', 'docker': {'image': 'busybox:latest'}, 'cpus': 1, 'mem': 512, 'disk' 0, 'user': 'nobody', 'restart': {'policy': 'ON_FAILURE'} } } dcos_api_session.metronome_one_off(job)
# ... existing code ... 'docker': {'image': 'busybox:latest'}, 'cpus': 1, 'mem': 512, 'disk' 0, 'user': 'nobody', 'restart': {'policy': 'ON_FAILURE'} } # ... rest of the code ...
150e338b7d2793c434d7e2f21aef061f35634476
openspending/test/__init__.py
openspending/test/__init__.py
import os import sys from paste.deploy import appconfig from openspending import mongo from helpers import clean_all __all__ = ['TestCase', 'DatabaseTestCase'] here_dir = os.getcwd() config = appconfig('config:test.ini', relative_to=here_dir) mongo.configure(config) class TestCase(object): def setup(self): pass def teardown(self): pass class DatabaseTestCase(TestCase): def teardown(self): clean_all() super(DatabaseTestCase, self).teardown()
import os import sys from pylons import config from openspending import mongo from .helpers import clean_all __all__ = ['TestCase', 'DatabaseTestCase'] mongo.configure(config) class TestCase(object): def setup(self): pass def teardown(self): pass class DatabaseTestCase(TestCase): def teardown(self): clean_all() super(DatabaseTestCase, self).teardown()
Use config given on command line
Use config given on command line
Python
agpl-3.0
pudo/spendb,openspending/spendb,openspending/spendb,nathanhilbert/FPA_Core,pudo/spendb,johnjohndoe/spendb,CivicVision/datahub,USStateDept/FPA_Core,johnjohndoe/spendb,USStateDept/FPA_Core,CivicVision/datahub,nathanhilbert/FPA_Core,johnjohndoe/spendb,openspending/spendb,USStateDept/FPA_Core,spendb/spendb,nathanhilbert/FPA_Core,spendb/spendb,pudo/spendb,spendb/spendb,CivicVision/datahub
python
## Code Before: import os import sys from paste.deploy import appconfig from openspending import mongo from helpers import clean_all __all__ = ['TestCase', 'DatabaseTestCase'] here_dir = os.getcwd() config = appconfig('config:test.ini', relative_to=here_dir) mongo.configure(config) class TestCase(object): def setup(self): pass def teardown(self): pass class DatabaseTestCase(TestCase): def teardown(self): clean_all() super(DatabaseTestCase, self).teardown() ## Instruction: Use config given on command line ## Code After: import os import sys from pylons import config from openspending import mongo from .helpers import clean_all __all__ = ['TestCase', 'DatabaseTestCase'] mongo.configure(config) class TestCase(object): def setup(self): pass def teardown(self): pass class DatabaseTestCase(TestCase): def teardown(self): clean_all() super(DatabaseTestCase, self).teardown()
... import os import sys from pylons import config from openspending import mongo from .helpers import clean_all __all__ = ['TestCase', 'DatabaseTestCase'] mongo.configure(config) class TestCase(object): ...
db9712cdc92385f6abc608d196fd82cf3dc356b2
src/main/java/org/mkonrad/fizzbuzz/FizzBuzz.java
src/main/java/org/mkonrad/fizzbuzz/FizzBuzz.java
package org.mkonrad.fizzbuzz; import java.io.PrintStream; import java.util.stream.IntStream; /** * @author Markus Konrad */ public final class FizzBuzz { private final PrintStream printStream; public FizzBuzz(PrintStream printStream) { this.printStream = printStream; } public final void run(int numberOfRounds){ if (numberOfRounds < 1) { printStream.println("Please specify a positive value for the parameter \"numberOfRounds\""); return; } IntStream.range(1, numberOfRounds + 1).mapToObj(i -> { if (i % 3 == 0) { if (i % 5 == 0) { return "FizzBuzz"; } return "Fizz"; } if (i % 5 == 0) { return "Buzz"; } return String.valueOf(i); }).forEach(printStream::println); } public static void main(String[] args) { new FizzBuzz(System.out).run(100); } }
package org.mkonrad.fizzbuzz; import java.io.PrintStream; import java.util.stream.IntStream; /** * @author Markus Konrad */ public final class FizzBuzz { private final PrintStream printStream; public FizzBuzz(PrintStream printStream) { this.printStream = printStream; } public final void run(int numberOfRounds){ if (numberOfRounds < 1) { printStream.println("Please specify a positive value for the parameter \"numberOfRounds\""); return; } IntStream.range(1, numberOfRounds + 1) .mapToObj(i -> { if (i % 3 == 0) { if (i % 5 == 0) { return "FizzBuzz"; } return "Fizz"; } if (i % 5 == 0) { return "Buzz"; } return String.valueOf(i); }) .forEach(printStream::println); } public static void main(String[] args) { new FizzBuzz(System.out).run(100); } }
Migrate implementation to Java 8
Migrate implementation to Java 8
Java
mit
mkonrad-dev/FizzBuzz
java
## Code Before: package org.mkonrad.fizzbuzz; import java.io.PrintStream; import java.util.stream.IntStream; /** * @author Markus Konrad */ public final class FizzBuzz { private final PrintStream printStream; public FizzBuzz(PrintStream printStream) { this.printStream = printStream; } public final void run(int numberOfRounds){ if (numberOfRounds < 1) { printStream.println("Please specify a positive value for the parameter \"numberOfRounds\""); return; } IntStream.range(1, numberOfRounds + 1).mapToObj(i -> { if (i % 3 == 0) { if (i % 5 == 0) { return "FizzBuzz"; } return "Fizz"; } if (i % 5 == 0) { return "Buzz"; } return String.valueOf(i); }).forEach(printStream::println); } public static void main(String[] args) { new FizzBuzz(System.out).run(100); } } ## Instruction: Migrate implementation to Java 8 ## Code After: package org.mkonrad.fizzbuzz; import java.io.PrintStream; import java.util.stream.IntStream; /** * @author Markus Konrad */ public final class FizzBuzz { private final PrintStream printStream; public FizzBuzz(PrintStream printStream) { this.printStream = printStream; } public final void run(int numberOfRounds){ if (numberOfRounds < 1) { printStream.println("Please specify a positive value for the parameter \"numberOfRounds\""); return; } IntStream.range(1, numberOfRounds + 1) .mapToObj(i -> { if (i % 3 == 0) { if (i % 5 == 0) { return "FizzBuzz"; } return "Fizz"; } if (i % 5 == 0) { return "Buzz"; } return String.valueOf(i); }) .forEach(printStream::println); } public static void main(String[] args) { new FizzBuzz(System.out).run(100); } }
... printStream.println("Please specify a positive value for the parameter \"numberOfRounds\""); return; } IntStream.range(1, numberOfRounds + 1) .mapToObj(i -> { if (i % 3 == 0) { if (i % 5 == 0) { return "FizzBuzz"; } return "Fizz"; } if (i % 5 == 0) { return "Buzz"; } return String.valueOf(i); }) .forEach(printStream::println); } public static void main(String[] args) { ...
41f244171011a1bbb4a2a77e779979ba8cc9ecb5
zeus/api/resources/auth_index.py
zeus/api/resources/auth_index.py
import json from zeus import auth from zeus.api import client from zeus.exceptions import ApiError from zeus.models import Email, Identity from .base import Resource from ..schemas import EmailSchema, IdentitySchema, UserSchema emails_schema = EmailSchema(many=True, strict=True) identities_schema = IdentitySchema(many=True, strict=True) user_schema = UserSchema(strict=True) class AuthIndexResource(Resource): auth_required = False def get(self): """ Return information on the currently authenticated user. """ try: user_response = client.get('/users/me') except ApiError as exc: if exc.code == 401: return { 'isAuthenticated': False, } identity_list = list(Identity.query.filter( Identity.user_id == user_response.data['id'], )) email_list = list(Email.query.filter( Email.user_id == user_response.data['id'], )) return { 'isAuthenticated': True, 'user': json.loads(user_response.data), 'emails': emails_schema.dump(email_list).data, 'identities': identities_schema.dump(identity_list).data, } def delete(self): """ Logout. """ auth.logout() return { 'isAuthenticated': False, 'user': None, }
import json from zeus import auth from zeus.api import client from zeus.exceptions import ApiError from zeus.models import Email, Identity from .base import Resource from ..schemas import EmailSchema, IdentitySchema, UserSchema emails_schema = EmailSchema(many=True, strict=True) identities_schema = IdentitySchema(many=True, strict=True) user_schema = UserSchema(strict=True) class AuthIndexResource(Resource): auth_required = False def get(self): """ Return information on the currently authenticated user. """ try: user_response = client.get('/users/me') except ApiError as exc: if exc.code == 401: return { 'isAuthenticated': False, } user = json.loads(user_response.data) identity_list = list(Identity.query.filter( Identity.user_id == user['id'], )) email_list = list(Email.query.filter( Email.user_id == user['id'], )) return { 'isAuthenticated': True, 'user': user, 'emails': emails_schema.dump(email_list).data, 'identities': identities_schema.dump(identity_list).data, } def delete(self): """ Logout. """ auth.logout() return { 'isAuthenticated': False, 'user': None, }
Fix auth API usage (this is why we wait for CI)
Fix auth API usage (this is why we wait for CI)
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
python
## Code Before: import json from zeus import auth from zeus.api import client from zeus.exceptions import ApiError from zeus.models import Email, Identity from .base import Resource from ..schemas import EmailSchema, IdentitySchema, UserSchema emails_schema = EmailSchema(many=True, strict=True) identities_schema = IdentitySchema(many=True, strict=True) user_schema = UserSchema(strict=True) class AuthIndexResource(Resource): auth_required = False def get(self): """ Return information on the currently authenticated user. """ try: user_response = client.get('/users/me') except ApiError as exc: if exc.code == 401: return { 'isAuthenticated': False, } identity_list = list(Identity.query.filter( Identity.user_id == user_response.data['id'], )) email_list = list(Email.query.filter( Email.user_id == user_response.data['id'], )) return { 'isAuthenticated': True, 'user': json.loads(user_response.data), 'emails': emails_schema.dump(email_list).data, 'identities': identities_schema.dump(identity_list).data, } def delete(self): """ Logout. """ auth.logout() return { 'isAuthenticated': False, 'user': None, } ## Instruction: Fix auth API usage (this is why we wait for CI) ## Code After: import json from zeus import auth from zeus.api import client from zeus.exceptions import ApiError from zeus.models import Email, Identity from .base import Resource from ..schemas import EmailSchema, IdentitySchema, UserSchema emails_schema = EmailSchema(many=True, strict=True) identities_schema = IdentitySchema(many=True, strict=True) user_schema = UserSchema(strict=True) class AuthIndexResource(Resource): auth_required = False def get(self): """ Return information on the currently authenticated user. """ try: user_response = client.get('/users/me') except ApiError as exc: if exc.code == 401: return { 'isAuthenticated': False, } user = json.loads(user_response.data) identity_list = list(Identity.query.filter( Identity.user_id == user['id'], )) email_list = list(Email.query.filter( Email.user_id == user['id'], )) return { 'isAuthenticated': True, 'user': user, 'emails': emails_schema.dump(email_list).data, 'identities': identities_schema.dump(identity_list).data, } def delete(self): """ Logout. """ auth.logout() return { 'isAuthenticated': False, 'user': None, }
... 'isAuthenticated': False, } user = json.loads(user_response.data) identity_list = list(Identity.query.filter( Identity.user_id == user['id'], )) email_list = list(Email.query.filter( Email.user_id == user['id'], )) return { 'isAuthenticated': True, 'user': user, 'emails': emails_schema.dump(email_list).data, 'identities': identities_schema.dump(identity_list).data, } ...
ab25537b67b14a8574028280c1e16637faa8037c
gunicorn/workers/gtornado.py
gunicorn/workers/gtornado.py
import os import sys from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop, PeriodicCallback from gunicorn.workers.base import Worker from gunicorn import __version__ as gversion def patch_request_handler(): web = sys.modules.pop("tornado.web") old_clear = web.RequestHandler.clear def clear(self): old_clear(self) self._headers["Server"] += " (Gunicorn/%s)" % gversion web.RequestHandler.clear = clear sys.modules["tornado.web"] = web class TornadoWorker(Worker): @classmethod def setup(cls): patch_request_handler() def watchdog(self): self.notify() if self.ppid != os.getppid(): self.log.info("Parent changed, shutting down: %s" % self) self.ioloop.stop() def run(self): self.socket.setblocking(0) self.ioloop = IOLoop.instance() PeriodicCallback(self.watchdog, 1000, io_loop=self.ioloop).start() server = HTTPServer(self.app, io_loop=self.ioloop) server._socket = self.socket server.start(num_processes=1) self.ioloop.start()
import os import sys import tornado.web from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop, PeriodicCallback from gunicorn.workers.base import Worker from gunicorn import __version__ as gversion def patch_request_handler(): web = sys.modules.pop("tornado.web") old_clear = web.RequestHandler.clear def clear(self): old_clear(self) self._headers["Server"] += " (Gunicorn/%s)" % gversion web.RequestHandler.clear = clear sys.modules["tornado.web"] = web class TornadoWorker(Worker): @classmethod def setup(cls): patch_request_handler() def watchdog(self): self.notify() if self.ppid != os.getppid(): self.log.info("Parent changed, shutting down: %s" % self) self.ioloop.stop() def run(self): self.socket.setblocking(0) self.ioloop = IOLoop.instance() PeriodicCallback(self.watchdog, 1000, io_loop=self.ioloop).start() server = HTTPServer(self.app, io_loop=self.ioloop) server._socket = self.socket server.start(num_processes=1) self.ioloop.start()
Fix assumption that tornado.web was imported.
Fix assumption that tornado.web was imported.
Python
mit
mvaled/gunicorn,wong2/gunicorn,prezi/gunicorn,elelianghh/gunicorn,wong2/gunicorn,WSDC-NITWarangal/gunicorn,MrKiven/gunicorn,mvaled/gunicorn,alex/gunicorn,1stvamp/gunicorn,z-fork/gunicorn,1stvamp/gunicorn,ephes/gunicorn,prezi/gunicorn,gtrdotmcs/gunicorn,tejasmanohar/gunicorn,urbaniak/gunicorn,gtrdotmcs/gunicorn,prezi/gunicorn,harrisonfeng/gunicorn,zhoucen/gunicorn,alex/gunicorn,urbaniak/gunicorn,ccl0326/gunicorn,ccl0326/gunicorn,jamesblunt/gunicorn,alex/gunicorn,pschanely/gunicorn,pschanely/gunicorn,1stvamp/gunicorn,jamesblunt/gunicorn,jamesblunt/gunicorn,GitHublong/gunicorn,beni55/gunicorn,malept/gunicorn,pschanely/gunicorn,gtrdotmcs/gunicorn,ammaraskar/gunicorn,malept/gunicorn,zhoucen/gunicorn,tempbottle/gunicorn,zhoucen/gunicorn,malept/gunicorn,keakon/gunicorn,ccl0326/gunicorn,urbaniak/gunicorn,wong2/gunicorn,mvaled/gunicorn
python
## Code Before: import os import sys from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop, PeriodicCallback from gunicorn.workers.base import Worker from gunicorn import __version__ as gversion def patch_request_handler(): web = sys.modules.pop("tornado.web") old_clear = web.RequestHandler.clear def clear(self): old_clear(self) self._headers["Server"] += " (Gunicorn/%s)" % gversion web.RequestHandler.clear = clear sys.modules["tornado.web"] = web class TornadoWorker(Worker): @classmethod def setup(cls): patch_request_handler() def watchdog(self): self.notify() if self.ppid != os.getppid(): self.log.info("Parent changed, shutting down: %s" % self) self.ioloop.stop() def run(self): self.socket.setblocking(0) self.ioloop = IOLoop.instance() PeriodicCallback(self.watchdog, 1000, io_loop=self.ioloop).start() server = HTTPServer(self.app, io_loop=self.ioloop) server._socket = self.socket server.start(num_processes=1) self.ioloop.start() ## Instruction: Fix assumption that tornado.web was imported. ## Code After: import os import sys import tornado.web from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop, PeriodicCallback from gunicorn.workers.base import Worker from gunicorn import __version__ as gversion def patch_request_handler(): web = sys.modules.pop("tornado.web") old_clear = web.RequestHandler.clear def clear(self): old_clear(self) self._headers["Server"] += " (Gunicorn/%s)" % gversion web.RequestHandler.clear = clear sys.modules["tornado.web"] = web class TornadoWorker(Worker): @classmethod def setup(cls): patch_request_handler() def watchdog(self): self.notify() if self.ppid != os.getppid(): self.log.info("Parent changed, shutting down: %s" % self) self.ioloop.stop() def run(self): self.socket.setblocking(0) self.ioloop = IOLoop.instance() PeriodicCallback(self.watchdog, 1000, io_loop=self.ioloop).start() server = HTTPServer(self.app, io_loop=self.ioloop) server._socket = self.socket server.start(num_processes=1) self.ioloop.start()
# ... existing code ... import os import sys import tornado.web from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop, PeriodicCallback # ... rest of the code ...
e3aa2ca9d9fb74de6512acd04c509a41c176040a
pdc/apps/repository/filters.py
pdc/apps/repository/filters.py
import django_filters as filters from pdc.apps.common.filters import MultiValueFilter from . import models class RepoFilter(filters.FilterSet): arch = MultiValueFilter(name='variant_arch__arch__name') content_category = MultiValueFilter(name='content_category__name') content_format = MultiValueFilter(name='content_format__name') release_id = MultiValueFilter(name='variant_arch__variant__release__release_id') variant_uid = MultiValueFilter(name='variant_arch__variant__variant_uid') repo_family = MultiValueFilter(name='repo_family__name') service = MultiValueFilter(name='service__name') shadow = filters.BooleanFilter() product_id = MultiValueFilter() class Meta: model = models.Repo fields = ('arch', 'content_category', 'content_format', 'name', 'release_id', 'repo_family', 'service', 'shadow', 'variant_uid', 'product_id') class RepoFamilyFilter(filters.FilterSet): name = filters.CharFilter(lookup_type="icontains") class Meta: model = models.RepoFamily fields = ('name',)
import django_filters as filters from pdc.apps.common.filters import MultiValueFilter, MultiIntFilter from . import models class RepoFilter(filters.FilterSet): arch = MultiValueFilter(name='variant_arch__arch__name') content_category = MultiValueFilter(name='content_category__name') content_format = MultiValueFilter(name='content_format__name') release_id = MultiValueFilter(name='variant_arch__variant__release__release_id') variant_uid = MultiValueFilter(name='variant_arch__variant__variant_uid') repo_family = MultiValueFilter(name='repo_family__name') service = MultiValueFilter(name='service__name') shadow = filters.BooleanFilter() product_id = MultiIntFilter() class Meta: model = models.Repo fields = ('arch', 'content_category', 'content_format', 'name', 'release_id', 'repo_family', 'service', 'shadow', 'variant_uid', 'product_id') class RepoFamilyFilter(filters.FilterSet): name = filters.CharFilter(lookup_type="icontains") class Meta: model = models.RepoFamily fields = ('name',)
Fix product_id filter on content delivery repos
Fix product_id filter on content delivery repos The value should be an integer. JIRA: PDC-1104
Python
mit
release-engineering/product-definition-center,release-engineering/product-definition-center,lao605/product-definition-center,lao605/product-definition-center,product-definition-center/product-definition-center,pombredanne/product-definition-center,xychu/product-definition-center,xychu/product-definition-center,pombredanne/product-definition-center,product-definition-center/product-definition-center,product-definition-center/product-definition-center,lao605/product-definition-center,xychu/product-definition-center,pombredanne/product-definition-center,tzhaoredhat/automation,release-engineering/product-definition-center,release-engineering/product-definition-center,xychu/product-definition-center,tzhaoredhat/automation,lao605/product-definition-center,tzhaoredhat/automation,tzhaoredhat/automation,product-definition-center/product-definition-center,pombredanne/product-definition-center
python
## Code Before: import django_filters as filters from pdc.apps.common.filters import MultiValueFilter from . import models class RepoFilter(filters.FilterSet): arch = MultiValueFilter(name='variant_arch__arch__name') content_category = MultiValueFilter(name='content_category__name') content_format = MultiValueFilter(name='content_format__name') release_id = MultiValueFilter(name='variant_arch__variant__release__release_id') variant_uid = MultiValueFilter(name='variant_arch__variant__variant_uid') repo_family = MultiValueFilter(name='repo_family__name') service = MultiValueFilter(name='service__name') shadow = filters.BooleanFilter() product_id = MultiValueFilter() class Meta: model = models.Repo fields = ('arch', 'content_category', 'content_format', 'name', 'release_id', 'repo_family', 'service', 'shadow', 'variant_uid', 'product_id') class RepoFamilyFilter(filters.FilterSet): name = filters.CharFilter(lookup_type="icontains") class Meta: model = models.RepoFamily fields = ('name',) ## Instruction: Fix product_id filter on content delivery repos The value should be an integer. JIRA: PDC-1104 ## Code After: import django_filters as filters from pdc.apps.common.filters import MultiValueFilter, MultiIntFilter from . import models class RepoFilter(filters.FilterSet): arch = MultiValueFilter(name='variant_arch__arch__name') content_category = MultiValueFilter(name='content_category__name') content_format = MultiValueFilter(name='content_format__name') release_id = MultiValueFilter(name='variant_arch__variant__release__release_id') variant_uid = MultiValueFilter(name='variant_arch__variant__variant_uid') repo_family = MultiValueFilter(name='repo_family__name') service = MultiValueFilter(name='service__name') shadow = filters.BooleanFilter() product_id = MultiIntFilter() class Meta: model = models.Repo fields = ('arch', 'content_category', 'content_format', 'name', 'release_id', 'repo_family', 'service', 'shadow', 'variant_uid', 'product_id') class RepoFamilyFilter(filters.FilterSet): name = filters.CharFilter(lookup_type="icontains") class Meta: model = models.RepoFamily fields = ('name',)
... import django_filters as filters from pdc.apps.common.filters import MultiValueFilter, MultiIntFilter from . import models ... repo_family = MultiValueFilter(name='repo_family__name') service = MultiValueFilter(name='service__name') shadow = filters.BooleanFilter() product_id = MultiIntFilter() class Meta: model = models.Repo ...
0ddaed24e0f011ca1bb777af49936f64684a7d4c
bin/scripts/contig_length_filter.py
bin/scripts/contig_length_filter.py
import sys from Bio import SeqIO from Bio.SeqRecord import SeqRecord if len(sys.argv) < 5: print("Usage: %s <length threshold> <contigs_file> <suffix> <output>" % sys.argv[0]) sys.exit(1) f_n = sys.argv[2] suffix = sys.argv[3] input_seq_iterator = SeqIO.parse(open(f_n, "r"), "fasta") output_handle = open(sys.argv[4], "w") SeqIO.write((SeqRecord(record.seq, (record.name + "_" + suffix).replace(".", "_"), "","") for record in input_seq_iterator \ if len(record.seq) > int(sys.argv[1])), output_handle, "fasta") output_handle.close()
import sys from Bio import SeqIO if len(sys.argv) < 4: print("Usage: %s <length threshold> <contigs_file> <output>" % sys.argv[0]) sys.exit(1) f_n = sys.argv[2] input_seq_iterator = SeqIO.parse(open(f_n, "r"), "fasta") filtered_iterator = (record for record in input_seq_iterator \ if len(record.seq) > int(sys.argv[1])) output_handle = open(sys.argv[3], "w") SeqIO.write(filtered_iterator, output_handle, "fasta") output_handle.close()
Revert "length filter script now adds provided suffix to contig names"
Revert "length filter script now adds provided suffix to contig names" This reverts commit 4d3985f667465eb5564de4fada8820e23607a58b.
Python
mit
tanaes/snakemake_assemble,tanaes/snakemake_assemble,tanaes/snakemake_assemble
python
## Code Before: import sys from Bio import SeqIO from Bio.SeqRecord import SeqRecord if len(sys.argv) < 5: print("Usage: %s <length threshold> <contigs_file> <suffix> <output>" % sys.argv[0]) sys.exit(1) f_n = sys.argv[2] suffix = sys.argv[3] input_seq_iterator = SeqIO.parse(open(f_n, "r"), "fasta") output_handle = open(sys.argv[4], "w") SeqIO.write((SeqRecord(record.seq, (record.name + "_" + suffix).replace(".", "_"), "","") for record in input_seq_iterator \ if len(record.seq) > int(sys.argv[1])), output_handle, "fasta") output_handle.close() ## Instruction: Revert "length filter script now adds provided suffix to contig names" This reverts commit 4d3985f667465eb5564de4fada8820e23607a58b. ## Code After: import sys from Bio import SeqIO if len(sys.argv) < 4: print("Usage: %s <length threshold> <contigs_file> <output>" % sys.argv[0]) sys.exit(1) f_n = sys.argv[2] input_seq_iterator = SeqIO.parse(open(f_n, "r"), "fasta") filtered_iterator = (record for record in input_seq_iterator \ if len(record.seq) > int(sys.argv[1])) output_handle = open(sys.argv[3], "w") SeqIO.write(filtered_iterator, output_handle, "fasta") output_handle.close()
// ... existing code ... import sys from Bio import SeqIO if len(sys.argv) < 4: print("Usage: %s <length threshold> <contigs_file> <output>" % sys.argv[0]) sys.exit(1) f_n = sys.argv[2] input_seq_iterator = SeqIO.parse(open(f_n, "r"), "fasta") filtered_iterator = (record for record in input_seq_iterator \ if len(record.seq) > int(sys.argv[1])) output_handle = open(sys.argv[3], "w") SeqIO.write(filtered_iterator, output_handle, "fasta") output_handle.close() // ... rest of the code ...
fa67de4900be765a5ea4194b1a786cd237934a33
displacy_service_tests/test_server.py
displacy_service_tests/test_server.py
import falcon.testing import json from displacy_service.server import APP class TestAPI(falcon.testing.TestCase): def __init__(self): self.api = APP def test_deps(): test_api = TestAPI() result = test_api.simulate_post(path='/dep', body='''{"text": "This is a test.", "model": "en", "collapse_punctuation": false, "collapse_phrases": false}''') result = json.loads(result.text) words = [w['text'] for w in result['words']] assert words == ["This", "is", "a", "test", "."] def test_ents(): test_api = TestAPI() result = test_api.simulate_post(path='/ent', body='''{"text": "What a great company Google is.", "model": "en"}''') ents = json.loads(result.text) assert ents == [ {"start": 21, "end": 27, "type": "ORG", "text": "Google"}] def test_sents(): test_api = TestAPI() sentences = test_api.simulate_post( path='/sent', body='''{"text": "This a test that should split into sentences! This is the second. Is this the third?", "model": "en"}''') assert sentences == ['This a test that should split into sentences!', 'This is the second.', 'Is this the third?']
import falcon.testing import json from displacy_service.server import APP class TestAPI(falcon.testing.TestCase): def __init__(self): self.api = APP def test_deps(): test_api = TestAPI() result = test_api.simulate_post( path='/dep', body='''{"text": "This is a test.", "model": "en", "collapse_punctuation": false, "collapse_phrases": false}''' ) result = json.loads(result.text) words = [w['text'] for w in result['words']] assert words == ["This", "is", "a", "test", "."] def test_ents(): test_api = TestAPI() result = test_api.simulate_post( path='/ent', body='''{"text": "What a great company Google is.", "model": "en"}''') ents = json.loads(result.text) assert ents == [ {"start": 21, "end": 27, "type": "ORG", "text": "Google"}] def test_sents(): test_api = TestAPI() sentences = test_api.simulate_post( path='/sent', body='''{"text": "This a test that should split into sentences! This is the second. Is this the third?", "model": "en"}''' ) assert sentences == ['This a test that should split into sentences!', 'This is the second.', 'Is this the third?']
Make test file PEP8 compliant.
Make test file PEP8 compliant.
Python
mit
jgontrum/spacy-api-docker,jgontrum/spacy-api-docker,jgontrum/spacy-api-docker,jgontrum/spacy-api-docker
python
## Code Before: import falcon.testing import json from displacy_service.server import APP class TestAPI(falcon.testing.TestCase): def __init__(self): self.api = APP def test_deps(): test_api = TestAPI() result = test_api.simulate_post(path='/dep', body='''{"text": "This is a test.", "model": "en", "collapse_punctuation": false, "collapse_phrases": false}''') result = json.loads(result.text) words = [w['text'] for w in result['words']] assert words == ["This", "is", "a", "test", "."] def test_ents(): test_api = TestAPI() result = test_api.simulate_post(path='/ent', body='''{"text": "What a great company Google is.", "model": "en"}''') ents = json.loads(result.text) assert ents == [ {"start": 21, "end": 27, "type": "ORG", "text": "Google"}] def test_sents(): test_api = TestAPI() sentences = test_api.simulate_post( path='/sent', body='''{"text": "This a test that should split into sentences! This is the second. Is this the third?", "model": "en"}''') assert sentences == ['This a test that should split into sentences!', 'This is the second.', 'Is this the third?'] ## Instruction: Make test file PEP8 compliant. ## Code After: import falcon.testing import json from displacy_service.server import APP class TestAPI(falcon.testing.TestCase): def __init__(self): self.api = APP def test_deps(): test_api = TestAPI() result = test_api.simulate_post( path='/dep', body='''{"text": "This is a test.", "model": "en", "collapse_punctuation": false, "collapse_phrases": false}''' ) result = json.loads(result.text) words = [w['text'] for w in result['words']] assert words == ["This", "is", "a", "test", "."] def test_ents(): test_api = TestAPI() result = test_api.simulate_post( path='/ent', body='''{"text": "What a great company Google is.", "model": "en"}''') ents = json.loads(result.text) assert ents == [ {"start": 21, "end": 27, "type": "ORG", "text": "Google"}] def test_sents(): test_api = TestAPI() sentences = test_api.simulate_post( path='/sent', body='''{"text": "This a test that should split into sentences! This is the second. Is this the third?", "model": "en"}''' ) assert sentences == ['This a test that should split into sentences!', 'This is the second.', 'Is this the third?']
... def test_deps(): test_api = TestAPI() result = test_api.simulate_post( path='/dep', body='''{"text": "This is a test.", "model": "en", "collapse_punctuation": false, "collapse_phrases": false}''' ) result = json.loads(result.text) words = [w['text'] for w in result['words']] assert words == ["This", "is", "a", "test", "."] ... def test_ents(): test_api = TestAPI() result = test_api.simulate_post( path='/ent', body='''{"text": "What a great company Google is.", "model": "en"}''') ents = json.loads(result.text) assert ents == [ ... def test_sents(): test_api = TestAPI() sentences = test_api.simulate_post( path='/sent', body='''{"text": "This a test that should split into sentences! This is the second. Is this the third?", "model": "en"}''' ) assert sentences == ['This a test that should split into sentences!', 'This is the second.', 'Is this the third?'] ...
5b7e92db448722fbf47027d1e8da156cb43eae54
src/main/java/com/threerings/gwt/util/Functions.java
src/main/java/com/threerings/gwt/util/Functions.java
// // $Id$ package com.threerings.gwt.util; import com.google.common.base.Function; /** * A collection of general purpose functions. */ public class Functions { /** Implements boolean not. */ public static Function<Boolean, Boolean> NOT = new Function<Boolean, Boolean>() { public Boolean apply (Boolean value) { return !value; } }; }
// // $Id$ package com.threerings.gwt.util; import java.util.Map; import com.google.common.base.Function; /** * A collection of general purpose functions. */ public class Functions { /** Implements boolean not. */ public static Function<Boolean, Boolean> NOT = new Function<Boolean, Boolean>() { public Boolean apply (Boolean value) { return !value; } }; /** Views the supplied map as a function from keys to values. */ public static <K, V> Function<K, V> fromMap (final Map<K, V> map) { return new Function<K, V>() { public V apply (K key) { return map.get(key); } }; } }
Allow a map to be viewed as a (K => V).
Allow a map to be viewed as a (K => V).
Java
lgpl-2.1
threerings/gwt-utils
java
## Code Before: // // $Id$ package com.threerings.gwt.util; import com.google.common.base.Function; /** * A collection of general purpose functions. */ public class Functions { /** Implements boolean not. */ public static Function<Boolean, Boolean> NOT = new Function<Boolean, Boolean>() { public Boolean apply (Boolean value) { return !value; } }; } ## Instruction: Allow a map to be viewed as a (K => V). ## Code After: // // $Id$ package com.threerings.gwt.util; import java.util.Map; import com.google.common.base.Function; /** * A collection of general purpose functions. */ public class Functions { /** Implements boolean not. */ public static Function<Boolean, Boolean> NOT = new Function<Boolean, Boolean>() { public Boolean apply (Boolean value) { return !value; } }; /** Views the supplied map as a function from keys to values. */ public static <K, V> Function<K, V> fromMap (final Map<K, V> map) { return new Function<K, V>() { public V apply (K key) { return map.get(key); } }; } }
... // $Id$ package com.threerings.gwt.util; import java.util.Map; import com.google.common.base.Function; ... return !value; } }; /** Views the supplied map as a function from keys to values. */ public static <K, V> Function<K, V> fromMap (final Map<K, V> map) { return new Function<K, V>() { public V apply (K key) { return map.get(key); } }; } } ...
6fb5110d4fb1c3de7d065267f9d8f7302c303ec1
allauth/socialaccount/providers/twitch/provider.py
allauth/socialaccount/providers/twitch/provider.py
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return dict(username=data.get('name'), name=data.get('display_name'), email=data.get('email')) provider_classes = [TwitchProvider]
from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return { "username": data.get("name"), "name": data.get("display_name"), "email": data.get("email"), } def get_default_scope(self): return ["user_read"] provider_classes = [TwitchProvider]
Add user_read as default scope
twitch: Add user_read as default scope
Python
mit
bittner/django-allauth,pennersr/django-allauth,pztrick/django-allauth,rsalmaso/django-allauth,rsalmaso/django-allauth,bittner/django-allauth,pztrick/django-allauth,lukeburden/django-allauth,AltSchool/django-allauth,pennersr/django-allauth,AltSchool/django-allauth,pennersr/django-allauth,AltSchool/django-allauth,rsalmaso/django-allauth,lukeburden/django-allauth,bittner/django-allauth,pztrick/django-allauth,lukeburden/django-allauth
python
## Code Before: from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return dict(username=data.get('name'), name=data.get('display_name'), email=data.get('email')) provider_classes = [TwitchProvider] ## Instruction: twitch: Add user_read as default scope ## Code After: from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class TwitchAccount(ProviderAccount): def get_profile_url(self): return 'http://twitch.tv/' + self.account.extra_data.get('name') def get_avatar_url(self): return self.account.extra_data.get('logo') def to_str(self): dflt = super(TwitchAccount, self).to_str() return self.account.extra_data.get('name', dflt) class TwitchProvider(OAuth2Provider): id = 'twitch' name = 'Twitch' account_class = TwitchAccount def extract_uid(self, data): return str(data['_id']) def extract_common_fields(self, data): return { "username": data.get("name"), "name": data.get("display_name"), "email": data.get("email"), } def get_default_scope(self): return ["user_read"] provider_classes = [TwitchProvider]
... return str(data['_id']) def extract_common_fields(self, data): return { "username": data.get("name"), "name": data.get("display_name"), "email": data.get("email"), } def get_default_scope(self): return ["user_read"] provider_classes = [TwitchProvider] ...
38848a976789e35271cc07cc5dae021f6521846f
src/main/java/org/icij/extract/core/Spewer.java
src/main/java/org/icij/extract/core/Spewer.java
package org.icij.extract.core; import java.io.IOException; import java.nio.file.Path; import java.nio.file.FileSystems; import java.nio.charset.Charset; import java.util.logging.Logger; import org.apache.tika.parser.ParsingReader; import org.apache.tika.exception.TikaException; /** * Extract * * @author Matthew Caruana Galizia <[email protected]> * @version 1.0.0-beta * @since 1.0.0-beta */ public abstract class Spewer { protected final Logger logger; private Path outputBase = null; public Spewer(Logger logger) { this.logger = logger; } public abstract void write(Path file, ParsingReader reader, Charset outputEncoding) throws IOException, TikaException, SpewerException; public void setOutputBase(Path outputBase) { this.outputBase = outputBase; } public void setOutputBase(String outputBase) { setOutputBase(FileSystems.getDefault().getPath(outputBase)); } public Path filterOutputPath(Path file) { if (file.startsWith(outputBase)) { return file.subpath(outputBase.getNameCount(), file.getNameCount()); } return file; } public void finish() throws IOException { logger.info("Spewer finishing pending jobs."); } }
package org.icij.extract.core; import java.io.IOException; import java.nio.file.Path; import java.nio.file.FileSystems; import java.nio.charset.Charset; import java.util.logging.Logger; import org.apache.tika.parser.ParsingReader; import org.apache.tika.exception.TikaException; /** * Extract * * @author Matthew Caruana Galizia <[email protected]> * @version 1.0.0-beta * @since 1.0.0-beta */ public abstract class Spewer { protected final Logger logger; private Path outputBase = null; public Spewer(Logger logger) { this.logger = logger; } public abstract void write(Path file, ParsingReader reader, Charset outputEncoding) throws IOException, TikaException, SpewerException; public void setOutputBase(Path outputBase) { this.outputBase = outputBase; } public void setOutputBase(String outputBase) { setOutputBase(FileSystems.getDefault().getPath(outputBase)); } public Path filterOutputPath(Path file) { if (null != outputBase && file.startsWith(outputBase)) { return file.subpath(outputBase.getNameCount(), file.getNameCount()); } return file; } public void finish() throws IOException { logger.info("Spewer finishing pending jobs."); } }
Fix NullPointerException when output base is null
Fix NullPointerException when output base is null
Java
mit
ICIJ/extract,ICIJ/extract
java
## Code Before: package org.icij.extract.core; import java.io.IOException; import java.nio.file.Path; import java.nio.file.FileSystems; import java.nio.charset.Charset; import java.util.logging.Logger; import org.apache.tika.parser.ParsingReader; import org.apache.tika.exception.TikaException; /** * Extract * * @author Matthew Caruana Galizia <[email protected]> * @version 1.0.0-beta * @since 1.0.0-beta */ public abstract class Spewer { protected final Logger logger; private Path outputBase = null; public Spewer(Logger logger) { this.logger = logger; } public abstract void write(Path file, ParsingReader reader, Charset outputEncoding) throws IOException, TikaException, SpewerException; public void setOutputBase(Path outputBase) { this.outputBase = outputBase; } public void setOutputBase(String outputBase) { setOutputBase(FileSystems.getDefault().getPath(outputBase)); } public Path filterOutputPath(Path file) { if (file.startsWith(outputBase)) { return file.subpath(outputBase.getNameCount(), file.getNameCount()); } return file; } public void finish() throws IOException { logger.info("Spewer finishing pending jobs."); } } ## Instruction: Fix NullPointerException when output base is null ## Code After: package org.icij.extract.core; import java.io.IOException; import java.nio.file.Path; import java.nio.file.FileSystems; import java.nio.charset.Charset; import java.util.logging.Logger; import org.apache.tika.parser.ParsingReader; import org.apache.tika.exception.TikaException; /** * Extract * * @author Matthew Caruana Galizia <[email protected]> * @version 1.0.0-beta * @since 1.0.0-beta */ public abstract class Spewer { protected final Logger logger; private Path outputBase = null; public Spewer(Logger logger) { this.logger = logger; } public abstract void write(Path file, ParsingReader reader, Charset outputEncoding) throws IOException, TikaException, SpewerException; public void setOutputBase(Path outputBase) { this.outputBase = outputBase; } public void setOutputBase(String outputBase) { setOutputBase(FileSystems.getDefault().getPath(outputBase)); } public Path filterOutputPath(Path file) { if (null != outputBase && file.startsWith(outputBase)) { return file.subpath(outputBase.getNameCount(), file.getNameCount()); } return file; } public void finish() throws IOException { logger.info("Spewer finishing pending jobs."); } }
# ... existing code ... } public Path filterOutputPath(Path file) { if (null != outputBase && file.startsWith(outputBase)) { return file.subpath(outputBase.getNameCount(), file.getNameCount()); } # ... rest of the code ...
3c0d465dde4a93fe60b8b2ce897cb4c5745450ad
pysarus.py
pysarus.py
import urllib.request import json #where to save reteived defintions #if None than no files are saved savepath = "." #Your API key for Big Huge Thesarus APIkey = "" def thesarus(word): if(savepath): try: return json.load(savepath+word) except: print("No file found in "+savepath+" for "+word) web = urllib.request.urlopen("http://words.bighugelabs.com/api/2/"+word+"/json") jsonobj = json.loads(web.read()) if(savepath): json.dump(jsonobj,savepath+word) return jsonobj
import urllib.request import json #where to save reteived defintions #if None than no files are saved savepath = "." #Your API key for Big Huge Thesarus APIkey = "" def thesarus(word): if(savepath): try: return json.load(savepath+word) except: print("No file found in "+savepath+" for "+word) web = urllib.request.urlopen("http://words.bighugelabs.com/api/2/"+APIkey+"/"+word+"/json") jsonobj = json.loads(web.read()) if(savepath): json.dump(jsonobj,savepath+word) return jsonobj
Use API key in URL
Use API key in URL
Python
mit
Tookmund/Pysarus
python
## Code Before: import urllib.request import json #where to save reteived defintions #if None than no files are saved savepath = "." #Your API key for Big Huge Thesarus APIkey = "" def thesarus(word): if(savepath): try: return json.load(savepath+word) except: print("No file found in "+savepath+" for "+word) web = urllib.request.urlopen("http://words.bighugelabs.com/api/2/"+word+"/json") jsonobj = json.loads(web.read()) if(savepath): json.dump(jsonobj,savepath+word) return jsonobj ## Instruction: Use API key in URL ## Code After: import urllib.request import json #where to save reteived defintions #if None than no files are saved savepath = "." #Your API key for Big Huge Thesarus APIkey = "" def thesarus(word): if(savepath): try: return json.load(savepath+word) except: print("No file found in "+savepath+" for "+word) web = urllib.request.urlopen("http://words.bighugelabs.com/api/2/"+APIkey+"/"+word+"/json") jsonobj = json.loads(web.read()) if(savepath): json.dump(jsonobj,savepath+word) return jsonobj
... return json.load(savepath+word) except: print("No file found in "+savepath+" for "+word) web = urllib.request.urlopen("http://words.bighugelabs.com/api/2/"+APIkey+"/"+word+"/json") jsonobj = json.loads(web.read()) if(savepath): json.dump(jsonobj,savepath+word) ...
36e35a475e3fd76331a073ee467afe938c89bd08
CarFactory/src/ru/nsu/ccfit/bogush/view/LabeledValue.java
CarFactory/src/ru/nsu/ccfit/bogush/view/LabeledValue.java
package ru.nsu.ccfit.bogush.view; import javax.swing.*; public class LabeledValue extends JPanel { private JLabel valueLabel; private JLabel label; private JPanel panel; public LabeledValue(String labelText) { label.setText(labelText); label.addPropertyChangeListener(evt -> { if ("label".equals(evt.getPropertyName())) { label.setText((String) evt.getNewValue()); } }); } public synchronized void setEnabled(boolean enabled) { valueLabel.setEnabled(enabled); } public synchronized void setValue(int value) { setText(String.valueOf(value)); } public synchronized void setText(String text) { valueLabel.setText(text); } public String getText() { return valueLabel.getText(); } }
package ru.nsu.ccfit.bogush.view; import javax.swing.*; public class LabeledValue extends JPanel { private JLabel valueLabel; private JLabel label; private JPanel panel; private int value; public LabeledValue(String labelText) { label.setText(labelText); } public void setEnabled(boolean enabled) { valueLabel.setEnabled(enabled); } public synchronized void setValue(int value) { this.value = value; valueLabel.setText(String.valueOf(value)); } public synchronized int getValue() { return value; } }
Make getter and setter of the value field synchronized
Make getter and setter of the value field synchronized
Java
mit
RoyPy/15201-bogush
java
## Code Before: package ru.nsu.ccfit.bogush.view; import javax.swing.*; public class LabeledValue extends JPanel { private JLabel valueLabel; private JLabel label; private JPanel panel; public LabeledValue(String labelText) { label.setText(labelText); label.addPropertyChangeListener(evt -> { if ("label".equals(evt.getPropertyName())) { label.setText((String) evt.getNewValue()); } }); } public synchronized void setEnabled(boolean enabled) { valueLabel.setEnabled(enabled); } public synchronized void setValue(int value) { setText(String.valueOf(value)); } public synchronized void setText(String text) { valueLabel.setText(text); } public String getText() { return valueLabel.getText(); } } ## Instruction: Make getter and setter of the value field synchronized ## Code After: package ru.nsu.ccfit.bogush.view; import javax.swing.*; public class LabeledValue extends JPanel { private JLabel valueLabel; private JLabel label; private JPanel panel; private int value; public LabeledValue(String labelText) { label.setText(labelText); } public void setEnabled(boolean enabled) { valueLabel.setEnabled(enabled); } public synchronized void setValue(int value) { this.value = value; valueLabel.setText(String.valueOf(value)); } public synchronized int getValue() { return value; } }
... private JLabel label; private JPanel panel; private int value; public LabeledValue(String labelText) { label.setText(labelText); } public void setEnabled(boolean enabled) { valueLabel.setEnabled(enabled); } public synchronized void setValue(int value) { this.value = value; valueLabel.setText(String.valueOf(value)); } public synchronized int getValue() { return value; } } ...
7d4cae64e8a5c76c49f5926dc9791167b09c1750
spatial-test/src/main/java/org/apache/lucene/spatial/test/strategy/BaseGeohashStrategyTestCase.java
spatial-test/src/main/java/org/apache/lucene/spatial/test/strategy/BaseGeohashStrategyTestCase.java
package org.apache.lucene.spatial.test.strategy; import org.apache.lucene.spatial.base.context.SpatialContext; import org.apache.lucene.spatial.base.prefix.GeohashSpatialPrefixGrid; import org.apache.lucene.spatial.strategy.SimpleSpatialFieldInfo; import org.apache.lucene.spatial.strategy.prefix.DynamicPrefixStrategy; import org.apache.lucene.spatial.test.SpatialMatchConcern; import org.apache.lucene.spatial.test.StrategyTestCase; import org.junit.Test; import java.io.IOException; public abstract class BaseGeohashStrategyTestCase extends StrategyTestCase<SimpleSpatialFieldInfo> { protected abstract SpatialContext getSpatialContext(); @Override public void setUp() throws Exception { super.setUp(); int maxLength = GeohashSpatialPrefixGrid.getMaxLevelsPossible(); // SimpleIO this.shapeIO = getSpatialContext(); this.strategy = new DynamicPrefixStrategy(new GeohashSpatialPrefixGrid( shapeIO, maxLength )); this.fieldInfo = new SimpleSpatialFieldInfo( "geohash" ); } @Test public void testGeohashStrategy() throws IOException { getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS); executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox); } }
package org.apache.lucene.spatial.test.strategy; import org.apache.lucene.spatial.base.context.SpatialContext; import org.apache.lucene.spatial.base.prefix.GeohashSpatialPrefixGrid; import org.apache.lucene.spatial.strategy.SimpleSpatialFieldInfo; import org.apache.lucene.spatial.strategy.prefix.DynamicPrefixStrategy; import org.apache.lucene.spatial.test.SpatialMatchConcern; import org.apache.lucene.spatial.test.StrategyTestCase; import org.junit.Test; import java.io.IOException; public abstract class BaseGeohashStrategyTestCase extends StrategyTestCase<SimpleSpatialFieldInfo> { private int maxLength; protected abstract SpatialContext getSpatialContext(); @Override public void setUp() throws Exception { super.setUp(); maxLength = GeohashSpatialPrefixGrid.getMaxLevelsPossible(); // SimpleIO this.shapeIO = getSpatialContext(); this.strategy = new DynamicPrefixStrategy(new GeohashSpatialPrefixGrid( shapeIO, maxLength )); this.fieldInfo = new SimpleSpatialFieldInfo( "geohash" ); } @Test public void testGeohashStrategy() throws IOException { getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS); //execute queries for each prefix grid scan level for(int i = 0; i <= maxLength; i++) { ((DynamicPrefixStrategy)strategy).setPrefixGridScanLevel(i); executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox); } } }
Test DynamicPrefixStrategy for each grid scan level (an internal threshold) to tease out possible bugs.
Test DynamicPrefixStrategy for each grid scan level (an internal threshold) to tease out possible bugs.
Java
apache-2.0
jdeolive/spatial4j,ryantxu/spatial-solr-sandbox,varsis/spatial4j,jdeolive/spatial4j
java
## Code Before: package org.apache.lucene.spatial.test.strategy; import org.apache.lucene.spatial.base.context.SpatialContext; import org.apache.lucene.spatial.base.prefix.GeohashSpatialPrefixGrid; import org.apache.lucene.spatial.strategy.SimpleSpatialFieldInfo; import org.apache.lucene.spatial.strategy.prefix.DynamicPrefixStrategy; import org.apache.lucene.spatial.test.SpatialMatchConcern; import org.apache.lucene.spatial.test.StrategyTestCase; import org.junit.Test; import java.io.IOException; public abstract class BaseGeohashStrategyTestCase extends StrategyTestCase<SimpleSpatialFieldInfo> { protected abstract SpatialContext getSpatialContext(); @Override public void setUp() throws Exception { super.setUp(); int maxLength = GeohashSpatialPrefixGrid.getMaxLevelsPossible(); // SimpleIO this.shapeIO = getSpatialContext(); this.strategy = new DynamicPrefixStrategy(new GeohashSpatialPrefixGrid( shapeIO, maxLength )); this.fieldInfo = new SimpleSpatialFieldInfo( "geohash" ); } @Test public void testGeohashStrategy() throws IOException { getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS); executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox); } } ## Instruction: Test DynamicPrefixStrategy for each grid scan level (an internal threshold) to tease out possible bugs. ## Code After: package org.apache.lucene.spatial.test.strategy; import org.apache.lucene.spatial.base.context.SpatialContext; import org.apache.lucene.spatial.base.prefix.GeohashSpatialPrefixGrid; import org.apache.lucene.spatial.strategy.SimpleSpatialFieldInfo; import org.apache.lucene.spatial.strategy.prefix.DynamicPrefixStrategy; import org.apache.lucene.spatial.test.SpatialMatchConcern; import org.apache.lucene.spatial.test.StrategyTestCase; import org.junit.Test; import java.io.IOException; public abstract class BaseGeohashStrategyTestCase extends StrategyTestCase<SimpleSpatialFieldInfo> { private int maxLength; protected abstract SpatialContext getSpatialContext(); @Override public void setUp() throws Exception { super.setUp(); maxLength = GeohashSpatialPrefixGrid.getMaxLevelsPossible(); // SimpleIO this.shapeIO = getSpatialContext(); this.strategy = new DynamicPrefixStrategy(new GeohashSpatialPrefixGrid( shapeIO, maxLength )); this.fieldInfo = new SimpleSpatialFieldInfo( "geohash" ); } @Test public void testGeohashStrategy() throws IOException { getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS); //execute queries for each prefix grid scan level for(int i = 0; i <= maxLength; i++) { ((DynamicPrefixStrategy)strategy).setPrefixGridScanLevel(i); executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox); } } }
# ... existing code ... public abstract class BaseGeohashStrategyTestCase extends StrategyTestCase<SimpleSpatialFieldInfo> { private int maxLength; protected abstract SpatialContext getSpatialContext(); @Override public void setUp() throws Exception { super.setUp(); maxLength = GeohashSpatialPrefixGrid.getMaxLevelsPossible(); // SimpleIO this.shapeIO = getSpatialContext(); this.strategy = new DynamicPrefixStrategy(new GeohashSpatialPrefixGrid( # ... modified code ... @Test public void testGeohashStrategy() throws IOException { getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS); //execute queries for each prefix grid scan level for(int i = 0; i <= maxLength; i++) { ((DynamicPrefixStrategy)strategy).setPrefixGridScanLevel(i); executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox); } } } # ... rest of the code ...
c9102ef894816d383177e49dbc6b801ca34d609b
binary_search_tree/TestBst.java
binary_search_tree/TestBst.java
package binary_search_tree; import binary_search_tree.Bst; // My implementation of Binary Search Tree in package binary_search_tree /* Class to test class Bst. (Binary Search Tree) */ class TestBst{ // Tests Insertion public static void testInsertion(){ // Create a bst object Bst bst = new Bst(); // Create array of integers to insert int[] values = {10, 7, 9, 8, 2, 15, 13, 17}; // Insert values into bst for(int v: values){ bst.insert(v); } // Print In Order traversal System.out.print("Inorder Traversal:\t "); bst.inOrder(); System.out.println(); System.out.println("Should be:\t\t 2 7 8 9 10 13 15 17"); } public static void main(String args[]){ // Test Insertion testInsertion(); } }
package binary_search_tree; import java.util.NoSuchElementException; import binary_search_tree.Bst; // My implementation of Binary Search Tree in package binary_search_tree /* Class to test class Bst. (Binary Search Tree) */ class TestBst{ // Tests Insertion public static void testInsertion(){ // Create a bst object Bst bst = new Bst(); // Test inorder when tree is empty. Should throw exception try{ bst.inOrder(); } catch(NoSuchElementException e){ System.out.println(e); } // Create array of integers to insert int[] values = {10, 7, 9, 8, 2, 15, 13, 17}; // Insert values into bst for(int v: values){ bst.insert(v); } // Print In Order traversal System.out.print("Inorder Traversal:\t "); bst.inOrder(); System.out.println(); System.out.println("Should be:\t\t 2 7 8 9 10 13 15 17"); } public static void main(String args[]){ // Test Insertion testInsertion(); } }
Add test case to check inOrder when tree is empty. Throws NoSuchElement exception
Add test case to check inOrder when tree is empty. Throws NoSuchElement exception
Java
mit
rohitkhilnani/Java-holic
java
## Code Before: package binary_search_tree; import binary_search_tree.Bst; // My implementation of Binary Search Tree in package binary_search_tree /* Class to test class Bst. (Binary Search Tree) */ class TestBst{ // Tests Insertion public static void testInsertion(){ // Create a bst object Bst bst = new Bst(); // Create array of integers to insert int[] values = {10, 7, 9, 8, 2, 15, 13, 17}; // Insert values into bst for(int v: values){ bst.insert(v); } // Print In Order traversal System.out.print("Inorder Traversal:\t "); bst.inOrder(); System.out.println(); System.out.println("Should be:\t\t 2 7 8 9 10 13 15 17"); } public static void main(String args[]){ // Test Insertion testInsertion(); } } ## Instruction: Add test case to check inOrder when tree is empty. Throws NoSuchElement exception ## Code After: package binary_search_tree; import java.util.NoSuchElementException; import binary_search_tree.Bst; // My implementation of Binary Search Tree in package binary_search_tree /* Class to test class Bst. (Binary Search Tree) */ class TestBst{ // Tests Insertion public static void testInsertion(){ // Create a bst object Bst bst = new Bst(); // Test inorder when tree is empty. Should throw exception try{ bst.inOrder(); } catch(NoSuchElementException e){ System.out.println(e); } // Create array of integers to insert int[] values = {10, 7, 9, 8, 2, 15, 13, 17}; // Insert values into bst for(int v: values){ bst.insert(v); } // Print In Order traversal System.out.print("Inorder Traversal:\t "); bst.inOrder(); System.out.println(); System.out.println("Should be:\t\t 2 7 8 9 10 13 15 17"); } public static void main(String args[]){ // Test Insertion testInsertion(); } }
# ... existing code ... package binary_search_tree; import java.util.NoSuchElementException; import binary_search_tree.Bst; // My implementation of Binary Search Tree in package binary_search_tree /* # ... modified code ... // Create a bst object Bst bst = new Bst(); // Test inorder when tree is empty. Should throw exception try{ bst.inOrder(); } catch(NoSuchElementException e){ System.out.println(e); } // Create array of integers to insert int[] values = {10, 7, 9, 8, 2, 15, 13, 17}; # ... rest of the code ...
979c56f882178ce49194850bd9e78c9dea4692dd
chardet/__init__.py
chardet/__init__.py
from .compat import PY2, PY3 from .universaldetector import UniversalDetector from .version import __version__, VERSION def detect(byte_str): """ Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` """ if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expected object of type bytes or bytearray, got: ' '{0}'.format(type(byte_str))) else: byte_str = bytearray(byte_str) detector = UniversalDetector() detector.feed(byte_str) detector.close() return detector.result
from .compat import PY2, PY3 from .universaldetector import UniversalDetector from .version import __version__, VERSION def detect(byte_str): """ Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` """ if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expected object of type bytes or bytearray, got: ' '{0}'.format(type(byte_str))) else: byte_str = bytearray(byte_str) detector = UniversalDetector() detector.feed(byte_str) return detector.close()
Remove unnecessary line from detect
Remove unnecessary line from detect
Python
lgpl-2.1
ddboline/chardet,chardet/chardet,chardet/chardet,ddboline/chardet
python
## Code Before: from .compat import PY2, PY3 from .universaldetector import UniversalDetector from .version import __version__, VERSION def detect(byte_str): """ Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` """ if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expected object of type bytes or bytearray, got: ' '{0}'.format(type(byte_str))) else: byte_str = bytearray(byte_str) detector = UniversalDetector() detector.feed(byte_str) detector.close() return detector.result ## Instruction: Remove unnecessary line from detect ## Code After: from .compat import PY2, PY3 from .universaldetector import UniversalDetector from .version import __version__, VERSION def detect(byte_str): """ Detect the encoding of the given byte string. :param byte_str: The byte sequence to examine. :type byte_str: ``bytes`` or ``bytearray`` """ if not isinstance(byte_str, bytearray): if not isinstance(byte_str, bytes): raise TypeError('Expected object of type bytes or bytearray, got: ' '{0}'.format(type(byte_str))) else: byte_str = bytearray(byte_str) detector = UniversalDetector() detector.feed(byte_str) return detector.close()
// ... existing code ... byte_str = bytearray(byte_str) detector = UniversalDetector() detector.feed(byte_str) return detector.close() // ... rest of the code ...
4467ffe669eec09bab16f4e5a3256ed333c5d3d5
rcamp/lib/ldap_utils.py
rcamp/lib/ldap_utils.py
from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org
from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server, bytes_mode=False) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org
Set bytes_mode=False for future compatability with Python3
Set bytes_mode=False for future compatability with Python3
Python
mit
ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP
python
## Code Before: from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org ## Instruction: Set bytes_mode=False for future compatability with Python3 ## Code After: from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server, bytes_mode=False) # Authenticate try: conn.simple_bind_s(dn, pwd) return True except ldap.INVALID_CREDENTIALS: return False def get_suffixed_username(username,organization): try: suffix = settings.ORGANIZATION_INFO[organization]['suffix'] except KeyError: suffix = None suffixed_username = username if suffix: suffixed_username = '{0}@{1}'.format(username,suffix) return suffixed_username def get_ldap_username_and_org(suffixed_username): username = suffixed_username org = 'ucb' if '@' in suffixed_username: username, suffix = suffixed_username.rsplit('@',1) for k,v in settings.ORGANIZATION_INFO.iteritems(): if v['suffix'] == suffix: org = k break return username, org
// ... existing code ... ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.initialize(server, bytes_mode=False) # Authenticate try: conn.simple_bind_s(dn, pwd) // ... rest of the code ...
b18aa2f4400deab98cc0e27c798ee6d7893232cd
utils/text.py
utils/text.py
def restrict_len(content): if len(content) > 320: content = content[:310].strip() + '...' return content def detect_language(config, langs, word): from yandex_translate import YandexTranslate translator = YandexTranslate(config['yandex_translate_key']) russian = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя' if word[0] in russian: lang = 'ru' else: lang = translator.detect(word) if lang not in langs: lang = 'en' return lang
def restrict_len(content): if len(content) > 320: content = content[:310].strip() + '...' return content def detect_language(config, langs, word): from yandex_translate import YandexTranslate, YandexTranslateException translator = YandexTranslate(config['yandex_translate_key']) russian = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя' if word[0] in russian: lang = 'ru' else: try: lang = translator.detect(word) except YandexTranslateException: lang = 'en' if lang not in langs: lang = 'en' return lang
Add unknown language error catching
Add unknown language error catching
Python
mit
Elishanto/HarryBotter
python
## Code Before: def restrict_len(content): if len(content) > 320: content = content[:310].strip() + '...' return content def detect_language(config, langs, word): from yandex_translate import YandexTranslate translator = YandexTranslate(config['yandex_translate_key']) russian = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя' if word[0] in russian: lang = 'ru' else: lang = translator.detect(word) if lang not in langs: lang = 'en' return lang ## Instruction: Add unknown language error catching ## Code After: def restrict_len(content): if len(content) > 320: content = content[:310].strip() + '...' return content def detect_language(config, langs, word): from yandex_translate import YandexTranslate, YandexTranslateException translator = YandexTranslate(config['yandex_translate_key']) russian = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя' if word[0] in russian: lang = 'ru' else: try: lang = translator.detect(word) except YandexTranslateException: lang = 'en' if lang not in langs: lang = 'en' return lang
# ... existing code ... def detect_language(config, langs, word): from yandex_translate import YandexTranslate, YandexTranslateException translator = YandexTranslate(config['yandex_translate_key']) russian = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя' # ... modified code ... if word[0] in russian: lang = 'ru' else: try: lang = translator.detect(word) except YandexTranslateException: lang = 'en' if lang not in langs: lang = 'en' return lang # ... rest of the code ...
f22beb7995fb20c477d837c0400b77480e5f1a13
yunity/users/tests/test_model.py
yunity/users/tests/test_model.py
from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.exampleuser = { 'display_name': 'bla', 'email': '[email protected]', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long)
from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase from yunity.users.factories import UserFactory class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = UserFactory() cls.exampleuser = { 'display_name': 'bla', 'email': '[email protected]', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) def test_user_representation(self): r = repr(self.user) self.assertTrue(self.user.display_name in r)
Add test for model representation
Add test for model representation
Python
agpl-3.0
yunity/foodsaving-backend,yunity/yunity-core,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend
python
## Code Before: from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.exampleuser = { 'display_name': 'bla', 'email': '[email protected]', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) ## Instruction: Add test for model representation ## Code After: from django.contrib.auth import get_user_model from django.db import DataError from django.db import IntegrityError from django.test import TestCase from yunity.users.factories import UserFactory class TestUserModel(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = UserFactory() cls.exampleuser = { 'display_name': 'bla', 'email': '[email protected]', 'password': 'notsafe' } def test_create_fails_if_email_is_not_unique(self): get_user_model().objects.create_user(**self.exampleuser) with self.assertRaises(IntegrityError): get_user_model().objects.create_user(**self.exampleuser) def test_create_fails_if_name_too_long(self): with self.assertRaises(DataError): too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) def test_user_representation(self): r = repr(self.user) self.assertTrue(self.user.display_name in r)
# ... existing code ... from django.db import DataError from django.db import IntegrityError from django.test import TestCase from yunity.users.factories import UserFactory class TestUserModel(TestCase): # ... modified code ... @classmethod def setUpClass(cls): super().setUpClass() cls.user = UserFactory() cls.exampleuser = { 'display_name': 'bla', 'email': '[email protected]', ... too_long = self.exampleuser too_long['display_name'] = 'a' * 81 get_user_model().objects.create_user(**too_long) def test_user_representation(self): r = repr(self.user) self.assertTrue(self.user.display_name in r) # ... rest of the code ...
0daa2132c071cb667aca5dbc416872a278e91a2b
pycoin/coins/groestlcoin/hash.py
pycoin/coins/groestlcoin/hash.py
import hashlib import groestlcoin_hash from pycoin.encoding.hexbytes import bytes_as_revhex def sha256(data): return bytes_as_revhex(hashlib.sha256(data).digest()) def groestlHash(data): """Groestl-512 compound hash.""" return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
import hashlib from pycoin.encoding.hexbytes import bytes_as_revhex def sha256(data): return bytes_as_revhex(hashlib.sha256(data).digest()) def groestlHash(data): """Groestl-512 compound hash.""" try: import groestlcoin_hash except ImportError: t = 'Groestlcoin requires the groestlcoin_hash package ("pip install groestlcoin_hash").' print(t) raise ImportError(t) return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
Raise ImportError when GRS is used without dependency
Raise ImportError when GRS is used without dependency
Python
mit
richardkiss/pycoin,richardkiss/pycoin
python
## Code Before: import hashlib import groestlcoin_hash from pycoin.encoding.hexbytes import bytes_as_revhex def sha256(data): return bytes_as_revhex(hashlib.sha256(data).digest()) def groestlHash(data): """Groestl-512 compound hash.""" return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data))) ## Instruction: Raise ImportError when GRS is used without dependency ## Code After: import hashlib from pycoin.encoding.hexbytes import bytes_as_revhex def sha256(data): return bytes_as_revhex(hashlib.sha256(data).digest()) def groestlHash(data): """Groestl-512 compound hash.""" try: import groestlcoin_hash except ImportError: t = 'Groestlcoin requires the groestlcoin_hash package ("pip install groestlcoin_hash").' print(t) raise ImportError(t) return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
# ... existing code ... import hashlib from pycoin.encoding.hexbytes import bytes_as_revhex # ... modified code ... def groestlHash(data): """Groestl-512 compound hash.""" try: import groestlcoin_hash except ImportError: t = 'Groestlcoin requires the groestlcoin_hash package ("pip install groestlcoin_hash").' print(t) raise ImportError(t) return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data))) # ... rest of the code ...
adf747998641b1aeb75feada25470aa2a072bd37
examples/test-mh/policies/participant_3.py
examples/test-mh/policies/participant_3.py
{ "inbound": [ { "cookie": 1, "match": { "tcp_dst": 4321 }, "action": { "fwd": 0 } }, { "cookie": 2, "match": { "tcp_dst": 4322 }, "action": { "fwd": 1 } }, { "cookie": 3, "match": { "tcp_dst": 4323 }, "action": { "drop": 0 } } ] }
{ "inbound": [ { "cookie": 1, "match": { "tcp_dst": 4321 }, "action": { "fwd": 0 } }, { "cookie": 2, "match": { "tcp_dst": 4322 }, "action": { "fwd": 1 } }, { "cookie": 3, "match": { "eth_src": '08:00:27:89:3b:9f' }, "action": { "drop": 0 } } ] }
Add inbound drop policy for participant 3 based on eth_src of participant 1
Add inbound drop policy for participant 3 based on eth_src of participant 1
Python
apache-2.0
h2020-endeavour/endeavour,h2020-endeavour/endeavour
python
## Code Before: { "inbound": [ { "cookie": 1, "match": { "tcp_dst": 4321 }, "action": { "fwd": 0 } }, { "cookie": 2, "match": { "tcp_dst": 4322 }, "action": { "fwd": 1 } }, { "cookie": 3, "match": { "tcp_dst": 4323 }, "action": { "drop": 0 } } ] } ## Instruction: Add inbound drop policy for participant 3 based on eth_src of participant 1 ## Code After: { "inbound": [ { "cookie": 1, "match": { "tcp_dst": 4321 }, "action": { "fwd": 0 } }, { "cookie": 2, "match": { "tcp_dst": 4322 }, "action": { "fwd": 1 } }, { "cookie": 3, "match": { "eth_src": '08:00:27:89:3b:9f' }, "action": { "drop": 0 } } ] }
// ... existing code ... "cookie": 3, "match": { "eth_src": '08:00:27:89:3b:9f' }, "action": { // ... rest of the code ...
1843e34bba0343cd3600f3c8934ae29b4b365554
chstrings/chstrings_test.py
chstrings/chstrings_test.py
import chstrings import config import unittest class CHStringsTest(unittest.TestCase): @classmethod def add_smoke_test(cls, cfg): def test(self): # We just want to see if this will blow up chstrings.get_localized_strings(cfg, cfg.lang_code) name = 'test_' + cfg.lang_code + '_smoke_test' setattr(cls, name, test) if __name__ == '__main__': for lc in config.LANG_CODES_TO_LANG_NAMES: cfg = config.get_localized_config(lc) CHStringsTest.add_smoke_test(cfg) unittest.main()
import chstrings import config import unittest class CHStringsTest(unittest.TestCase): @classmethod def add_smoke_test(cls, cfg): def test(self): # We just want to see if this will blow up. Use the fallback # lang_tag across all tests. lang_tag = cfg.lang_code if cfg.accept_language: lang_tag = cfg.accept_language[-1] self.assertNotEqual({}, chstrings.get_localized_strings(cfg, lang_tag)) name = 'test_' + cfg.lang_code + '_smoke_test' setattr(cls, name, test) if __name__ == '__main__': for lc in config.LANG_CODES_TO_LANG_NAMES: cfg = config.get_localized_config(lc) CHStringsTest.add_smoke_test(cfg) unittest.main()
Extend chstrings smoke test a little more.
Extend chstrings smoke test a little more.
Python
mit
eggpi/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt
python
## Code Before: import chstrings import config import unittest class CHStringsTest(unittest.TestCase): @classmethod def add_smoke_test(cls, cfg): def test(self): # We just want to see if this will blow up chstrings.get_localized_strings(cfg, cfg.lang_code) name = 'test_' + cfg.lang_code + '_smoke_test' setattr(cls, name, test) if __name__ == '__main__': for lc in config.LANG_CODES_TO_LANG_NAMES: cfg = config.get_localized_config(lc) CHStringsTest.add_smoke_test(cfg) unittest.main() ## Instruction: Extend chstrings smoke test a little more. ## Code After: import chstrings import config import unittest class CHStringsTest(unittest.TestCase): @classmethod def add_smoke_test(cls, cfg): def test(self): # We just want to see if this will blow up. Use the fallback # lang_tag across all tests. lang_tag = cfg.lang_code if cfg.accept_language: lang_tag = cfg.accept_language[-1] self.assertNotEqual({}, chstrings.get_localized_strings(cfg, lang_tag)) name = 'test_' + cfg.lang_code + '_smoke_test' setattr(cls, name, test) if __name__ == '__main__': for lc in config.LANG_CODES_TO_LANG_NAMES: cfg = config.get_localized_config(lc) CHStringsTest.add_smoke_test(cfg) unittest.main()
// ... existing code ... @classmethod def add_smoke_test(cls, cfg): def test(self): # We just want to see if this will blow up. Use the fallback # lang_tag across all tests. lang_tag = cfg.lang_code if cfg.accept_language: lang_tag = cfg.accept_language[-1] self.assertNotEqual({}, chstrings.get_localized_strings(cfg, lang_tag)) name = 'test_' + cfg.lang_code + '_smoke_test' setattr(cls, name, test) // ... rest of the code ...
d921858302f8bba715a7f4e63eaec68dfe04927a
app/grandchallenge/workstations/context_processors.py
app/grandchallenge/workstations/context_processors.py
from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) return {"workstation_session": s}
from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None try: if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) except AttributeError: # No user pass return {"workstation_session": s}
Handle no user at all
Handle no user at all
Python
apache-2.0
comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django
python
## Code Before: from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) return {"workstation_session": s} ## Instruction: Handle no user at all ## Code After: from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None try: if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) except AttributeError: # No user pass return {"workstation_session": s}
// ... existing code ... s = None try: if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.QUEUED, Session.STOPPED]) .order_by("-created") .select_related("workstation_image__workstation") .first() ) except AttributeError: # No user pass return {"workstation_session": s} // ... rest of the code ...
6068905219a04974f18033b3cf64b2a037f05d7b
opps/core/__init__.py
opps/core/__init__.py
from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Opps') settings.INSTALLED_APPS += ('opps.article', 'opps.image', 'opps.channel', 'opps.source', 'redactor', 'tagging',) settings.REDACTOR_OPTIONS = {'lang': 'en'} settings.REDACTOR_UPLOAD = 'uploads/'
from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Opps') settings.INSTALLED_APPS += ('opps.article', 'opps.image', 'opps.channel', 'opps.source', 'django.contrib.redirects', 'redactor', 'tagging',) settings.MIDDLEWARE_CLASSES += ( 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',) settings.REDACTOR_OPTIONS = {'lang': 'en'} settings.REDACTOR_UPLOAD = 'uploads/'
Add django contrib redirects on opps core init
Add django contrib redirects on opps core init
Python
mit
opps/opps,opps/opps,williamroot/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,opps/opps
python
## Code Before: from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Opps') settings.INSTALLED_APPS += ('opps.article', 'opps.image', 'opps.channel', 'opps.source', 'redactor', 'tagging',) settings.REDACTOR_OPTIONS = {'lang': 'en'} settings.REDACTOR_UPLOAD = 'uploads/' ## Instruction: Add django contrib redirects on opps core init ## Code After: from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Opps') settings.INSTALLED_APPS += ('opps.article', 'opps.image', 'opps.channel', 'opps.source', 'django.contrib.redirects', 'redactor', 'tagging',) settings.MIDDLEWARE_CLASSES += ( 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',) settings.REDACTOR_OPTIONS = {'lang': 'en'} settings.REDACTOR_UPLOAD = 'uploads/'
// ... existing code ... 'opps.image', 'opps.channel', 'opps.source', 'django.contrib.redirects', 'redactor', 'tagging',) settings.MIDDLEWARE_CLASSES += ( 'django.contrib.redirects.middleware.RedirectFallbackMiddleware',) settings.REDACTOR_OPTIONS = {'lang': 'en'} settings.REDACTOR_UPLOAD = 'uploads/' // ... rest of the code ...
aacd131aadb0ce730477688cb4be0b36020ea281
app/src/main/java/de/fau/amos/virtualledger/android/api/shared/RetrofitCallback.java
app/src/main/java/de/fau/amos/virtualledger/android/api/shared/RetrofitCallback.java
package de.fau.amos.virtualledger.android.api.shared; import android.util.Log; import io.reactivex.subjects.PublishSubject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class RetrofitCallback<T> implements Callback<T> { private static final String TAG = RetrofitCallback.class.getSimpleName(); private final PublishSubject<T> observable; public RetrofitCallback(final PublishSubject<T> observable) { this.observable = observable; } @Override public void onResponse(final Call<T> call, final Response<T> response) { // got response from server final String requestString = "Request " + call.request().method() + " " + call.request().url() + " "; if (response.isSuccessful()) { final T result = response.body(); Log.v(TAG, requestString + "was successful: " + response.code()); observable.onNext(result); } else { Log.e(TAG, requestString + "was not successful! ERROR " + response.code()); observable.onError(new Throwable(requestString + " was not successful!")); } } @Override public void onFailure(final Call<T> call, final Throwable t) { // response of server failed Log.e(TAG, "No connection to server!"); observable.onError(t); } }
package de.fau.amos.virtualledger.android.api.shared; import android.util.Log; import java.io.IOException; import io.reactivex.subjects.PublishSubject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class RetrofitCallback<T> implements Callback<T> { private static final String TAG = RetrofitCallback.class.getSimpleName(); private final PublishSubject<T> observable; public RetrofitCallback(final PublishSubject<T> observable) { this.observable = observable; } @Override public void onResponse(final Call<T> call, final Response<T> response) { // got response from server final String requestString = "Request " + call.request().method() + " " + call.request().url() + " "; if (response.isSuccessful()) { final T result = response.body(); Log.v(TAG, requestString + "was successful: " + response.code()); observable.onNext(result); } else { Log.e(TAG, requestString + "was not successful! ERROR " + response.code()); observable.onError(new IOException(requestString + " was not successful!")); } } @Override public void onFailure(final Call<T> call, final Throwable t) { // response of server failed Log.e(TAG, "No connection to server!"); observable.onError(t); } }
Use IOException instead of Throwable for not successful http status
Use IOException instead of Throwable for not successful http status
Java
apache-2.0
BankingBoys/amos-ss17-proj7,BankingBoys/amos-ss17-proj7
java
## Code Before: package de.fau.amos.virtualledger.android.api.shared; import android.util.Log; import io.reactivex.subjects.PublishSubject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class RetrofitCallback<T> implements Callback<T> { private static final String TAG = RetrofitCallback.class.getSimpleName(); private final PublishSubject<T> observable; public RetrofitCallback(final PublishSubject<T> observable) { this.observable = observable; } @Override public void onResponse(final Call<T> call, final Response<T> response) { // got response from server final String requestString = "Request " + call.request().method() + " " + call.request().url() + " "; if (response.isSuccessful()) { final T result = response.body(); Log.v(TAG, requestString + "was successful: " + response.code()); observable.onNext(result); } else { Log.e(TAG, requestString + "was not successful! ERROR " + response.code()); observable.onError(new Throwable(requestString + " was not successful!")); } } @Override public void onFailure(final Call<T> call, final Throwable t) { // response of server failed Log.e(TAG, "No connection to server!"); observable.onError(t); } } ## Instruction: Use IOException instead of Throwable for not successful http status ## Code After: package de.fau.amos.virtualledger.android.api.shared; import android.util.Log; import java.io.IOException; import io.reactivex.subjects.PublishSubject; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class RetrofitCallback<T> implements Callback<T> { private static final String TAG = RetrofitCallback.class.getSimpleName(); private final PublishSubject<T> observable; public RetrofitCallback(final PublishSubject<T> observable) { this.observable = observable; } @Override public void onResponse(final Call<T> call, final Response<T> response) { // got response from server final String requestString = "Request " + call.request().method() + " " + call.request().url() + " "; if (response.isSuccessful()) { final T result = response.body(); Log.v(TAG, requestString + "was successful: " + response.code()); observable.onNext(result); } else { Log.e(TAG, requestString + "was not successful! ERROR " + response.code()); observable.onError(new IOException(requestString + " was not successful!")); } } @Override public void onFailure(final Call<T> call, final Throwable t) { // response of server failed Log.e(TAG, "No connection to server!"); observable.onError(t); } }
// ... existing code ... package de.fau.amos.virtualledger.android.api.shared; import android.util.Log; import java.io.IOException; import io.reactivex.subjects.PublishSubject; import retrofit2.Call; // ... modified code ... observable.onNext(result); } else { Log.e(TAG, requestString + "was not successful! ERROR " + response.code()); observable.onError(new IOException(requestString + " was not successful!")); } } // ... rest of the code ...
45e3a01380cd5c4487a241aad14d69c88649d96e
bcelldb_init.py
bcelldb_init.py
import re def get_config(): """ Look for config file in . and than ../ Return config key value pairs in dictionary conf[]. """ # try to open config file in . try: config_file = open("config","r") except IOError: # try from ../ directory try: config_file = open("../config", "r") except IOError: print "no config file found" # global dictionary conf that will be exported conf = dict() # read lines of config for line in config_file: # every line with # is used as a comment line if re.search('=', line) and not re.match('\s?#', line): # split entries into key-value [key, value] = re.split("=", line) # get rid of new line conf[key] = value[:-1] # return conf[] return conf
import re re_key_value = re.compile("^\s*([_A-Za-z][_0-9A-Za-z]+)=(.*?)\s*;?\s*$") re_inline_comment = re.compile("^(.*?)(?<!\\\\)#.*") def get_config(): """ Look for config file in . and than ../ Return config key value pairs in dictionary conf[]. """ # try to open config file in . try: config_file = open("config","r") except IOError: # try from ../ directory try: config_file = open("../config", "r") except IOError: print "no config file found" # global dictionary conf that will be exported conf = dict() # read lines of config for line in config_file: line = line.rstrip() if not re.match("^\s*$", line) and not re.match("^\s*#", line): # Split entries into key-value. line = re_inline_comment.sub('\g<1>', line) key, value = re_key_value.match(line).group(1,2) conf[key] = value return conf
Fix handling of separator characters by Python modules
Fix handling of separator characters by Python modules Currently the Python modules do not tolerate more than one equal sign ("=") in each line of the config file. However REs with look-ahead functionality require this character. Introduce new RE-based line-splitting mechanism. Fix handling of in-line comments.
Python
agpl-3.0
b-cell-immunology/sciReptor,b-cell-immunology/sciReptor,b-cell-immunology/sciReptor,b-cell-immunology/sciReptor
python
## Code Before: import re def get_config(): """ Look for config file in . and than ../ Return config key value pairs in dictionary conf[]. """ # try to open config file in . try: config_file = open("config","r") except IOError: # try from ../ directory try: config_file = open("../config", "r") except IOError: print "no config file found" # global dictionary conf that will be exported conf = dict() # read lines of config for line in config_file: # every line with # is used as a comment line if re.search('=', line) and not re.match('\s?#', line): # split entries into key-value [key, value] = re.split("=", line) # get rid of new line conf[key] = value[:-1] # return conf[] return conf ## Instruction: Fix handling of separator characters by Python modules Currently the Python modules do not tolerate more than one equal sign ("=") in each line of the config file. However REs with look-ahead functionality require this character. Introduce new RE-based line-splitting mechanism. Fix handling of in-line comments. ## Code After: import re re_key_value = re.compile("^\s*([_A-Za-z][_0-9A-Za-z]+)=(.*?)\s*;?\s*$") re_inline_comment = re.compile("^(.*?)(?<!\\\\)#.*") def get_config(): """ Look for config file in . and than ../ Return config key value pairs in dictionary conf[]. """ # try to open config file in . try: config_file = open("config","r") except IOError: # try from ../ directory try: config_file = open("../config", "r") except IOError: print "no config file found" # global dictionary conf that will be exported conf = dict() # read lines of config for line in config_file: line = line.rstrip() if not re.match("^\s*$", line) and not re.match("^\s*#", line): # Split entries into key-value. line = re_inline_comment.sub('\g<1>', line) key, value = re_key_value.match(line).group(1,2) conf[key] = value return conf
// ... existing code ... import re re_key_value = re.compile("^\s*([_A-Za-z][_0-9A-Za-z]+)=(.*?)\s*;?\s*$") re_inline_comment = re.compile("^(.*?)(?<!\\\\)#.*") def get_config(): """ // ... modified code ... # read lines of config for line in config_file: line = line.rstrip() if not re.match("^\s*$", line) and not re.match("^\s*#", line): # Split entries into key-value. line = re_inline_comment.sub('\g<1>', line) key, value = re_key_value.match(line).group(1,2) conf[key] = value return conf // ... rest of the code ...
bde734dc751cbfd59b40c1c2f0d60229795fae4a
tests/app/main/test_request_header.py
tests/app/main/test_request_header.py
import pytest from tests.conftest import set_config_values @pytest.mark.parametrize('check_proxy_header,header_value,expected_code', [ (True, 'key_1', 200), (True, 'wrong_key', 403), (False, 'wrong_key', 200), (False, 'key_1', 200), ]) def test_route_correct_secret_key(app_, check_proxy_header, header_value, expected_code): with set_config_values(app_, { 'ROUTE_SECRET_KEY_1': 'key_1', 'ROUTE_SECRET_KEY_2': '', 'CHECK_PROXY_HEADER': check_proxy_header, }): client = app_.test_client() response = client.get( path='/_status?elb=True', headers=[ ('X-Custom-forwarder', header_value), ] ) assert response.status_code == expected_code
import pytest from tests.conftest import set_config_values @pytest.mark.parametrize('check_proxy_header,header_value,expected_code', [ (True, 'key_1', 200), (True, 'wrong_key', 403), (False, 'wrong_key', 200), (False, 'key_1', 200), ]) def test_route_correct_secret_key(app_, check_proxy_header, header_value, expected_code): with set_config_values(app_, { 'ROUTE_SECRET_KEY_1': 'key_1', 'ROUTE_SECRET_KEY_2': '', 'CHECK_PROXY_HEADER': check_proxy_header, }): with app_.test_client() as client: response = client.get( path='/_status?elb=True', headers=[ ('X-Custom-forwarder', header_value), ] ) assert response.status_code == expected_code
Use test_client() as context manager
Use test_client() as context manager
Python
mit
gov-cjwaszczuk/notifications-admin,gov-cjwaszczuk/notifications-admin,gov-cjwaszczuk/notifications-admin,alphagov/notifications-admin,gov-cjwaszczuk/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin
python
## Code Before: import pytest from tests.conftest import set_config_values @pytest.mark.parametrize('check_proxy_header,header_value,expected_code', [ (True, 'key_1', 200), (True, 'wrong_key', 403), (False, 'wrong_key', 200), (False, 'key_1', 200), ]) def test_route_correct_secret_key(app_, check_proxy_header, header_value, expected_code): with set_config_values(app_, { 'ROUTE_SECRET_KEY_1': 'key_1', 'ROUTE_SECRET_KEY_2': '', 'CHECK_PROXY_HEADER': check_proxy_header, }): client = app_.test_client() response = client.get( path='/_status?elb=True', headers=[ ('X-Custom-forwarder', header_value), ] ) assert response.status_code == expected_code ## Instruction: Use test_client() as context manager ## Code After: import pytest from tests.conftest import set_config_values @pytest.mark.parametrize('check_proxy_header,header_value,expected_code', [ (True, 'key_1', 200), (True, 'wrong_key', 403), (False, 'wrong_key', 200), (False, 'key_1', 200), ]) def test_route_correct_secret_key(app_, check_proxy_header, header_value, expected_code): with set_config_values(app_, { 'ROUTE_SECRET_KEY_1': 'key_1', 'ROUTE_SECRET_KEY_2': '', 'CHECK_PROXY_HEADER': check_proxy_header, }): with app_.test_client() as client: response = client.get( path='/_status?elb=True', headers=[ ('X-Custom-forwarder', header_value), ] ) assert response.status_code == expected_code
... 'CHECK_PROXY_HEADER': check_proxy_header, }): with app_.test_client() as client: response = client.get( path='/_status?elb=True', headers=[ ('X-Custom-forwarder', header_value), ] ) assert response.status_code == expected_code ...
aa127c5db2a3cab3c2046b53aac59d99516306bf
src/main/java/com/carpentersblocks/entity/item/EntityBase.java
src/main/java/com/carpentersblocks/entity/item/EntityBase.java
package com.carpentersblocks.entity.item; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import com.carpentersblocks.util.protection.IProtected; import com.carpentersblocks.util.protection.ProtectedObject; public class EntityBase extends Entity implements IProtected { private final static byte ID_OWNER = 12; private final static String TAG_OWNER = "owner"; public EntityBase(World world) { super(world); } public EntityBase(World world, EntityPlayer entityPlayer) { this(world); setOwner(new ProtectedObject(entityPlayer)); } @Override public void setOwner(ProtectedObject obj) { getDataWatcher().updateObject(ID_OWNER, obj); } @Override public String getOwner() { return getDataWatcher().getWatchableObjectString(ID_OWNER); } @Override protected void entityInit() { getDataWatcher().addObject(ID_OWNER, new String("")); } @Override protected void readEntityFromNBT(NBTTagCompound nbtTagCompound) { getDataWatcher().updateObject(ID_OWNER, String.valueOf(nbtTagCompound.getString(TAG_OWNER))); } @Override protected void writeEntityToNBT(NBTTagCompound nbtTagCompound) { nbtTagCompound.setString(TAG_OWNER, getDataWatcher().getWatchableObjectString(ID_OWNER)); } }
package com.carpentersblocks.entity.item; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import com.carpentersblocks.util.protection.IProtected; import com.carpentersblocks.util.protection.ProtectedObject; public class EntityBase extends Entity implements IProtected { private final static byte ID_OWNER = 12; private final static String TAG_OWNER = "owner"; public EntityBase(World world) { super(world); } public EntityBase(World world, EntityPlayer entityPlayer) { this(world); setOwner(new ProtectedObject(entityPlayer)); } @Override public void setOwner(ProtectedObject obj) { getDataWatcher().updateObject(ID_OWNER, obj.toString()); } @Override public String getOwner() { return getDataWatcher().getWatchableObjectString(ID_OWNER); } @Override protected void entityInit() { getDataWatcher().addObject(ID_OWNER, new String("")); } @Override protected void readEntityFromNBT(NBTTagCompound nbtTagCompound) { getDataWatcher().updateObject(ID_OWNER, String.valueOf(nbtTagCompound.getString(TAG_OWNER))); } @Override protected void writeEntityToNBT(NBTTagCompound nbtTagCompound) { nbtTagCompound.setString(TAG_OWNER, getDataWatcher().getWatchableObjectString(ID_OWNER)); } }
Fix broken tiles (dev bug only).
Fix broken tiles (dev bug only).
Java
lgpl-2.1
Mineshopper/carpentersblocks,Techern/carpentersblocks,burpingdog1/carpentersblocks
java
## Code Before: package com.carpentersblocks.entity.item; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import com.carpentersblocks.util.protection.IProtected; import com.carpentersblocks.util.protection.ProtectedObject; public class EntityBase extends Entity implements IProtected { private final static byte ID_OWNER = 12; private final static String TAG_OWNER = "owner"; public EntityBase(World world) { super(world); } public EntityBase(World world, EntityPlayer entityPlayer) { this(world); setOwner(new ProtectedObject(entityPlayer)); } @Override public void setOwner(ProtectedObject obj) { getDataWatcher().updateObject(ID_OWNER, obj); } @Override public String getOwner() { return getDataWatcher().getWatchableObjectString(ID_OWNER); } @Override protected void entityInit() { getDataWatcher().addObject(ID_OWNER, new String("")); } @Override protected void readEntityFromNBT(NBTTagCompound nbtTagCompound) { getDataWatcher().updateObject(ID_OWNER, String.valueOf(nbtTagCompound.getString(TAG_OWNER))); } @Override protected void writeEntityToNBT(NBTTagCompound nbtTagCompound) { nbtTagCompound.setString(TAG_OWNER, getDataWatcher().getWatchableObjectString(ID_OWNER)); } } ## Instruction: Fix broken tiles (dev bug only). ## Code After: package com.carpentersblocks.entity.item; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import com.carpentersblocks.util.protection.IProtected; import com.carpentersblocks.util.protection.ProtectedObject; public class EntityBase extends Entity implements IProtected { private final static byte ID_OWNER = 12; private final static String TAG_OWNER = "owner"; public EntityBase(World world) { super(world); } public EntityBase(World world, EntityPlayer entityPlayer) { this(world); setOwner(new ProtectedObject(entityPlayer)); } @Override public void setOwner(ProtectedObject obj) { getDataWatcher().updateObject(ID_OWNER, obj.toString()); } @Override public String getOwner() { return getDataWatcher().getWatchableObjectString(ID_OWNER); } @Override protected void entityInit() { getDataWatcher().addObject(ID_OWNER, new String("")); } @Override protected void readEntityFromNBT(NBTTagCompound nbtTagCompound) { getDataWatcher().updateObject(ID_OWNER, String.valueOf(nbtTagCompound.getString(TAG_OWNER))); } @Override protected void writeEntityToNBT(NBTTagCompound nbtTagCompound) { nbtTagCompound.setString(TAG_OWNER, getDataWatcher().getWatchableObjectString(ID_OWNER)); } }
... @Override public void setOwner(ProtectedObject obj) { getDataWatcher().updateObject(ID_OWNER, obj.toString()); } @Override ...
4456f5604c1d824f5012bcee550d274c905d74c8
bigcrunch/shutdown.py
bigcrunch/shutdown.py
import asyncio import botocore.exceptions from bigcrunch import webapp @asyncio.coroutine def shutdown(): client = yield from webapp.redshift_client() cluster_control = webapp.ClusterControl(client) try: cluster = yield from cluster_control.get() except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] != 'ClusterNotFound': raise e else: print('Redshift already shutdown') return engine = yield from webapp.create_engine(cluster) with (yield from engine) as conn: db = webapp.Database(conn=conn) sessions = yield from db.running_test_sessions() if sessions == 0: print('shutting down Redshift') yield from cluster_control.destroy() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(shutdown()) loop.close()
import asyncio import botocore.exceptions from bigcrunch import webapp @asyncio.coroutine def shutdown(): client = webapp.redshift_client() cluster_control = webapp.ClusterControl(client) try: cluster = yield from cluster_control.get() except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] != 'ClusterNotFound': raise e else: print('Redshift already shutdown') return engine = yield from webapp.create_engine(cluster) with (yield from engine) as conn: db = webapp.Database(conn=conn) sessions = yield from db.running_test_sessions() if sessions == 0: print('shutting down Redshift') yield from cluster_control.destroy() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(shutdown()) loop.close()
Remove yield from on redshift_client
Remove yield from on redshift_client
Python
agpl-3.0
sqlalchemy-redshift/bigcrunch
python
## Code Before: import asyncio import botocore.exceptions from bigcrunch import webapp @asyncio.coroutine def shutdown(): client = yield from webapp.redshift_client() cluster_control = webapp.ClusterControl(client) try: cluster = yield from cluster_control.get() except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] != 'ClusterNotFound': raise e else: print('Redshift already shutdown') return engine = yield from webapp.create_engine(cluster) with (yield from engine) as conn: db = webapp.Database(conn=conn) sessions = yield from db.running_test_sessions() if sessions == 0: print('shutting down Redshift') yield from cluster_control.destroy() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(shutdown()) loop.close() ## Instruction: Remove yield from on redshift_client ## Code After: import asyncio import botocore.exceptions from bigcrunch import webapp @asyncio.coroutine def shutdown(): client = webapp.redshift_client() cluster_control = webapp.ClusterControl(client) try: cluster = yield from cluster_control.get() except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] != 'ClusterNotFound': raise e else: print('Redshift already shutdown') return engine = yield from webapp.create_engine(cluster) with (yield from engine) as conn: db = webapp.Database(conn=conn) sessions = yield from db.running_test_sessions() if sessions == 0: print('shutting down Redshift') yield from cluster_control.destroy() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(shutdown()) loop.close()
// ... existing code ... @asyncio.coroutine def shutdown(): client = webapp.redshift_client() cluster_control = webapp.ClusterControl(client) try: cluster = yield from cluster_control.get() // ... rest of the code ...