Dataset Viewer
Auto-converted to Parquet
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
7a3772437d9e2250fface932d65fda664ae4e7f2
app/src/main/java/com/x1unix/avi/rest/KPApiInterface.java
app/src/main/java/com/x1unix/avi/rest/KPApiInterface.java
package com.x1unix.avi.rest; import com.x1unix.avi.model.KPMovie; import com.x1unix.avi.model.KPSearchResponse; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; public interface KPApiInterface { @GET("getKPSearchInFilms") Call<KPSearchResponse> findMovies(@Query("keyword") String keyword); @GET("getFilm") Call<KPMovie> getMovieById(@Query("filmID") String filmId); }
package com.x1unix.avi.rest; import com.x1unix.avi.model.KPMovie; import com.x1unix.avi.model.KPSearchResponse; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; public interface KPApiInterface { @GET("getKPSearchInFilms") Call<KPSearchResponse> findMovies(@Query("keyword") String keyword); @GET("getKPFilmDetailView") Call<KPMovie> getMovieById(@Query("filmID") String filmId); }
Use internal KP method for movie details
Use internal KP method for movie details
Java
bsd-3-clause
odin3/Avi,odin3/Avi,odin3/Avi
java
## Code Before: package com.x1unix.avi.rest; import com.x1unix.avi.model.KPMovie; import com.x1unix.avi.model.KPSearchResponse; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; public interface KPApiInterface { @GET("getKPSearchInFilms") Call<KPSearchResponse> findMovies(@Query("keyword") String keyword); @GET("getFilm") Call<KPMovie> getMovieById(@Query("filmID") String filmId); } ## Instruction: Use internal KP method for movie details ## Code After: package com.x1unix.avi.rest; import com.x1unix.avi.model.KPMovie; import com.x1unix.avi.model.KPSearchResponse; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; public interface KPApiInterface { @GET("getKPSearchInFilms") Call<KPSearchResponse> findMovies(@Query("keyword") String keyword); @GET("getKPFilmDetailView") Call<KPMovie> getMovieById(@Query("filmID") String filmId); }
// ... existing code ... @GET("getKPSearchInFilms") Call<KPSearchResponse> findMovies(@Query("keyword") String keyword); @GET("getKPFilmDetailView") Call<KPMovie> getMovieById(@Query("filmID") String filmId); } // ... rest of the code ...
4b16ef27769403b56516233622505b822f7572d5
src/codechicken/lib/render/PlaceholderTexture.java
src/codechicken/lib/render/PlaceholderTexture.java
package codechicken.lib.render; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.IResourceManager; import net.minecraft.util.ResourceLocation; public class PlaceholderTexture extends TextureAtlasSprite { protected PlaceholderTexture(String par1) { super(par1); } @Override public boolean load(IResourceManager manager, ResourceLocation location) { return false; } }
package codechicken.lib.render; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.IResourceManager; import net.minecraft.util.ResourceLocation; public class PlaceholderTexture extends TextureAtlasSprite { protected PlaceholderTexture(String par1) { super(par1); } @Override public boolean hasCustomLoader(IResourceManager manager, ResourceLocation location) { return true; } @Override public boolean load(IResourceManager manager, ResourceLocation location) { return true; } }
Fix texture not found exceptions in console when using placeholder texture
Fix texture not found exceptions in console when using placeholder texture
Java
lgpl-2.1
KJ4IPS/CodeChickenLib,alexbegt/CodeChickenLib,TheCBProject/CodeChickenLib,Chicken-Bones/CodeChickenLib
java
## Code Before: package codechicken.lib.render; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.IResourceManager; import net.minecraft.util.ResourceLocation; public class PlaceholderTexture extends TextureAtlasSprite { protected PlaceholderTexture(String par1) { super(par1); } @Override public boolean load(IResourceManager manager, ResourceLocation location) { return false; } } ## Instruction: Fix texture not found exceptions in console when using placeholder texture ## Code After: package codechicken.lib.render; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.resources.IResourceManager; import net.minecraft.util.ResourceLocation; public class PlaceholderTexture extends TextureAtlasSprite { protected PlaceholderTexture(String par1) { super(par1); } @Override public boolean hasCustomLoader(IResourceManager manager, ResourceLocation location) { return true; } @Override public boolean load(IResourceManager manager, ResourceLocation location) { return true; } }
... public class PlaceholderTexture extends TextureAtlasSprite { protected PlaceholderTexture(String par1) { super(par1); } @Override public boolean hasCustomLoader(IResourceManager manager, ResourceLocation location) { return true; } @Override public boolean load(IResourceManager manager, ResourceLocation location) { return true; } } ...
2c73a41ab78b41da7b6f2ccbd16140fa701d74f2
gunicorn/app/wsgiapp.py
gunicorn/app/wsgiapp.py
import os import sys import traceback from gunicorn import util from gunicorn.app.base import Application class WSGIApplication(Application): def init(self, parser, opts, args): if len(args) != 1: parser.error("No application module specified.") self.cfg.set("default_proc_name", args[0]) self.app_uri = args[0] sys.path.insert(0, os.getcwd()) try: self.load() except: print "Failed to import application: %s" % self.app_uri traceback.print_exc() sys.exit(1) def load(self): return util.import_app(self.app_uri)
import os import sys import traceback from gunicorn import util from gunicorn.app.base import Application class WSGIApplication(Application): def init(self, parser, opts, args): if len(args) != 1: parser.error("No application module specified.") self.cfg.set("default_proc_name", args[0]) self.app_uri = args[0] sys.path.insert(0, os.getcwd()) def load(self): try: return util.import_app(self.app_uri) except: print "Failed to import application: %s" % self.app_uri traceback.print_exc() sys.exit(1)
Load wsgi apps after reading the configuration.
Load wsgi apps after reading the configuration.
Python
mit
WSDC-NITWarangal/gunicorn,wong2/gunicorn,ccl0326/gunicorn,ephes/gunicorn,tempbottle/gunicorn,zhoucen/gunicorn,prezi/gunicorn,urbaniak/gunicorn,wong2/gunicorn,jamesblunt/gunicorn,gtrdotmcs/gunicorn,alex/gunicorn,keakon/gunicorn,jamesblunt/gunicorn,jamesblunt/gunicorn,gtrdotmcs/gunicorn,1stvamp/gunicorn,elelianghh/gunicorn,ccl0326/gunicorn,ammaraskar/gunicorn,gtrdotmcs/gunicorn,urbaniak/gunicorn,malept/gunicorn,pschanely/gunicorn,alex/gunicorn,ccl0326/gunicorn,prezi/gunicorn,GitHublong/gunicorn,zhoucen/gunicorn,prezi/gunicorn,wong2/gunicorn,pschanely/gunicorn,tejasmanohar/gunicorn,malept/gunicorn,pschanely/gunicorn,mvaled/gunicorn,alex/gunicorn,1stvamp/gunicorn,mvaled/gunicorn,MrKiven/gunicorn,urbaniak/gunicorn,harrisonfeng/gunicorn,zhoucen/gunicorn,beni55/gunicorn,z-fork/gunicorn,1stvamp/gunicorn,mvaled/gunicorn,malept/gunicorn
python
## Code Before: import os import sys import traceback from gunicorn import util from gunicorn.app.base import Application class WSGIApplication(Application): def init(self, parser, opts, args): if len(args) != 1: parser.error("No application module specified.") self.cfg.set("default_proc_name", args[0]) self.app_uri = args[0] sys.path.insert(0, os.getcwd()) try: self.load() except: print "Failed to import application: %s" % self.app_uri traceback.print_exc() sys.exit(1) def load(self): return util.import_app(self.app_uri) ## Instruction: Load wsgi apps after reading the configuration. ## Code After: import os import sys import traceback from gunicorn import util from gunicorn.app.base import Application class WSGIApplication(Application): def init(self, parser, opts, args): if len(args) != 1: parser.error("No application module specified.") self.cfg.set("default_proc_name", args[0]) self.app_uri = args[0] sys.path.insert(0, os.getcwd()) def load(self): try: return util.import_app(self.app_uri) except: print "Failed to import application: %s" % self.app_uri traceback.print_exc() sys.exit(1)
// ... existing code ... self.app_uri = args[0] sys.path.insert(0, os.getcwd()) def load(self): try: return util.import_app(self.app_uri) except: print "Failed to import application: %s" % self.app_uri traceback.print_exc() sys.exit(1) // ... rest of the code ...
8a8b152566b92cfe0ccbc379b9871da795cd4b5b
keystoneclient/hacking/checks.py
keystoneclient/hacking/checks.py
import re def check_oslo_namespace_imports(logical_line, blank_before, filename): oslo_namespace_imports = re.compile( r"(((from)|(import))\s+oslo\." "((config)|(serialization)|(utils)|(i18n)))|" "(from\s+oslo\s+import\s+((config)|(serialization)|(utils)|(i18n)))") if re.match(oslo_namespace_imports, logical_line): msg = ("K333: '%s' must be used instead of '%s'.") % ( logical_line.replace('oslo.', 'oslo_'), logical_line) yield(0, msg) def factory(register): register(check_oslo_namespace_imports)
import re def check_oslo_namespace_imports(logical_line, blank_before, filename): oslo_namespace_imports = re.compile( r"(((from)|(import))\s+oslo\.)|(from\s+oslo\s+import\s+)") if re.match(oslo_namespace_imports, logical_line): msg = ("K333: '%s' must be used instead of '%s'.") % ( logical_line.replace('oslo.', 'oslo_'), logical_line) yield(0, msg) def factory(register): register(check_oslo_namespace_imports)
Change hacking check to verify all oslo imports
Change hacking check to verify all oslo imports The hacking check was verifying that specific oslo imports weren't using the oslo-namespaced package. Since all the oslo libraries used by keystoneclient are now changed to use the new package name the hacking check can be simplified. bp drop-namespace-packages Change-Id: I6466e857c6eda0add6918e9fb14dc9296ed98600
Python
apache-2.0
jamielennox/keystoneauth,citrix-openstack-build/keystoneauth,sileht/keystoneauth
python
## Code Before: import re def check_oslo_namespace_imports(logical_line, blank_before, filename): oslo_namespace_imports = re.compile( r"(((from)|(import))\s+oslo\." "((config)|(serialization)|(utils)|(i18n)))|" "(from\s+oslo\s+import\s+((config)|(serialization)|(utils)|(i18n)))") if re.match(oslo_namespace_imports, logical_line): msg = ("K333: '%s' must be used instead of '%s'.") % ( logical_line.replace('oslo.', 'oslo_'), logical_line) yield(0, msg) def factory(register): register(check_oslo_namespace_imports) ## Instruction: Change hacking check to verify all oslo imports The hacking check was verifying that specific oslo imports weren't using the oslo-namespaced package. Since all the oslo libraries used by keystoneclient are now changed to use the new package name the hacking check can be simplified. bp drop-namespace-packages Change-Id: I6466e857c6eda0add6918e9fb14dc9296ed98600 ## Code After: import re def check_oslo_namespace_imports(logical_line, blank_before, filename): oslo_namespace_imports = re.compile( r"(((from)|(import))\s+oslo\.)|(from\s+oslo\s+import\s+)") if re.match(oslo_namespace_imports, logical_line): msg = ("K333: '%s' must be used instead of '%s'.") % ( logical_line.replace('oslo.', 'oslo_'), logical_line) yield(0, msg) def factory(register): register(check_oslo_namespace_imports)
... def check_oslo_namespace_imports(logical_line, blank_before, filename): oslo_namespace_imports = re.compile( r"(((from)|(import))\s+oslo\.)|(from\s+oslo\s+import\s+)") if re.match(oslo_namespace_imports, logical_line): msg = ("K333: '%s' must be used instead of '%s'.") % ( ...
d7c4f0471271d104c0ff3500033e425547ca6c27
notification/context_processors.py
notification/context_processors.py
from notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), } else: return {}
from notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), "notifications": Notice.objects.filter(user=request.user.id) } else: return {}
Add user notifications to context processor
Add user notifications to context processor
Python
mit
affan2/django-notification,affan2/django-notification
python
## Code Before: from notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), } else: return {} ## Instruction: Add user notifications to context processor ## Code After: from notification.models import Notice def notification(request): if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), "notifications": Notice.objects.filter(user=request.user.id) } else: return {}
# ... existing code ... if request.user.is_authenticated(): return { "notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True), "notifications": Notice.objects.filter(user=request.user.id) } else: return {} # ... rest of the code ...
9672bd20203bc4235910080cca6d79c3b8e126b1
nupic/research/frameworks/dendrites/modules/__init__.py
nupic/research/frameworks/dendrites/modules/__init__.py
from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, )
from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, DendriticLayerBase, )
Add DendriticLayerBase to init to ease experimentation
Add DendriticLayerBase to init to ease experimentation
Python
agpl-3.0
mrcslws/nupic.research,subutai/nupic.research,numenta/nupic.research,subutai/nupic.research,numenta/nupic.research,mrcslws/nupic.research
python
## Code Before: from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, ) ## Instruction: Add DendriticLayerBase to init to ease experimentation ## Code After: from .apply_dendrites import * from .boosted_dendrites import * from .dendrite_segments import DendriteSegments from .dendritic_layers import ( AbsoluteMaxGatingDendriticLayer, AbsoluteMaxGatingDendriticLayer2d, BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, DendriticLayerBase, )
// ... existing code ... BiasingDendriticLayer, GatingDendriticLayer, GatingDendriticLayer2d, DendriticLayerBase, ) // ... rest of the code ...
1b4e7ebd4aaa7f506789a112a9338667e955954f
django_git/views.py
django_git/views.py
from pygments import highlight from pygments.lexers import guess_lexer_for_filename from pygments.formatters import HtmlFormatter from django.http import HttpResponse from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 from django.template import RequestContext from django_git.utils import * def index(request, template_name='django_git/index.html'): return render_to_response(template_name, {'repos': get_repos()}, context_instance=RequestContext(request)) def repo(request, repo, template_name='django_git/repo.html'): return render_to_response(template_name, {'repo': get_repo(repo)}, context_instance=RequestContext(request)) def commit(request, repo, commit, template_name='django_git/commit.html'): return render_to_response(template_name, {'diffs': get_commit(repo, commit).diffs, 'repo': get_repo(repo), 'commit': commit }, context_instance=RequestContext(request)) def blob(request, repo, commit): file = request.GET.get('file', '') blob = get_blob(repo, commit, file) lexer = guess_lexer_for_filename(blob.basename, blob.data) return HttpResponse(highlight(blob.data, lexer, HtmlFormatter(cssclass="pygment_highlight", linenos='inline')))
from pygments import highlight from pygments.lexers import guess_lexer_for_filename from pygments.formatters import HtmlFormatter from django.http import HttpResponse from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 from django.template import RequestContext from django_git.utils import * def index(request, template_name='django_git/index.html'): return render_to_response(template_name, {'repos': get_repos()}, context_instance=RequestContext(request)) def repo(request, repo, template_name='django_git/repo.html'): return render_to_response(template_name, {'repo': get_repo(repo)}, context_instance=RequestContext(request)) def commit(request, repo, commit, template_name='django_git/commit.html'): print repo, commit return render_to_response(template_name, {'diffs': get_commit(repo, commit).diffs, 'repo': get_repo(repo), 'commit': commit }, context_instance=RequestContext(request)) def blob(request, repo, commit): file = request.GET.get('file', '') blob = get_blob(repo, commit, file) lexer = guess_lexer_for_filename(blob.basename, blob.data) return HttpResponse(highlight(blob.data, lexer, HtmlFormatter(cssclass="pygment_highlight", linenos='inline')))
Add newline to end of file
Add newline to end of file Signed-off-by: Seth Buntin <[email protected]>
Python
bsd-3-clause
sethtrain/django-git,sethtrain/django-git
python
## Code Before: from pygments import highlight from pygments.lexers import guess_lexer_for_filename from pygments.formatters import HtmlFormatter from django.http import HttpResponse from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 from django.template import RequestContext from django_git.utils import * def index(request, template_name='django_git/index.html'): return render_to_response(template_name, {'repos': get_repos()}, context_instance=RequestContext(request)) def repo(request, repo, template_name='django_git/repo.html'): return render_to_response(template_name, {'repo': get_repo(repo)}, context_instance=RequestContext(request)) def commit(request, repo, commit, template_name='django_git/commit.html'): return render_to_response(template_name, {'diffs': get_commit(repo, commit).diffs, 'repo': get_repo(repo), 'commit': commit }, context_instance=RequestContext(request)) def blob(request, repo, commit): file = request.GET.get('file', '') blob = get_blob(repo, commit, file) lexer = guess_lexer_for_filename(blob.basename, blob.data) return HttpResponse(highlight(blob.data, lexer, HtmlFormatter(cssclass="pygment_highlight", linenos='inline'))) ## Instruction: Add newline to end of file Signed-off-by: Seth Buntin <[email protected]> ## Code After: from pygments import highlight from pygments.lexers import guess_lexer_for_filename from pygments.formatters import HtmlFormatter from django.http import HttpResponse from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404 from django.template import RequestContext from django_git.utils import * def index(request, template_name='django_git/index.html'): return render_to_response(template_name, {'repos': get_repos()}, context_instance=RequestContext(request)) def repo(request, repo, template_name='django_git/repo.html'): return render_to_response(template_name, {'repo': get_repo(repo)}, context_instance=RequestContext(request)) def commit(request, repo, commit, template_name='django_git/commit.html'): print repo, commit return render_to_response(template_name, {'diffs': get_commit(repo, commit).diffs, 'repo': get_repo(repo), 'commit': commit }, context_instance=RequestContext(request)) def blob(request, repo, commit): file = request.GET.get('file', '') blob = get_blob(repo, commit, file) lexer = guess_lexer_for_filename(blob.basename, blob.data) return HttpResponse(highlight(blob.data, lexer, HtmlFormatter(cssclass="pygment_highlight", linenos='inline')))
# ... existing code ... return render_to_response(template_name, {'repo': get_repo(repo)}, context_instance=RequestContext(request)) def commit(request, repo, commit, template_name='django_git/commit.html'): print repo, commit return render_to_response(template_name, {'diffs': get_commit(repo, commit).diffs, 'repo': get_repo(repo), 'commit': commit }, context_instance=RequestContext(request)) def blob(request, repo, commit): # ... rest of the code ...
00922099d6abb03a0dbcca19781eb586d367eab0
skimage/measure/__init__.py
skimage/measure/__init__.py
from .find_contours import find_contours from ._regionprops import regionprops from .find_contours import find_contours from ._structural_similarity import ssim
from .find_contours import find_contours from ._regionprops import regionprops from ._structural_similarity import ssim
Remove double import of find contours.
BUG: Remove double import of find contours.
Python
bsd-3-clause
robintw/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,ajaybhat/scikit-image,rjeli/scikit-image,SamHames/scikit-image,chintak/scikit-image,ofgulban/scikit-image,SamHames/scikit-image,dpshelio/scikit-image,chintak/scikit-image,rjeli/scikit-image,oew1v07/scikit-image,almarklein/scikit-image,pratapvardhan/scikit-image,bsipocz/scikit-image,ClinicalGraphics/scikit-image,vighneshbirodkar/scikit-image,michaelaye/scikit-image,michaelaye/scikit-image,jwiggins/scikit-image,pratapvardhan/scikit-image,keflavich/scikit-image,chriscrosscutler/scikit-image,Britefury/scikit-image,dpshelio/scikit-image,bennlich/scikit-image,bsipocz/scikit-image,blink1073/scikit-image,GaZ3ll3/scikit-image,paalge/scikit-image,almarklein/scikit-image,Hiyorimi/scikit-image,bennlich/scikit-image,Hiyorimi/scikit-image,emon10005/scikit-image,emmanuelle/scikits.image,vighneshbirodkar/scikit-image,ofgulban/scikit-image,almarklein/scikit-image,warmspringwinds/scikit-image,Midafi/scikit-image,youprofit/scikit-image,chintak/scikit-image,newville/scikit-image,Britefury/scikit-image,almarklein/scikit-image,juliusbierk/scikit-image,jwiggins/scikit-image,chriscrosscutler/scikit-image,michaelpacer/scikit-image,emmanuelle/scikits.image,juliusbierk/scikit-image,SamHames/scikit-image,robintw/scikit-image,chintak/scikit-image,WarrenWeckesser/scikits-image,Midafi/scikit-image,emmanuelle/scikits.image,vighneshbirodkar/scikit-image,newville/scikit-image,blink1073/scikit-image,michaelpacer/scikit-image,emmanuelle/scikits.image,oew1v07/scikit-image,emon10005/scikit-image,youprofit/scikit-image,ajaybhat/scikit-image,paalge/scikit-image,rjeli/scikit-image,warmspringwinds/scikit-image,paalge/scikit-image,keflavich/scikit-image,ClinicalGraphics/scikit-image,GaZ3ll3/scikit-image,SamHames/scikit-image
python
## Code Before: from .find_contours import find_contours from ._regionprops import regionprops from .find_contours import find_contours from ._structural_similarity import ssim ## Instruction: BUG: Remove double import of find contours. ## Code After: from .find_contours import find_contours from ._regionprops import regionprops from ._structural_similarity import ssim
# ... existing code ... from .find_contours import find_contours from ._regionprops import regionprops from ._structural_similarity import ssim # ... rest of the code ...
cb048cc483754b003d70844ae99a4c512d35d2ee
setup.py
setup.py
from setuptools import setup, find_packages setup( name='regressive-imagery-dictionary', version='0.1.7', url='https://github.com/jefftriplett/rid.py', license='MIT', description='The Regressive Imagery Dictionary (RID) is a coding scheme for text analysis that is designed to measure "primordial" and conceptual content.', long_description=__doc__, author='John Wiseman', maintainer='Jeff Triplett', maintainer_email='[email protected]', packages=find_packages(), package_data={}, py_modules=['rid'], entry_points={ 'console_scripts': [ 'rid = rid:main', ] }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: Public Domain', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
from setuptools import setup, find_packages setup( name='regressive-imagery-dictionary', version='0.1.7', url='https://github.com/jefftriplett/rid.py', license='MIT', description='The Regressive Imagery Dictionary (RID) is a coding scheme for text analysis that is designed to measure "primordial" and conceptual content.', long_description=__doc__, maintainer='Jeff Triplett', maintainer_email='[email protected]', packages=find_packages(), package_data={}, py_modules=['rid'], entry_points={ 'console_scripts': [ 'rid = rid:main', ] }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: Public Domain', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
Fix for missing author info
Fix for missing author info
Python
mit
jefftriplett/rid.py
python
## Code Before: from setuptools import setup, find_packages setup( name='regressive-imagery-dictionary', version='0.1.7', url='https://github.com/jefftriplett/rid.py', license='MIT', description='The Regressive Imagery Dictionary (RID) is a coding scheme for text analysis that is designed to measure "primordial" and conceptual content.', long_description=__doc__, author='John Wiseman', maintainer='Jeff Triplett', maintainer_email='[email protected]', packages=find_packages(), package_data={}, py_modules=['rid'], entry_points={ 'console_scripts': [ 'rid = rid:main', ] }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: Public Domain', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], ) ## Instruction: Fix for missing author info ## Code After: from setuptools import setup, find_packages setup( name='regressive-imagery-dictionary', version='0.1.7', url='https://github.com/jefftriplett/rid.py', license='MIT', description='The Regressive Imagery Dictionary (RID) is a coding scheme for text analysis that is designed to measure "primordial" and conceptual content.', long_description=__doc__, maintainer='Jeff Triplett', maintainer_email='[email protected]', packages=find_packages(), package_data={}, py_modules=['rid'], entry_points={ 'console_scripts': [ 'rid = rid:main', ] }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: Public Domain', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities' ], )
# ... existing code ... license='MIT', description='The Regressive Imagery Dictionary (RID) is a coding scheme for text analysis that is designed to measure "primordial" and conceptual content.', long_description=__doc__, maintainer='Jeff Triplett', maintainer_email='[email protected]', packages=find_packages(), # ... rest of the code ...
b4e106271f96b083644b27d313ad80c240fcb0a5
gapipy/resources/booking/booking.py
gapipy/resources/booking/booking.py
from __future__ import unicode_literals from gapipy.resources.checkin import Checkin from ..base import Resource from .transaction import Payment, Refund from .document import Invoice, Document from .override import Override from .service import Service class Booking(Resource): _resource_name = 'bookings' _is_parent_resource = True _as_is_fields = ['id', 'href', 'external_id', 'currency'] _price_fields = [ 'amount_owing', 'amount_paid', 'amount_pending', 'commission', 'tax_on_commission', ] _date_fields = [ 'date_closed', 'date_of_first_travel', 'date_of_last_travel', 'balance_due_date', ] _date_time_fields_utc = ['date_created', ] _resource_fields = [ ('agent', 'Agent'), ('agency', 'Agency'), ('associated_agency', 'Agency'), ] @property def _resource_collection_fields(self): return [ ('services', Service), ('invoices', Invoice), ('payments', Payment), ('refunds', Refund), ('documents', Document), ('overrides', Override), ('checkins', Checkin), ]
from __future__ import unicode_literals from gapipy.resources.checkin import Checkin from ..base import Resource from .agency_chain import AgencyChain from .document import Invoice, Document from .override import Override from .service import Service from .transaction import Payment, Refund class Booking(Resource): _resource_name = 'bookings' _is_parent_resource = True _as_is_fields = ['id', 'href', 'external_id', 'currency'] _price_fields = [ 'amount_owing', 'amount_paid', 'amount_pending', 'commission', 'tax_on_commission', ] _date_fields = [ 'date_closed', 'date_of_first_travel', 'date_of_last_travel', 'balance_due_date', ] _date_time_fields_utc = ['date_created', ] _resource_fields = [ ('agency', 'Agency'), ('agency_chain', AgencyChain), ('agent', 'Agent'), ('associated_agency', 'Agency'), ] @property def _resource_collection_fields(self): return [ ('services', Service), ('invoices', Invoice), ('payments', Payment), ('refunds', Refund), ('documents', Document), ('overrides', Override), ('checkins', Checkin), ]
Add agency chain to Booking
Add agency chain to Booking
Python
mit
gadventures/gapipy
python
## Code Before: from __future__ import unicode_literals from gapipy.resources.checkin import Checkin from ..base import Resource from .transaction import Payment, Refund from .document import Invoice, Document from .override import Override from .service import Service class Booking(Resource): _resource_name = 'bookings' _is_parent_resource = True _as_is_fields = ['id', 'href', 'external_id', 'currency'] _price_fields = [ 'amount_owing', 'amount_paid', 'amount_pending', 'commission', 'tax_on_commission', ] _date_fields = [ 'date_closed', 'date_of_first_travel', 'date_of_last_travel', 'balance_due_date', ] _date_time_fields_utc = ['date_created', ] _resource_fields = [ ('agent', 'Agent'), ('agency', 'Agency'), ('associated_agency', 'Agency'), ] @property def _resource_collection_fields(self): return [ ('services', Service), ('invoices', Invoice), ('payments', Payment), ('refunds', Refund), ('documents', Document), ('overrides', Override), ('checkins', Checkin), ] ## Instruction: Add agency chain to Booking ## Code After: from __future__ import unicode_literals from gapipy.resources.checkin import Checkin from ..base import Resource from .agency_chain import AgencyChain from .document import Invoice, Document from .override import Override from .service import Service from .transaction import Payment, Refund class Booking(Resource): _resource_name = 'bookings' _is_parent_resource = True _as_is_fields = ['id', 'href', 'external_id', 'currency'] _price_fields = [ 'amount_owing', 'amount_paid', 'amount_pending', 'commission', 'tax_on_commission', ] _date_fields = [ 'date_closed', 'date_of_first_travel', 'date_of_last_travel', 'balance_due_date', ] _date_time_fields_utc = ['date_created', ] _resource_fields = [ ('agency', 'Agency'), ('agency_chain', AgencyChain), ('agent', 'Agent'), ('associated_agency', 'Agency'), ] @property def _resource_collection_fields(self): return [ ('services', Service), ('invoices', Invoice), ('payments', Payment), ('refunds', Refund), ('documents', Document), ('overrides', Override), ('checkins', Checkin), ]
# ... existing code ... from gapipy.resources.checkin import Checkin from ..base import Resource from .agency_chain import AgencyChain from .document import Invoice, Document from .override import Override from .service import Service from .transaction import Payment, Refund class Booking(Resource): # ... modified code ... ] _date_time_fields_utc = ['date_created', ] _resource_fields = [ ('agency', 'Agency'), ('agency_chain', AgencyChain), ('agent', 'Agent'), ('associated_agency', 'Agency'), ] # ... rest of the code ...
3ad4a7f564acc9e653d57c6a6bbbd10bbc87ea01
src/com/haxademic/core/image/filters/shaders/ChromaColorFilter.java
src/com/haxademic/core/image/filters/shaders/ChromaColorFilter.java
package com.haxademic.core.image.filters.shaders; import processing.core.PApplet; public class ChromaColorFilter extends BaseFilter { public static ChromaColorFilter instance; public ChromaColorFilter(PApplet p) { super(p, "shaders/filters/chroma-color.glsl"); setThresholdSensitivity(0.1f); setSmoothing(0.7f); setColorToReplace(0, 0, 0); } public static ChromaColorFilter instance(PApplet p) { if(instance != null) return instance; instance = new ChromaColorFilter(p); return instance; } public void setThresholdSensitivity(float thresholdSensitivity) { shader.set("thresholdSensitivity", thresholdSensitivity); } public void setSmoothing(float smoothing) { shader.set("smoothing", smoothing); } public void setColorToReplace(float colorToReplaceR, float colorToReplaceG, float colorToReplaceB) { shader.set("colorToReplace", colorToReplaceR, colorToReplaceG, colorToReplaceB); } }
package com.haxademic.core.image.filters.shaders; import processing.core.PApplet; public class ChromaColorFilter extends BaseFilter { public static ChromaColorFilter instance; public ChromaColorFilter(PApplet p) { super(p, "shaders/filters/chroma-color.glsl"); setThresholdSensitivity(0.1f); setSmoothing(0.7f); setColorToReplace(0, 0, 0); } public static ChromaColorFilter instance(PApplet p) { if(instance != null) return instance; instance = new ChromaColorFilter(p); return instance; } public void setThresholdSensitivity(float thresholdSensitivity) { shader.set("thresholdSensitivity", thresholdSensitivity); } public void setSmoothing(float smoothing) { shader.set("smoothing", smoothing); } public void setColorToReplace(float colorToReplaceR, float colorToReplaceG, float colorToReplaceB) { shader.set("colorToReplace", colorToReplaceR, colorToReplaceG, colorToReplaceB); } public void presetGreenScreen() { setThresholdSensitivity(0.73f); setSmoothing(0.08f); setColorToReplace(0.71f, 0.99f, 0.02f); } public void presetBlackKnockout() { setThresholdSensitivity(0.2f); setSmoothing(0.1f); setColorToReplace(0.0f, 0.0f, 0.0f); } }
Add a couple of chrome presets
Add a couple of chrome presets
Java
mit
cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic
java
## Code Before: package com.haxademic.core.image.filters.shaders; import processing.core.PApplet; public class ChromaColorFilter extends BaseFilter { public static ChromaColorFilter instance; public ChromaColorFilter(PApplet p) { super(p, "shaders/filters/chroma-color.glsl"); setThresholdSensitivity(0.1f); setSmoothing(0.7f); setColorToReplace(0, 0, 0); } public static ChromaColorFilter instance(PApplet p) { if(instance != null) return instance; instance = new ChromaColorFilter(p); return instance; } public void setThresholdSensitivity(float thresholdSensitivity) { shader.set("thresholdSensitivity", thresholdSensitivity); } public void setSmoothing(float smoothing) { shader.set("smoothing", smoothing); } public void setColorToReplace(float colorToReplaceR, float colorToReplaceG, float colorToReplaceB) { shader.set("colorToReplace", colorToReplaceR, colorToReplaceG, colorToReplaceB); } } ## Instruction: Add a couple of chrome presets ## Code After: package com.haxademic.core.image.filters.shaders; import processing.core.PApplet; public class ChromaColorFilter extends BaseFilter { public static ChromaColorFilter instance; public ChromaColorFilter(PApplet p) { super(p, "shaders/filters/chroma-color.glsl"); setThresholdSensitivity(0.1f); setSmoothing(0.7f); setColorToReplace(0, 0, 0); } public static ChromaColorFilter instance(PApplet p) { if(instance != null) return instance; instance = new ChromaColorFilter(p); return instance; } public void setThresholdSensitivity(float thresholdSensitivity) { shader.set("thresholdSensitivity", thresholdSensitivity); } public void setSmoothing(float smoothing) { shader.set("smoothing", smoothing); } public void setColorToReplace(float colorToReplaceR, float colorToReplaceG, float colorToReplaceB) { shader.set("colorToReplace", colorToReplaceR, colorToReplaceG, colorToReplaceB); } public void presetGreenScreen() { setThresholdSensitivity(0.73f); setSmoothing(0.08f); setColorToReplace(0.71f, 0.99f, 0.02f); } public void presetBlackKnockout() { setThresholdSensitivity(0.2f); setSmoothing(0.1f); setColorToReplace(0.0f, 0.0f, 0.0f); } }
# ... existing code ... shader.set("colorToReplace", colorToReplaceR, colorToReplaceG, colorToReplaceB); } public void presetGreenScreen() { setThresholdSensitivity(0.73f); setSmoothing(0.08f); setColorToReplace(0.71f, 0.99f, 0.02f); } public void presetBlackKnockout() { setThresholdSensitivity(0.2f); setSmoothing(0.1f); setColorToReplace(0.0f, 0.0f, 0.0f); } } # ... rest of the code ...
3a0cf1f6114d6c80909f90fe122b026908200b0a
IPython/nbconvert/exporters/markdown.py
IPython/nbconvert/exporters/markdown.py
"""Markdown Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.config import Config from .templateexporter import TemplateExporter #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class MarkdownExporter(TemplateExporter): """ Exports to a markdown document (.md) """ def _file_extension_default(self): return 'md' def _template_file_default(self): return 'markdown' output_mimetype = 'text/markdown' def _raw_mimetypes_default(self): return ['text/markdown', 'text/html', ''] @property def default_config(self): c = Config({ 'NbConvertBase': { 'display_data_priority': ['html', 'application/pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text'] }, 'ExtractOutputPreprocessor': { 'enabled':True} }) c.merge(super(MarkdownExporter,self).default_config) return c
"""Markdown Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.config import Config from .templateexporter import TemplateExporter #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class MarkdownExporter(TemplateExporter): """ Exports to a markdown document (.md) """ def _file_extension_default(self): return 'md' def _template_file_default(self): return 'markdown' output_mimetype = 'text/markdown' def _raw_mimetypes_default(self): return ['text/markdown', 'text/html', ''] @property def default_config(self): c = Config({'ExtractOutputPreprocessor':{'enabled':True}}) c.merge(super(MarkdownExporter,self).default_config) return c
Revert "Removed Javascript from Markdown by adding display priority to def config."
Revert "Removed Javascript from Markdown by adding display priority to def config." This reverts commit 58e05f9625c60f8deba9ddf1c74dba73e8ea7dd1.
Python
bsd-3-clause
ipython/ipython,ipython/ipython
python
## Code Before: """Markdown Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.config import Config from .templateexporter import TemplateExporter #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class MarkdownExporter(TemplateExporter): """ Exports to a markdown document (.md) """ def _file_extension_default(self): return 'md' def _template_file_default(self): return 'markdown' output_mimetype = 'text/markdown' def _raw_mimetypes_default(self): return ['text/markdown', 'text/html', ''] @property def default_config(self): c = Config({ 'NbConvertBase': { 'display_data_priority': ['html', 'application/pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text'] }, 'ExtractOutputPreprocessor': { 'enabled':True} }) c.merge(super(MarkdownExporter,self).default_config) return c ## Instruction: Revert "Removed Javascript from Markdown by adding display priority to def config." This reverts commit 58e05f9625c60f8deba9ddf1c74dba73e8ea7dd1. ## Code After: """Markdown Exporter class""" #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from IPython.config import Config from .templateexporter import TemplateExporter #----------------------------------------------------------------------------- # Classes #----------------------------------------------------------------------------- class MarkdownExporter(TemplateExporter): """ Exports to a markdown document (.md) """ def _file_extension_default(self): return 'md' def _template_file_default(self): return 'markdown' output_mimetype = 'text/markdown' def _raw_mimetypes_default(self): return ['text/markdown', 'text/html', ''] @property def default_config(self): c = Config({'ExtractOutputPreprocessor':{'enabled':True}}) c.merge(super(MarkdownExporter,self).default_config) return c
... @property def default_config(self): c = Config({'ExtractOutputPreprocessor':{'enabled':True}}) c.merge(super(MarkdownExporter,self).default_config) return c ...
41021611b9bccbc524ababfab256fe7d7f28cf1c
src/lib/ems_server.c
src/lib/ems_server.c
/*============================================================================* * Local * *============================================================================*/ /*============================================================================* * Global * *============================================================================*/ void ems_server_init(void) { Azy_Server *serv; Azy_Server_Module_Def **mods; azy_init(); //Define the list of module used by the server. Azy_Server_Module_Def *modules[] = { EMS_Config_module_def(), NULL }; serv = azy_server_new(EINA_FALSE); azy_server_addr_set(serv, "0.0.0.0"); azy_server_port_set(serv, 2000); for (mods = modules; mods && *mods; mods++) { if (!azy_server_module_add(serv, *mods)) ERR("Unable to create server\n"); } INF("Start Azy server"); azy_server_start(serv); } /*============================================================================* * API * *============================================================================*/
/*============================================================================* * Local * *============================================================================*/ Azy_Server *_serv; /*============================================================================* * Global * *============================================================================*/ void ems_server_init(void) { Azy_Server_Module_Def **mods; azy_init(); //Define the list of module used by the server. Azy_Server_Module_Def *modules[] = { EMS_Config_module_def(), NULL }; _serv = azy_server_new(EINA_FALSE); azy_server_addr_set(_serv, "0.0.0.0"); azy_server_port_set(_serv, ems_config->port); for (mods = modules; mods && *mods; mods++) { if (!azy_server_module_add(_serv, *mods)) ERR("Unable to create server\n"); } } void ems_server_run(void) { INF("Start Azy server"); azy_server_run(_serv); } /*============================================================================* * API * *============================================================================*/
Use azy_server_run as a replacement for ecore_main_loop_begin
Use azy_server_run as a replacement for ecore_main_loop_begin
C
bsd-2-clause
enna-project/Enna-Media-Server,raoulh/Enna-Media-Server,enna-project/Enna-Media-Server,raoulh/Enna-Media-Server,enna-project/Enna-Media-Server,enna-project/Enna-Media-Server,raoulh/Enna-Media-Server,enna-project/Enna-Media-Server,raoulh/Enna-Media-Server,raoulh/Enna-Media-Server
c
## Code Before: /*============================================================================* * Local * *============================================================================*/ /*============================================================================* * Global * *============================================================================*/ void ems_server_init(void) { Azy_Server *serv; Azy_Server_Module_Def **mods; azy_init(); //Define the list of module used by the server. Azy_Server_Module_Def *modules[] = { EMS_Config_module_def(), NULL }; serv = azy_server_new(EINA_FALSE); azy_server_addr_set(serv, "0.0.0.0"); azy_server_port_set(serv, 2000); for (mods = modules; mods && *mods; mods++) { if (!azy_server_module_add(serv, *mods)) ERR("Unable to create server\n"); } INF("Start Azy server"); azy_server_start(serv); } /*============================================================================* * API * *============================================================================*/ ## Instruction: Use azy_server_run as a replacement for ecore_main_loop_begin ## Code After: /*============================================================================* * Local * *============================================================================*/ Azy_Server *_serv; /*============================================================================* * Global * *============================================================================*/ void ems_server_init(void) { Azy_Server_Module_Def **mods; azy_init(); //Define the list of module used by the server. Azy_Server_Module_Def *modules[] = { EMS_Config_module_def(), NULL }; _serv = azy_server_new(EINA_FALSE); azy_server_addr_set(_serv, "0.0.0.0"); azy_server_port_set(_serv, ems_config->port); for (mods = modules; mods && *mods; mods++) { if (!azy_server_module_add(_serv, *mods)) ERR("Unable to create server\n"); } } void ems_server_run(void) { INF("Start Azy server"); azy_server_run(_serv); } /*============================================================================* * API * *============================================================================*/
... /*============================================================================* * Local * *============================================================================*/ Azy_Server *_serv; /*============================================================================* * Global * ... void ems_server_init(void) { Azy_Server_Module_Def **mods; azy_init(); ... NULL }; _serv = azy_server_new(EINA_FALSE); azy_server_addr_set(_serv, "0.0.0.0"); azy_server_port_set(_serv, ems_config->port); for (mods = modules; mods && *mods; mods++) { if (!azy_server_module_add(_serv, *mods)) ERR("Unable to create server\n"); } } void ems_server_run(void) { INF("Start Azy server"); azy_server_run(_serv); } /*============================================================================* ...
14c88194d67dc600fec3645b0b1e8d52cf0eacf6
app/src/main/java/org/wikipedia/page/PageAvailableOfflineHandler.kt
app/src/main/java/org/wikipedia/page/PageAvailableOfflineHandler.kt
package org.wikipedia.page import android.annotation.SuppressLint import kotlinx.coroutines.* import org.wikipedia.WikipediaApp import org.wikipedia.readinglist.database.ReadingListDbHelper import org.wikipedia.readinglist.database.ReadingListPage import org.wikipedia.util.log.L object PageAvailableOfflineHandler { interface Callback { fun onFinish(available: Boolean) } fun check(page: ReadingListPage, callback: Callback) { callback.onFinish(WikipediaApp.getInstance().isOnline || (page.offline() && !page.saving())) } @SuppressLint("CheckResult") fun check(pageTitle: PageTitle, callback: Callback) { if (WikipediaApp.getInstance().isOnline) { callback.onFinish(true) return } CoroutineScope(Dispatchers.Main).launch(CoroutineExceptionHandler { _, exception -> run { callback.onFinish(false) L.w(exception) } }) { val readingListPage = withContext(Dispatchers.IO) { ReadingListDbHelper.instance().findPageInAnyList(pageTitle) } callback.onFinish(readingListPage!!.offline() && !readingListPage.saving()) } } }
package org.wikipedia.page import android.annotation.SuppressLint import kotlinx.coroutines.* import org.wikipedia.WikipediaApp import org.wikipedia.readinglist.database.ReadingListDbHelper import org.wikipedia.readinglist.database.ReadingListPage import org.wikipedia.util.log.L object PageAvailableOfflineHandler { interface Callback { fun onFinish(available: Boolean) } fun check(page: ReadingListPage, callback: Callback) { callback.onFinish(WikipediaApp.getInstance().isOnline || (page.offline() && !page.saving())) } @SuppressLint("CheckResult") fun check(pageTitle: PageTitle, callback: Callback) { if (WikipediaApp.getInstance().isOnline) { callback.onFinish(true) return } CoroutineScope(Dispatchers.Main).launch(CoroutineExceptionHandler { _, exception -> run { callback.onFinish(false) L.w(exception) } }) { val readingListPage = withContext(Dispatchers.IO) { ReadingListDbHelper.instance().findPageInAnyList(pageTitle) } callback.onFinish(readingListPage != null && readingListPage.offline() && !readingListPage.saving()) } } }
Fix possible crash if cannot find any reading list
Fix possible crash if cannot find any reading list
Kotlin
apache-2.0
dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia,wikimedia/apps-android-wikipedia,dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia,dbrant/apps-android-wikipedia,wikimedia/apps-android-wikipedia
kotlin
## Code Before: package org.wikipedia.page import android.annotation.SuppressLint import kotlinx.coroutines.* import org.wikipedia.WikipediaApp import org.wikipedia.readinglist.database.ReadingListDbHelper import org.wikipedia.readinglist.database.ReadingListPage import org.wikipedia.util.log.L object PageAvailableOfflineHandler { interface Callback { fun onFinish(available: Boolean) } fun check(page: ReadingListPage, callback: Callback) { callback.onFinish(WikipediaApp.getInstance().isOnline || (page.offline() && !page.saving())) } @SuppressLint("CheckResult") fun check(pageTitle: PageTitle, callback: Callback) { if (WikipediaApp.getInstance().isOnline) { callback.onFinish(true) return } CoroutineScope(Dispatchers.Main).launch(CoroutineExceptionHandler { _, exception -> run { callback.onFinish(false) L.w(exception) } }) { val readingListPage = withContext(Dispatchers.IO) { ReadingListDbHelper.instance().findPageInAnyList(pageTitle) } callback.onFinish(readingListPage!!.offline() && !readingListPage.saving()) } } } ## Instruction: Fix possible crash if cannot find any reading list ## Code After: package org.wikipedia.page import android.annotation.SuppressLint import kotlinx.coroutines.* import org.wikipedia.WikipediaApp import org.wikipedia.readinglist.database.ReadingListDbHelper import org.wikipedia.readinglist.database.ReadingListPage import org.wikipedia.util.log.L object PageAvailableOfflineHandler { interface Callback { fun onFinish(available: Boolean) } fun check(page: ReadingListPage, callback: Callback) { callback.onFinish(WikipediaApp.getInstance().isOnline || (page.offline() && !page.saving())) } @SuppressLint("CheckResult") fun check(pageTitle: PageTitle, callback: Callback) { if (WikipediaApp.getInstance().isOnline) { callback.onFinish(true) return } CoroutineScope(Dispatchers.Main).launch(CoroutineExceptionHandler { _, exception -> run { callback.onFinish(false) L.w(exception) } }) { val readingListPage = withContext(Dispatchers.IO) { ReadingListDbHelper.instance().findPageInAnyList(pageTitle) } callback.onFinish(readingListPage != null && readingListPage.offline() && !readingListPage.saving()) } } }
// ... existing code ... } }) { val readingListPage = withContext(Dispatchers.IO) { ReadingListDbHelper.instance().findPageInAnyList(pageTitle) } callback.onFinish(readingListPage != null && readingListPage.offline() && !readingListPage.saving()) } } } // ... rest of the code ...
2a42a82d72d8bfbf11b605002bc4781fee320ea3
setup.py
setup.py
import sys try: from setuptools import setup except ImportError: from distutils import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' readme = open('README.rst', 'r') README_TEXT = readme.read() readme.close() setup( name='aniso8601', version='0.90dev', description='A library for parsing ISO 8601 strings.', long_description=README_TEXT, author='Brandon Nielsen', author_email='[email protected]', url='https://bitbucket.org/nielsenb/aniso8601', packages=['aniso8601'], package_dir={ 'aniso8601' : base_dir + '/aniso8601', }, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
import sys try: from setuptools import setup except ImportError: from distutils import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' readme = open('README.rst', 'r') README_TEXT = readme.read() readme.close() setup( name='aniso8601', version='0.90dev', description='A library for parsing ISO 8601 strings.', long_description=README_TEXT, author='Brandon Nielsen', author_email='[email protected]', url='https://bitbucket.org/nielsenb/aniso8601', packages=['aniso8601'], package_dir={ 'aniso8601' : base_dir + '/aniso8601', }, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Add python2 specifically to classifier list.
Add python2 specifically to classifier list.
Python
bsd-3-clause
3stack-software/python-aniso8601-relativedelta
python
## Code Before: import sys try: from setuptools import setup except ImportError: from distutils import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' readme = open('README.rst', 'r') README_TEXT = readme.read() readme.close() setup( name='aniso8601', version='0.90dev', description='A library for parsing ISO 8601 strings.', long_description=README_TEXT, author='Brandon Nielsen', author_email='[email protected]', url='https://bitbucket.org/nielsenb/aniso8601', packages=['aniso8601'], package_dir={ 'aniso8601' : base_dir + '/aniso8601', }, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) ## Instruction: Add python2 specifically to classifier list. ## Code After: import sys try: from setuptools import setup except ImportError: from distutils import setup if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' readme = open('README.rst', 'r') README_TEXT = readme.read() readme.close() setup( name='aniso8601', version='0.90dev', description='A library for parsing ISO 8601 strings.', long_description=README_TEXT, author='Brandon Nielsen', author_email='[email protected]', url='https://bitbucket.org/nielsenb/aniso8601', packages=['aniso8601'], package_dir={ 'aniso8601' : base_dir + '/aniso8601', }, classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
// ... existing code ... 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries :: Python Modules' ] // ... rest of the code ...
27d7ab7ecca0d2e6307dbcb1317b486fe77a97d7
cyder/core/system/models.py
cyder/core/system/models.py
from django.db import models from cyder.base.mixins import ObjectUrlMixin from cyder.base.models import BaseModel from cyder.cydhcp.keyvalue.models import KeyValue class System(BaseModel, ObjectUrlMixin): name = models.CharField(max_length=255, unique=False) search_fields = ('name',) display_fields = ('name', 'pk') def __str__(self): return "{0} : {1}".format(*(str(getattr(self, f)) for f in self.display_fields)) class Meta: db_table = 'system' def details(self): """For tables.""" data = super(System, self).details() data['data'] = [ ('Name', 'name', self), ] return data @staticmethod def eg_metadata(): """EditableGrid metadata.""" return {'metadata': [ {'name': 'name', 'datatype': 'string', 'editable': True}, ]} class SystemKeyValue(KeyValue): system = models.ForeignKey(System, null=False) class Meta: db_table = 'system_key_value' unique_together = ('key', 'value', 'system')
from django.db import models from cyder.base.mixins import ObjectUrlMixin from cyder.base.models import BaseModel from cyder.base.helpers import get_display from cyder.cydhcp.keyvalue.models import KeyValue class System(BaseModel, ObjectUrlMixin): name = models.CharField(max_length=255, unique=False) search_fields = ('name',) display_fields = ('name',) def __str__(self): return get_display(self) class Meta: db_table = 'system' def details(self): """For tables.""" data = super(System, self).details() data['data'] = [ ('Name', 'name', self), ] return data @staticmethod def eg_metadata(): """EditableGrid metadata.""" return {'metadata': [ {'name': 'name', 'datatype': 'string', 'editable': True}, ]} class SystemKeyValue(KeyValue): system = models.ForeignKey(System, null=False) class Meta: db_table = 'system_key_value' unique_together = ('key', 'value', 'system')
Revert system names to normal
Revert system names to normal
Python
bsd-3-clause
drkitty/cyder,OSU-Net/cyder,drkitty/cyder,murrown/cyder,zeeman/cyder,OSU-Net/cyder,zeeman/cyder,murrown/cyder,akeym/cyder,akeym/cyder,akeym/cyder,zeeman/cyder,drkitty/cyder,OSU-Net/cyder,zeeman/cyder,murrown/cyder,akeym/cyder,murrown/cyder,drkitty/cyder,OSU-Net/cyder
python
## Code Before: from django.db import models from cyder.base.mixins import ObjectUrlMixin from cyder.base.models import BaseModel from cyder.cydhcp.keyvalue.models import KeyValue class System(BaseModel, ObjectUrlMixin): name = models.CharField(max_length=255, unique=False) search_fields = ('name',) display_fields = ('name', 'pk') def __str__(self): return "{0} : {1}".format(*(str(getattr(self, f)) for f in self.display_fields)) class Meta: db_table = 'system' def details(self): """For tables.""" data = super(System, self).details() data['data'] = [ ('Name', 'name', self), ] return data @staticmethod def eg_metadata(): """EditableGrid metadata.""" return {'metadata': [ {'name': 'name', 'datatype': 'string', 'editable': True}, ]} class SystemKeyValue(KeyValue): system = models.ForeignKey(System, null=False) class Meta: db_table = 'system_key_value' unique_together = ('key', 'value', 'system') ## Instruction: Revert system names to normal ## Code After: from django.db import models from cyder.base.mixins import ObjectUrlMixin from cyder.base.models import BaseModel from cyder.base.helpers import get_display from cyder.cydhcp.keyvalue.models import KeyValue class System(BaseModel, ObjectUrlMixin): name = models.CharField(max_length=255, unique=False) search_fields = ('name',) display_fields = ('name',) def __str__(self): return get_display(self) class Meta: db_table = 'system' def details(self): """For tables.""" data = super(System, self).details() data['data'] = [ ('Name', 'name', self), ] return data @staticmethod def eg_metadata(): """EditableGrid metadata.""" return {'metadata': [ {'name': 'name', 'datatype': 'string', 'editable': True}, ]} class SystemKeyValue(KeyValue): system = models.ForeignKey(System, null=False) class Meta: db_table = 'system_key_value' unique_together = ('key', 'value', 'system')
# ... existing code ... from cyder.base.mixins import ObjectUrlMixin from cyder.base.models import BaseModel from cyder.base.helpers import get_display from cyder.cydhcp.keyvalue.models import KeyValue # ... modified code ... name = models.CharField(max_length=255, unique=False) search_fields = ('name',) display_fields = ('name',) def __str__(self): return get_display(self) class Meta: db_table = 'system' # ... rest of the code ...
48b63d01d00c791088b24057751ed1de79811964
src/com/openxc/measurements/ClimateMode.java
src/com/openxc/measurements/ClimateMode.java
package com.openxc.measurements; import java.util.Locale; import com.openxc.units.State; /** * The ClimateMode measurement is used to start the AC/Heater/Fan */ public class ClimateMode extends BaseMeasurement<State<ClimateMode.ClimateControls>> { public final static String ID = "climate_mode"; public enum ClimateControls { UNUSED(0), PANEL_VENT(1), PANEL_FLOOR(2), FLOOR(3), FAN_SPEED_INCREMENT(11), FAN_SPEED_DECREMENT(12), AUTO(13), MAX_AC(14), RECIRCULATION(15), FRONT_DEFROST(16), REAR_DEFROST(17), MAX_DEFROTS(22) } public ClimateMode(State<ClimateControls> value) { super(value); } public ClimateMode(ClimateControls value) { this(new State<ClimateControls>(value)); } public ClimateMode(String value) { this(ClimateControls.valueOf(value.toUpperCase(Locale.US))); } @Override public String getGenericName() { return ID; } }
package com.openxc.measurements; import java.util.Locale; import com.openxc.units.State; /** * The ClimateMode measurement is used to start the AC/Heater/Fan */ public class ClimateMode extends BaseMeasurement<State<ClimateMode.ClimateControls>> { public final static String ID = "climate_mode"; public enum ClimateControls { OFF, PANEL_VENT, PANEL_FLOOR, FLOOR, FAN_SPEED_INCREMENT, FAN_SPEED_DECREMENT, AUTO, MAX_AC, RECIRCULATION, FRONT_DEFROST, REAR_DEFROST, MAX_DEFROST } public ClimateMode(State<ClimateControls> value) { super(value); } public ClimateMode(ClimateControls value) { this(new State<ClimateControls>(value)); } public ClimateMode(String value) { this(ClimateControls.valueOf(value.toUpperCase(Locale.US))); } @Override public String getGenericName() { return ID; } }
Remove int enum values, as they are unneeded
Remove int enum values, as they are unneeded
Java
bsd-3-clause
openxc/nonstandard-android-measurements,openxc/nonstandard-android-measurements
java
## Code Before: package com.openxc.measurements; import java.util.Locale; import com.openxc.units.State; /** * The ClimateMode measurement is used to start the AC/Heater/Fan */ public class ClimateMode extends BaseMeasurement<State<ClimateMode.ClimateControls>> { public final static String ID = "climate_mode"; public enum ClimateControls { UNUSED(0), PANEL_VENT(1), PANEL_FLOOR(2), FLOOR(3), FAN_SPEED_INCREMENT(11), FAN_SPEED_DECREMENT(12), AUTO(13), MAX_AC(14), RECIRCULATION(15), FRONT_DEFROST(16), REAR_DEFROST(17), MAX_DEFROTS(22) } public ClimateMode(State<ClimateControls> value) { super(value); } public ClimateMode(ClimateControls value) { this(new State<ClimateControls>(value)); } public ClimateMode(String value) { this(ClimateControls.valueOf(value.toUpperCase(Locale.US))); } @Override public String getGenericName() { return ID; } } ## Instruction: Remove int enum values, as they are unneeded ## Code After: package com.openxc.measurements; import java.util.Locale; import com.openxc.units.State; /** * The ClimateMode measurement is used to start the AC/Heater/Fan */ public class ClimateMode extends BaseMeasurement<State<ClimateMode.ClimateControls>> { public final static String ID = "climate_mode"; public enum ClimateControls { OFF, PANEL_VENT, PANEL_FLOOR, FLOOR, FAN_SPEED_INCREMENT, FAN_SPEED_DECREMENT, AUTO, MAX_AC, RECIRCULATION, FRONT_DEFROST, REAR_DEFROST, MAX_DEFROST } public ClimateMode(State<ClimateControls> value) { super(value); } public ClimateMode(ClimateControls value) { this(new State<ClimateControls>(value)); } public ClimateMode(String value) { this(ClimateControls.valueOf(value.toUpperCase(Locale.US))); } @Override public String getGenericName() { return ID; } }
# ... existing code ... public final static String ID = "climate_mode"; public enum ClimateControls { OFF, PANEL_VENT, PANEL_FLOOR, FLOOR, FAN_SPEED_INCREMENT, FAN_SPEED_DECREMENT, AUTO, MAX_AC, RECIRCULATION, FRONT_DEFROST, REAR_DEFROST, MAX_DEFROST } public ClimateMode(State<ClimateControls> value) { # ... modified code ... public ClimateMode(String value) { this(ClimateControls.valueOf(value.toUpperCase(Locale.US))); } @Override public String getGenericName() { return ID; # ... rest of the code ...
4a425b414d62d42d28ecd6eefd7bfaa84dd7b710
wow-attendance/src/main/java/ru/faulab/attendence/Runner.java
wow-attendance/src/main/java/ru/faulab/attendence/Runner.java
package ru.faulab.attendence; import com.google.inject.Guice; import com.google.inject.Injector; import ru.faulab.attendence.module.MainModule; import ru.faulab.attendence.ui.MainFrame; public class Runner { /* * 1. Статистика * */ public static void main(String[] args) throws Exception { String userHome = System.getProperty("user.home"); System.setProperty("derby.system.home", userHome); Injector injector = Guice.createInjector(new MainModule()); MainFrame mainFrame = injector.getInstance(MainFrame.class); mainFrame.init(); } }
package ru.faulab.attendence; import com.google.inject.Guice; import com.google.inject.Injector; import ru.faulab.attendence.module.MainModule; import ru.faulab.attendence.ui.MainFrame; import javax.swing.*; public class Runner { /* * 1. Статистика * */ public static void main(String[] args) throws Exception { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); String userHome = System.getProperty("user.home"); System.setProperty("derby.system.home", userHome); Injector injector = Guice.createInjector(new MainModule()); MainFrame mainFrame = injector.getInstance(MainFrame.class); mainFrame.init(); } }
Set UI as best on OS
Set UI as best on OS
Java
apache-2.0
anton-tregubov/wow-attendance
java
## Code Before: package ru.faulab.attendence; import com.google.inject.Guice; import com.google.inject.Injector; import ru.faulab.attendence.module.MainModule; import ru.faulab.attendence.ui.MainFrame; public class Runner { /* * 1. Статистика * */ public static void main(String[] args) throws Exception { String userHome = System.getProperty("user.home"); System.setProperty("derby.system.home", userHome); Injector injector = Guice.createInjector(new MainModule()); MainFrame mainFrame = injector.getInstance(MainFrame.class); mainFrame.init(); } } ## Instruction: Set UI as best on OS ## Code After: package ru.faulab.attendence; import com.google.inject.Guice; import com.google.inject.Injector; import ru.faulab.attendence.module.MainModule; import ru.faulab.attendence.ui.MainFrame; import javax.swing.*; public class Runner { /* * 1. Статистика * */ public static void main(String[] args) throws Exception { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); String userHome = System.getProperty("user.home"); System.setProperty("derby.system.home", userHome); Injector injector = Guice.createInjector(new MainModule()); MainFrame mainFrame = injector.getInstance(MainFrame.class); mainFrame.init(); } }
... import ru.faulab.attendence.module.MainModule; import ru.faulab.attendence.ui.MainFrame; import javax.swing.*; public class Runner { /* ... * 1. Статистика * */ public static void main(String[] args) throws Exception { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); String userHome = System.getProperty("user.home"); System.setProperty("derby.system.home", userHome); ...
e6d8789a1847ebe1525bb87c80b90d45db7cd29e
source/setup.py
source/setup.py
from distutils.core import setup from Cython.Build import cythonize ext_options = {"compiler_directives": {"profile": True}, "annotate": True} setup( name='Weighted-Levenshtein', version='', packages=[''], url='', license='', author='Team bluebird', author_email='', description='', requires=['numpy','weighted_levenshtein','pandas', 'fuzzy', 'ngram'], ext_modules = cythonize("*.pyx", **ext_options) )
from setuptools import setup from Cython.Build import cythonize ext_options = {"compiler_directives": {"profile": True}, "annotate": True} setup( name='Weighted-Levenshtein', version='', packages=[''], url='', license='', author='Team bluebird', author_email='', description='', install_requires=['numpy','weighted_levenshtein','pandas', 'fuzzy', 'ngram'], ext_modules = cythonize("*.pyx", **ext_options) )
Refactor rename to cost matrx
Refactor rename to cost matrx
Python
mit
elangovana/NLP-BackTransliteration-PersianNames
python
## Code Before: from distutils.core import setup from Cython.Build import cythonize ext_options = {"compiler_directives": {"profile": True}, "annotate": True} setup( name='Weighted-Levenshtein', version='', packages=[''], url='', license='', author='Team bluebird', author_email='', description='', requires=['numpy','weighted_levenshtein','pandas', 'fuzzy', 'ngram'], ext_modules = cythonize("*.pyx", **ext_options) ) ## Instruction: Refactor rename to cost matrx ## Code After: from setuptools import setup from Cython.Build import cythonize ext_options = {"compiler_directives": {"profile": True}, "annotate": True} setup( name='Weighted-Levenshtein', version='', packages=[''], url='', license='', author='Team bluebird', author_email='', description='', install_requires=['numpy','weighted_levenshtein','pandas', 'fuzzy', 'ngram'], ext_modules = cythonize("*.pyx", **ext_options) )
# ... existing code ... from setuptools import setup from Cython.Build import cythonize ext_options = {"compiler_directives": {"profile": True}, "annotate": True} # ... modified code ... license='', author='Team bluebird', author_email='', description='', install_requires=['numpy','weighted_levenshtein','pandas', 'fuzzy', 'ngram'], ext_modules = cythonize("*.pyx", **ext_options) ) # ... rest of the code ...
64f0171d781d03571a7ce725fff64e8162e9b55e
org.spoofax.jsglr2.integrationtest/src/test/java/org/spoofax/jsglr2/integrationtest/languages/StrategoTest.java
org.spoofax.jsglr2.integrationtest/src/test/java/org/spoofax/jsglr2/integrationtest/languages/StrategoTest.java
package org.spoofax.jsglr2.integrationtest.languages; import java.io.IOException; import java.util.stream.Stream; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.jsglr2.integrationtest.BaseTestWithParseTableFromTermWithJSGLR1; import org.spoofax.terms.ParseError; public class StrategoTest extends BaseTestWithParseTableFromTermWithJSGLR1 { public StrategoTest() throws Exception { setupParseTable("Stratego"); } @TestFactory public Stream<DynamicTest> testAmbByExpectedAST() throws ParseError, IOException { String sampleProgram = getFileAsString("Stratego/ambiguity-issue.str"); IStrategoTerm expectedAST = getFileAsAST("Stratego/ambiguity-issue.aterm"); return testSuccessByAstString(sampleProgram, expectedAST.toString()); } @TestFactory public Stream<DynamicTest> testIndentPadding() throws ParseError, IOException { String sampleProgram = getFileAsString("Stratego/test112.str"); IStrategoTerm expectedAST = getFileAsAST("Stratego/test112.aterm"); return testSuccessByAstString(sampleProgram, expectedAST.toString()); } }
package org.spoofax.jsglr2.integrationtest.languages; import java.io.IOException; import java.util.stream.Stream; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.jsglr2.integrationtest.BaseTestWithParseTableFromTermWithJSGLR1; import org.spoofax.terms.ParseError; public class StrategoTest extends BaseTestWithParseTableFromTermWithJSGLR1 { public StrategoTest() throws Exception { setupParseTable("Stratego"); } @TestFactory public Stream<DynamicTest> testAmbByExpectedAST() throws ParseError, IOException { String sampleProgram = getFileAsString("Stratego/ambiguity-issue.str"); IStrategoTerm expectedAST = getFileAsAST("Stratego/ambiguity-issue.aterm"); return testSuccessByAstString(sampleProgram, expectedAST.toString()); } @Disabled("The {indentpadding} attribute is not supported by JSGLR2 imploding due to concerns around incremental parsing") @TestFactory public Stream<DynamicTest> testIndentPadding() throws ParseError, IOException { String sampleProgram = getFileAsString("Stratego/test112.str"); IStrategoTerm expectedAST = getFileAsAST("Stratego/test112.aterm"); return testSuccessByAstString(sampleProgram, expectedAST.toString()); } }
Disable indentpadding test, note why
Disable indentpadding test, note why
Java
apache-2.0
metaborg/jsglr,metaborg/jsglr,metaborg/jsglr,metaborg/jsglr
java
## Code Before: package org.spoofax.jsglr2.integrationtest.languages; import java.io.IOException; import java.util.stream.Stream; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.jsglr2.integrationtest.BaseTestWithParseTableFromTermWithJSGLR1; import org.spoofax.terms.ParseError; public class StrategoTest extends BaseTestWithParseTableFromTermWithJSGLR1 { public StrategoTest() throws Exception { setupParseTable("Stratego"); } @TestFactory public Stream<DynamicTest> testAmbByExpectedAST() throws ParseError, IOException { String sampleProgram = getFileAsString("Stratego/ambiguity-issue.str"); IStrategoTerm expectedAST = getFileAsAST("Stratego/ambiguity-issue.aterm"); return testSuccessByAstString(sampleProgram, expectedAST.toString()); } @TestFactory public Stream<DynamicTest> testIndentPadding() throws ParseError, IOException { String sampleProgram = getFileAsString("Stratego/test112.str"); IStrategoTerm expectedAST = getFileAsAST("Stratego/test112.aterm"); return testSuccessByAstString(sampleProgram, expectedAST.toString()); } } ## Instruction: Disable indentpadding test, note why ## Code After: package org.spoofax.jsglr2.integrationtest.languages; import java.io.IOException; import java.util.stream.Stream; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.jsglr2.integrationtest.BaseTestWithParseTableFromTermWithJSGLR1; import org.spoofax.terms.ParseError; public class StrategoTest extends BaseTestWithParseTableFromTermWithJSGLR1 { public StrategoTest() throws Exception { setupParseTable("Stratego"); } @TestFactory public Stream<DynamicTest> testAmbByExpectedAST() throws ParseError, IOException { String sampleProgram = getFileAsString("Stratego/ambiguity-issue.str"); IStrategoTerm expectedAST = getFileAsAST("Stratego/ambiguity-issue.aterm"); return testSuccessByAstString(sampleProgram, expectedAST.toString()); } @Disabled("The {indentpadding} attribute is not supported by JSGLR2 imploding due to concerns around incremental parsing") @TestFactory public Stream<DynamicTest> testIndentPadding() throws ParseError, IOException { String sampleProgram = getFileAsString("Stratego/test112.str"); IStrategoTerm expectedAST = getFileAsAST("Stratego/test112.aterm"); return testSuccessByAstString(sampleProgram, expectedAST.toString()); } }
// ... existing code ... import java.io.IOException; import java.util.stream.Stream; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import org.spoofax.interpreter.terms.IStrategoTerm; // ... modified code ... return testSuccessByAstString(sampleProgram, expectedAST.toString()); } @Disabled("The {indentpadding} attribute is not supported by JSGLR2 imploding due to concerns around incremental parsing") @TestFactory public Stream<DynamicTest> testIndentPadding() throws ParseError, IOException { String sampleProgram = getFileAsString("Stratego/test112.str"); IStrategoTerm expectedAST = getFileAsAST("Stratego/test112.aterm"); // ... rest of the code ...
322997e229457bf43ee2281993ccdc30c8455244
tests/test_util.py
tests/test_util.py
from archivebox import util def test_download_url_downloads_content(): text = util.download_url("https://example.com") assert "Example Domain" in text
from archivebox import util def test_download_url_downloads_content(): text = util.download_url("http://localhost:8080/static/example.com.html") assert "Example Domain" in text
Refactor util tests to use local webserver
test: Refactor util tests to use local webserver
Python
mit
pirate/bookmark-archiver,pirate/bookmark-archiver,pirate/bookmark-archiver
python
## Code Before: from archivebox import util def test_download_url_downloads_content(): text = util.download_url("https://example.com") assert "Example Domain" in text ## Instruction: test: Refactor util tests to use local webserver ## Code After: from archivebox import util def test_download_url_downloads_content(): text = util.download_url("http://localhost:8080/static/example.com.html") assert "Example Domain" in text
... from archivebox import util def test_download_url_downloads_content(): text = util.download_url("http://localhost:8080/static/example.com.html") assert "Example Domain" in text ...
aece5e1eb7435d6ce0b5c667cb755aeb3c742084
app/src/main/java/de/bowstreet/testandroidapp/MainActivity.java
app/src/main/java/de/bowstreet/testandroidapp/MainActivity.java
package de.bowstreet.testandroidapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.microsoft.azure.mobile.MobileCenter; import com.microsoft.azure.mobile.analytics.Analytics; import com.microsoft.azure.mobile.crashes.Crashes; public class MainActivity extends AppCompatActivity { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MobileCenter.start(getApplication(), "2f85b1e5-f98d-4d7f-95f0-3509876fa2dd", Analytics.class, Crashes.class); mButton = (Button) findViewById(R.id.button); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { throw new RuntimeException("Test exception"); } }); } }
package de.bowstreet.testandroidapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.microsoft.azure.mobile.MobileCenter; import com.microsoft.azure.mobile.analytics.Analytics; import com.microsoft.azure.mobile.crashes.Crashes; public class MainActivity extends AppCompatActivity { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MobileCenter.start(getApplication(), "675da273-5716-4855-9dd0-431fe51ebfef", Analytics.class, Crashes.class); mButton = (Button) findViewById(R.id.button); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { throw new RuntimeException("Test exception"); } }); } }
Use app secret for prod app
Use app secret for prod app
Java
mit
ranterle/TestAndroidApp
java
## Code Before: package de.bowstreet.testandroidapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.microsoft.azure.mobile.MobileCenter; import com.microsoft.azure.mobile.analytics.Analytics; import com.microsoft.azure.mobile.crashes.Crashes; public class MainActivity extends AppCompatActivity { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MobileCenter.start(getApplication(), "2f85b1e5-f98d-4d7f-95f0-3509876fa2dd", Analytics.class, Crashes.class); mButton = (Button) findViewById(R.id.button); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { throw new RuntimeException("Test exception"); } }); } } ## Instruction: Use app secret for prod app ## Code After: package de.bowstreet.testandroidapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.microsoft.azure.mobile.MobileCenter; import com.microsoft.azure.mobile.analytics.Analytics; import com.microsoft.azure.mobile.crashes.Crashes; public class MainActivity extends AppCompatActivity { private Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MobileCenter.start(getApplication(), "675da273-5716-4855-9dd0-431fe51ebfef", Analytics.class, Crashes.class); mButton = (Button) findViewById(R.id.button); mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { throw new RuntimeException("Test exception"); } }); } }
// ... existing code ... super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MobileCenter.start(getApplication(), "675da273-5716-4855-9dd0-431fe51ebfef", Analytics.class, Crashes.class); mButton = (Button) findViewById(R.id.button); // ... rest of the code ...
aff8cebfd168493a4a9dff77cf9722507429d570
contrib/examples/actions/pythonactions/isprime.py
contrib/examples/actions/pythonactions/isprime.py
import math class PrimeChecker(object): def run(self, **kwargs): return self._is_prime(**kwargs) def _is_prime(self, value=0): if math.floor(value) != value: raise ValueError('%s should be an integer.' % value) if value < 2: return False for test in range(2, int(math.floor(math.sqrt(value)))+1): if value % test == 0: return False return True if __name__ == '__main__': checker = PrimeChecker() for i in range(0, 10): print '%s : %s' % (i, checker.run(**{'value': i}))
import math class PrimeChecker(object): def run(self, value=0): if math.floor(value) != value: raise ValueError('%s should be an integer.' % value) if value < 2: return False for test in range(2, int(math.floor(math.sqrt(value)))+1): if value % test == 0: return False return True if __name__ == '__main__': checker = PrimeChecker() for i in range(0, 10): print '%s : %s' % (i, checker.run(**{'value': i}))
Update pythonaction sample for simpler run.
Update pythonaction sample for simpler run.
Python
apache-2.0
peak6/st2,lakshmi-kannan/st2,pixelrebel/st2,StackStorm/st2,jtopjian/st2,pinterb/st2,Plexxi/st2,punalpatel/st2,armab/st2,grengojbo/st2,grengojbo/st2,punalpatel/st2,pixelrebel/st2,Itxaka/st2,lakshmi-kannan/st2,emedvedev/st2,lakshmi-kannan/st2,pixelrebel/st2,nzlosh/st2,peak6/st2,dennybaa/st2,pinterb/st2,Plexxi/st2,nzlosh/st2,Itxaka/st2,grengojbo/st2,alfasin/st2,nzlosh/st2,pinterb/st2,Plexxi/st2,jtopjian/st2,emedvedev/st2,StackStorm/st2,armab/st2,jtopjian/st2,StackStorm/st2,dennybaa/st2,alfasin/st2,emedvedev/st2,peak6/st2,punalpatel/st2,tonybaloney/st2,Plexxi/st2,tonybaloney/st2,alfasin/st2,nzlosh/st2,StackStorm/st2,tonybaloney/st2,dennybaa/st2,armab/st2,Itxaka/st2
python
## Code Before: import math class PrimeChecker(object): def run(self, **kwargs): return self._is_prime(**kwargs) def _is_prime(self, value=0): if math.floor(value) != value: raise ValueError('%s should be an integer.' % value) if value < 2: return False for test in range(2, int(math.floor(math.sqrt(value)))+1): if value % test == 0: return False return True if __name__ == '__main__': checker = PrimeChecker() for i in range(0, 10): print '%s : %s' % (i, checker.run(**{'value': i})) ## Instruction: Update pythonaction sample for simpler run. ## Code After: import math class PrimeChecker(object): def run(self, value=0): if math.floor(value) != value: raise ValueError('%s should be an integer.' % value) if value < 2: return False for test in range(2, int(math.floor(math.sqrt(value)))+1): if value % test == 0: return False return True if __name__ == '__main__': checker = PrimeChecker() for i in range(0, 10): print '%s : %s' % (i, checker.run(**{'value': i}))
# ... existing code ... class PrimeChecker(object): def run(self, value=0): if math.floor(value) != value: raise ValueError('%s should be an integer.' % value) if value < 2: # ... rest of the code ...
6e0f2880c80150a71cc719ff652f1bfbde08a1fa
setup.py
setup.py
from setuptools import setup try: import ez_setup ez_setup.use_setuptools() except ImportError: pass setup( name = "django-tsearch2", version = "0.2", packages = ['tsearch2', 'tsearch2.management', 'tsearch2.management.commands'], author = "Henrique Carvalho Alves", author_email = "[email protected]", description = "TSearch2 support for Django", url = "http://github.com/hcarvalhoalves/django-tsearch2", )
from setuptools import setup setup( name = "django-tsearch2", version = "0.2", packages = ['tsearch2', 'tsearch2.management', 'tsearch2.management.commands'], zip_safe = False, author = "Henrique Carvalho Alves", author_email = "[email protected]", description = "TSearch2 support for Django", url = "http://github.com/hcarvalhoalves/django-tsearch2", )
Mark as zip_safe = False
Mark as zip_safe = False
Python
bsd-3-clause
hcarvalhoalves/django-tsearch2
python
## Code Before: from setuptools import setup try: import ez_setup ez_setup.use_setuptools() except ImportError: pass setup( name = "django-tsearch2", version = "0.2", packages = ['tsearch2', 'tsearch2.management', 'tsearch2.management.commands'], author = "Henrique Carvalho Alves", author_email = "[email protected]", description = "TSearch2 support for Django", url = "http://github.com/hcarvalhoalves/django-tsearch2", ) ## Instruction: Mark as zip_safe = False ## Code After: from setuptools import setup setup( name = "django-tsearch2", version = "0.2", packages = ['tsearch2', 'tsearch2.management', 'tsearch2.management.commands'], zip_safe = False, author = "Henrique Carvalho Alves", author_email = "[email protected]", description = "TSearch2 support for Django", url = "http://github.com/hcarvalhoalves/django-tsearch2", )
# ... existing code ... from setuptools import setup setup( name = "django-tsearch2", version = "0.2", packages = ['tsearch2', 'tsearch2.management', 'tsearch2.management.commands'], zip_safe = False, author = "Henrique Carvalho Alves", author_email = "[email protected]", description = "TSearch2 support for Django", # ... rest of the code ...
28f9f7e85bb8353435db322138d1bd624934110f
london_commute_alert.py
london_commute_alert.py
import datetime import os import requests import sys def update(lines): url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status' resp = requests.get(url).json() result = [] for el in resp: value = el['lineStatuses'][0] state = value['statusSeverityDescription'] if el['id'] in lines and state != 'Good Service': result.append('{}: {} ({})'.format( el['id'].capitalize(), state, value['reason'])) return result def email(delays): os.chdir(sys.path[0]) with open('curl_raw_command.sh') as f: raw_command = f.read() # Running on PythonAnywhere - Monday to Sunday. Skip on the weekend if delays and datetime.date.today().isoweekday() in range(1, 6): os.system(raw_command.format(subject='Tube delays for commute', body='\n\n'.join(delays))) def main(): commute_lines = ['metropolitan', 'jubilee', 'central'] email(update(commute_lines)) if __name__ == '__main__': main()
import datetime import os import requests import sys def update(lines): url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status' resp = requests.get(url).json() result = [] for el in resp: value = el['lineStatuses'][0] state = value['statusSeverityDescription'] if el['id'] in lines and state != 'Good Service': result.append('{}: {} ({})'.format( el['id'].capitalize(), state, value['reason'])) return result def email(delays): # While tube is on shuttle service, don't email return os.chdir(sys.path[0]) with open('curl_raw_command.sh') as f: raw_command = f.read() # Running on PythonAnywhere - Monday to Sunday. Skip on the weekend if delays and datetime.date.today().isoweekday() in range(1, 6): os.system(raw_command.format(subject='Tube delays for commute', body='\n\n'.join(delays))) def main(): commute_lines = ['metropolitan', 'jubilee', 'central'] email(update(commute_lines)) if __name__ == '__main__': main()
Halt emails for time being
Halt emails for time being
Python
mit
noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit
python
## Code Before: import datetime import os import requests import sys def update(lines): url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status' resp = requests.get(url).json() result = [] for el in resp: value = el['lineStatuses'][0] state = value['statusSeverityDescription'] if el['id'] in lines and state != 'Good Service': result.append('{}: {} ({})'.format( el['id'].capitalize(), state, value['reason'])) return result def email(delays): os.chdir(sys.path[0]) with open('curl_raw_command.sh') as f: raw_command = f.read() # Running on PythonAnywhere - Monday to Sunday. Skip on the weekend if delays and datetime.date.today().isoweekday() in range(1, 6): os.system(raw_command.format(subject='Tube delays for commute', body='\n\n'.join(delays))) def main(): commute_lines = ['metropolitan', 'jubilee', 'central'] email(update(commute_lines)) if __name__ == '__main__': main() ## Instruction: Halt emails for time being ## Code After: import datetime import os import requests import sys def update(lines): url = 'http://api.tfl.gov.uk/Line/Mode/tube/Status' resp = requests.get(url).json() result = [] for el in resp: value = el['lineStatuses'][0] state = value['statusSeverityDescription'] if el['id'] in lines and state != 'Good Service': result.append('{}: {} ({})'.format( el['id'].capitalize(), state, value['reason'])) return result def email(delays): # While tube is on shuttle service, don't email return os.chdir(sys.path[0]) with open('curl_raw_command.sh') as f: raw_command = f.read() # Running on PythonAnywhere - Monday to Sunday. Skip on the weekend if delays and datetime.date.today().isoweekday() in range(1, 6): os.system(raw_command.format(subject='Tube delays for commute', body='\n\n'.join(delays))) def main(): commute_lines = ['metropolitan', 'jubilee', 'central'] email(update(commute_lines)) if __name__ == '__main__': main()
... def email(delays): # While tube is on shuttle service, don't email return os.chdir(sys.path[0]) with open('curl_raw_command.sh') as f: raw_command = f.read() ...
539fae27f9911b9ad13edc5244ffbd12b1509006
utils.py
utils.py
__all__ = ['mstack', 'wget'] def mstack(vs, fs): import chumpy as ch import numpy as np lengths = [v.shape[0] for v in vs] f = np.vstack([fs[i]+np.sum(lengths[:i]).astype(np.uint32) for i in range(len(fs))]) v = ch.vstack(vs) return v, f def wget(url, dest_fname=None): import urllib.request, urllib.error, urllib.parse from os.path import split, join curdir = split(__file__)[0] print(url) if dest_fname is None: dest_fname = join(curdir, split(url)[1]) try: contents = urllib.request.urlopen(url).read() except: raise Exception('Unable to get url: %s' % (url,)) open(dest_fname, 'w').write(contents)
__all__ = ['mstack', 'wget'] def mstack(vs, fs): import chumpy as ch import numpy as np lengths = [v.shape[0] for v in vs] f = np.vstack([fs[i]+np.sum(lengths[:i]).astype(np.uint32) for i in range(len(fs))]) v = ch.vstack(vs) return v, f def wget(url, dest_fname=None): try: #python3 from urllib.request import urlopen except: #python2 from urllib2 import urlopen from os.path import split, join curdir = split(__file__)[0] print(url) if dest_fname is None: dest_fname = join(curdir, split(url)[1]) try: contents = urlopen(url).read() except: raise Exception('Unable to get url: %s' % (url,)) open(dest_fname, 'w').write(contents)
Fix for python2/3 compatibility issue with urllib
Fix for python2/3 compatibility issue with urllib
Python
mit
mattloper/opendr,mattloper/opendr
python
## Code Before: __all__ = ['mstack', 'wget'] def mstack(vs, fs): import chumpy as ch import numpy as np lengths = [v.shape[0] for v in vs] f = np.vstack([fs[i]+np.sum(lengths[:i]).astype(np.uint32) for i in range(len(fs))]) v = ch.vstack(vs) return v, f def wget(url, dest_fname=None): import urllib.request, urllib.error, urllib.parse from os.path import split, join curdir = split(__file__)[0] print(url) if dest_fname is None: dest_fname = join(curdir, split(url)[1]) try: contents = urllib.request.urlopen(url).read() except: raise Exception('Unable to get url: %s' % (url,)) open(dest_fname, 'w').write(contents) ## Instruction: Fix for python2/3 compatibility issue with urllib ## Code After: __all__ = ['mstack', 'wget'] def mstack(vs, fs): import chumpy as ch import numpy as np lengths = [v.shape[0] for v in vs] f = np.vstack([fs[i]+np.sum(lengths[:i]).astype(np.uint32) for i in range(len(fs))]) v = ch.vstack(vs) return v, f def wget(url, dest_fname=None): try: #python3 from urllib.request import urlopen except: #python2 from urllib2 import urlopen from os.path import split, join curdir = split(__file__)[0] print(url) if dest_fname is None: dest_fname = join(curdir, split(url)[1]) try: contents = urlopen(url).read() except: raise Exception('Unable to get url: %s' % (url,)) open(dest_fname, 'w').write(contents)
// ... existing code ... def wget(url, dest_fname=None): try: #python3 from urllib.request import urlopen except: #python2 from urllib2 import urlopen from os.path import split, join curdir = split(__file__)[0] // ... modified code ... dest_fname = join(curdir, split(url)[1]) try: contents = urlopen(url).read() except: raise Exception('Unable to get url: %s' % (url,)) open(dest_fname, 'w').write(contents) // ... rest of the code ...
a68494b48bbbdeb8293a0e5c521a501bf3eb3750
OpenMRS-iOS/MRSVisit.h
OpenMRS-iOS/MRSVisit.h
// // MRSVisit.h // OpenMRS-iOS // // Created by Parker Erway on 12/2/14. // Copyright (c) 2014 Erway Software. All rights reserved. // #import <Foundation/Foundation.h> @interface MRSVisit : NSObject @property (nonatomic, strong) NSString *displayName; @property (nonatomic, strong) NSString *UUID; @property (nonatomic) BOOL active; @end
// // MRSVisit.h // OpenMRS-iOS // // Created by Parker Erway on 12/2/14. // Copyright (c) 2014 Erway Software. All rights reserved. // #import <Foundation/Foundation.h> #import "MRSLocation.h" @class MRSVisitType; @interface MRSVisit : NSObject @property (nonatomic, strong) NSString *displayName; @property (nonatomic, strong) NSString *UUID; @property (nonatomic, strong) NSString *startDateTime; @property (nonatomic, strong) MRSVisitType *visitType; @property (nonatomic, strong) MRSLocation *location; @property (nonatomic) BOOL active; @end
Add new attributes to Visit class
Add new attributes to Visit class
C
mpl-2.0
yousefhamza/openmrs-contrib-ios-client,Undo1/openmrs-contrib-ios-client,yousefhamza/openmrs-contrib-ios-client,Undo1/openmrs-contrib-ios-client
c
## Code Before: // // MRSVisit.h // OpenMRS-iOS // // Created by Parker Erway on 12/2/14. // Copyright (c) 2014 Erway Software. All rights reserved. // #import <Foundation/Foundation.h> @interface MRSVisit : NSObject @property (nonatomic, strong) NSString *displayName; @property (nonatomic, strong) NSString *UUID; @property (nonatomic) BOOL active; @end ## Instruction: Add new attributes to Visit class ## Code After: // // MRSVisit.h // OpenMRS-iOS // // Created by Parker Erway on 12/2/14. // Copyright (c) 2014 Erway Software. All rights reserved. // #import <Foundation/Foundation.h> #import "MRSLocation.h" @class MRSVisitType; @interface MRSVisit : NSObject @property (nonatomic, strong) NSString *displayName; @property (nonatomic, strong) NSString *UUID; @property (nonatomic, strong) NSString *startDateTime; @property (nonatomic, strong) MRSVisitType *visitType; @property (nonatomic, strong) MRSLocation *location; @property (nonatomic) BOOL active; @end
# ... existing code ... // #import <Foundation/Foundation.h> #import "MRSLocation.h" @class MRSVisitType; @interface MRSVisit : NSObject @property (nonatomic, strong) NSString *displayName; @property (nonatomic, strong) NSString *UUID; @property (nonatomic, strong) NSString *startDateTime; @property (nonatomic, strong) MRSVisitType *visitType; @property (nonatomic, strong) MRSLocation *location; @property (nonatomic) BOOL active; @end # ... rest of the code ...
c2dbfc7f18dc44747fbb8b14e212cbb4151e8f85
analyze.py
analyze.py
import fore.database analysis = fore.database.get_analysis(2) import pickle, base64 analysis = pickle.loads(base64.b64decode(analysis)) print(analysis)
import sys import fore.database if len(sys.argv) > 1: track_no = sys.argv[1] else: track_no = 2 analysis = fore.database.get_analysis(track_no) import pickle, base64 analysis = pickle.loads(base64.b64decode(analysis)) print(analysis)
Send track number as CLI argument.
Send track number as CLI argument.
Python
artistic-2.0
MikeiLL/appension,Rosuav/appension,MikeiLL/appension,MikeiLL/appension,Rosuav/appension,Rosuav/appension,MikeiLL/appension,Rosuav/appension
python
## Code Before: import fore.database analysis = fore.database.get_analysis(2) import pickle, base64 analysis = pickle.loads(base64.b64decode(analysis)) print(analysis) ## Instruction: Send track number as CLI argument. ## Code After: import sys import fore.database if len(sys.argv) > 1: track_no = sys.argv[1] else: track_no = 2 analysis = fore.database.get_analysis(track_no) import pickle, base64 analysis = pickle.loads(base64.b64decode(analysis)) print(analysis)
... import sys import fore.database if len(sys.argv) > 1: track_no = sys.argv[1] else: track_no = 2 analysis = fore.database.get_analysis(track_no) import pickle, base64 analysis = pickle.loads(base64.b64decode(analysis)) print(analysis) ...
7891cf254bb98b65503675a20ed6b013385328cf
setup.py
setup.py
import setuptools def package_data_dirs(source, sub_folders): import os dirs = [] for d in sub_folders: for dirname, _, files in os.walk(os.path.join(source, d)): dirname = os.path.relpath(dirname, source) for f in files: dirs.append(os.path.join(dirname, f)) return dirs def params(): name = "OctoPrint-Netconnectd" version = "0.1" description = "Client for netconnectd that allows configuration of netconnectd through OctoPrint's settings dialog. It's only available for Linux right now." author = "Gina Häußge" author_email = "[email protected]" url = "http://octoprint.org" license = "AGPLv3" packages = ["octoprint_netconnectd"] package_data = {"octoprint": package_data_dirs('octoprint_netconnectd', ['static', 'templates'])} include_package_data = True zip_safe = False install_requires = open("requirements.txt").read().split("\n") entry_points = { "octoprint.plugin": [ "netconnectd = octoprint_netconnectd" ] } return locals() setuptools.setup(**params())
import setuptools def package_data_dirs(source, sub_folders): import os dirs = [] for d in sub_folders: for dirname, _, files in os.walk(os.path.join(source, d)): dirname = os.path.relpath(dirname, source) for f in files: dirs.append(os.path.join(dirname, f)) return dirs def params(): name = "OctoPrint-Netconnectd" version = "0.1" description = "Client for netconnectd that allows configuration of netconnectd through OctoPrint's settings dialog. It's only available for Linux right now." author = "Gina Häußge" author_email = "[email protected]" url = "http://octoprint.org" license = "AGPLv3" packages = ["octoprint_netconnectd"] package_data = {"octoprint_netconnectd": package_data_dirs('octoprint_netconnectd', ['static', 'templates'])} include_package_data = True zip_safe = False install_requires = open("requirements.txt").read().split("\n") entry_points = { "octoprint.plugin": [ "netconnectd = octoprint_netconnectd" ] } return locals() setuptools.setup(**params())
Copy paste error leading to static and template folders not being properly installed along side the package
Copy paste error leading to static and template folders not being properly installed along side the package
Python
agpl-3.0
OctoPrint/OctoPrint-Netconnectd,mrbeam/OctoPrint-Netconnectd,mrbeam/OctoPrint-Netconnectd,OctoPrint/OctoPrint-Netconnectd,mrbeam/OctoPrint-Netconnectd
python
## Code Before: import setuptools def package_data_dirs(source, sub_folders): import os dirs = [] for d in sub_folders: for dirname, _, files in os.walk(os.path.join(source, d)): dirname = os.path.relpath(dirname, source) for f in files: dirs.append(os.path.join(dirname, f)) return dirs def params(): name = "OctoPrint-Netconnectd" version = "0.1" description = "Client for netconnectd that allows configuration of netconnectd through OctoPrint's settings dialog. It's only available for Linux right now." author = "Gina Häußge" author_email = "[email protected]" url = "http://octoprint.org" license = "AGPLv3" packages = ["octoprint_netconnectd"] package_data = {"octoprint": package_data_dirs('octoprint_netconnectd', ['static', 'templates'])} include_package_data = True zip_safe = False install_requires = open("requirements.txt").read().split("\n") entry_points = { "octoprint.plugin": [ "netconnectd = octoprint_netconnectd" ] } return locals() setuptools.setup(**params()) ## Instruction: Copy paste error leading to static and template folders not being properly installed along side the package ## Code After: import setuptools def package_data_dirs(source, sub_folders): import os dirs = [] for d in sub_folders: for dirname, _, files in os.walk(os.path.join(source, d)): dirname = os.path.relpath(dirname, source) for f in files: dirs.append(os.path.join(dirname, f)) return dirs def params(): name = "OctoPrint-Netconnectd" version = "0.1" description = "Client for netconnectd that allows configuration of netconnectd through OctoPrint's settings dialog. It's only available for Linux right now." author = "Gina Häußge" author_email = "[email protected]" url = "http://octoprint.org" license = "AGPLv3" packages = ["octoprint_netconnectd"] package_data = {"octoprint_netconnectd": package_data_dirs('octoprint_netconnectd', ['static', 'templates'])} include_package_data = True zip_safe = False install_requires = open("requirements.txt").read().split("\n") entry_points = { "octoprint.plugin": [ "netconnectd = octoprint_netconnectd" ] } return locals() setuptools.setup(**params())
// ... existing code ... license = "AGPLv3" packages = ["octoprint_netconnectd"] package_data = {"octoprint_netconnectd": package_data_dirs('octoprint_netconnectd', ['static', 'templates'])} include_package_data = True zip_safe = False // ... rest of the code ...
69ec6586cd9ce9c8bda5b9c2f6f76ecd4a43baca
chessfellows/chess/models.py
chessfellows/chess/models.py
from django.db import models from django.contrib.auth.models import User class Match(models.Model): white = models.ForeignKey(User, related_name="White") black = models.ForeignKey(User, related_name="Black") moves = models.TextField() class Player(models.Model): user = models.OneToOneField(User) rating = models.PositiveSmallIntegerField(default=1200) wins = models.PositiveIntegerField(default=0) losses = models.PositiveIntegerField(default=0) draws = models.PositiveIntegerField(default=0) matches = models.ManyToManyField(Match, related_name="Player") opponent_rating = models.PositiveIntegerField(default=0) def calc_rating(self): numerator = (self.opponent_rating + 400 * (self.wins - self.losses)) denom = self.wins + self.losses + self.draws return numerator // denom def save(self, *args, **kwargs): self.rating = self.calc_rating() super(Player, self).save(*args, **kwargs)
import os from django.db import models from django.contrib.auth.models import User def get_file_owner_username(instance, filename): parts = [instance.user.username] parts.append(os.path.basename(filename)) path = u"/".join(parts) return path class Match(models.Model): white = models.ForeignKey(User, related_name="White") black = models.ForeignKey(User, related_name="Black") moves = models.TextField() date_played = models.DateTimeField(auto_now=True) class Player(models.Model): user = models.OneToOneField(User) rating = models.PositiveSmallIntegerField(default=1200) wins = models.PositiveIntegerField(default=0) losses = models.PositiveIntegerField(default=0) draws = models.PositiveIntegerField(default=0) matches = models.ManyToManyField(Match, related_name="Player") all_opponents_rating = models.PositiveIntegerField(default=0) image_upload_folder = 'photos/' photo = models.ImageField(upload_to=image_upload_folder, height_field='height', width_field='width') def update_all_opponents_rating(self, other): self.all_opponents_rating += other.rating def calc_rating(self): numerator = (self.opponents_rating + 400 * (self.wins - self.losses)) denom = self.wins + self.losses + self.draws return numerator // denom def save(self, *args, **kwargs): opponent = Match.objects.filter() self.update_all_opponents_rating(opponent) self.rating = self.calc_rating() super(Player, self).save(*args, **kwargs)
Add get_file_owner_username() to return a file path for a player's profile picture; add photo attribute to Player() model
Add get_file_owner_username() to return a file path for a player's profile picture; add photo attribute to Player() model
Python
mit
EyuelAbebe/gamer,EyuelAbebe/gamer
python
## Code Before: from django.db import models from django.contrib.auth.models import User class Match(models.Model): white = models.ForeignKey(User, related_name="White") black = models.ForeignKey(User, related_name="Black") moves = models.TextField() class Player(models.Model): user = models.OneToOneField(User) rating = models.PositiveSmallIntegerField(default=1200) wins = models.PositiveIntegerField(default=0) losses = models.PositiveIntegerField(default=0) draws = models.PositiveIntegerField(default=0) matches = models.ManyToManyField(Match, related_name="Player") opponent_rating = models.PositiveIntegerField(default=0) def calc_rating(self): numerator = (self.opponent_rating + 400 * (self.wins - self.losses)) denom = self.wins + self.losses + self.draws return numerator // denom def save(self, *args, **kwargs): self.rating = self.calc_rating() super(Player, self).save(*args, **kwargs) ## Instruction: Add get_file_owner_username() to return a file path for a player's profile picture; add photo attribute to Player() model ## Code After: import os from django.db import models from django.contrib.auth.models import User def get_file_owner_username(instance, filename): parts = [instance.user.username] parts.append(os.path.basename(filename)) path = u"/".join(parts) return path class Match(models.Model): white = models.ForeignKey(User, related_name="White") black = models.ForeignKey(User, related_name="Black") moves = models.TextField() date_played = models.DateTimeField(auto_now=True) class Player(models.Model): user = models.OneToOneField(User) rating = models.PositiveSmallIntegerField(default=1200) wins = models.PositiveIntegerField(default=0) losses = models.PositiveIntegerField(default=0) draws = models.PositiveIntegerField(default=0) matches = models.ManyToManyField(Match, related_name="Player") all_opponents_rating = models.PositiveIntegerField(default=0) image_upload_folder = 'photos/' photo = models.ImageField(upload_to=image_upload_folder, height_field='height', width_field='width') def update_all_opponents_rating(self, other): self.all_opponents_rating += other.rating def calc_rating(self): numerator = (self.opponents_rating + 400 * (self.wins - self.losses)) denom = self.wins + self.losses + self.draws return numerator // denom def save(self, *args, **kwargs): opponent = Match.objects.filter() self.update_all_opponents_rating(opponent) self.rating = self.calc_rating() super(Player, self).save(*args, **kwargs)
// ... existing code ... import os from django.db import models from django.contrib.auth.models import User def get_file_owner_username(instance, filename): parts = [instance.user.username] parts.append(os.path.basename(filename)) path = u"/".join(parts) return path class Match(models.Model): // ... modified code ... white = models.ForeignKey(User, related_name="White") black = models.ForeignKey(User, related_name="Black") moves = models.TextField() date_played = models.DateTimeField(auto_now=True) class Player(models.Model): ... losses = models.PositiveIntegerField(default=0) draws = models.PositiveIntegerField(default=0) matches = models.ManyToManyField(Match, related_name="Player") all_opponents_rating = models.PositiveIntegerField(default=0) image_upload_folder = 'photos/' photo = models.ImageField(upload_to=image_upload_folder, height_field='height', width_field='width') def update_all_opponents_rating(self, other): self.all_opponents_rating += other.rating def calc_rating(self): numerator = (self.opponents_rating + 400 * (self.wins - self.losses)) denom = self.wins + self.losses + self.draws return numerator // denom def save(self, *args, **kwargs): opponent = Match.objects.filter() self.update_all_opponents_rating(opponent) self.rating = self.calc_rating() super(Player, self).save(*args, **kwargs) // ... rest of the code ...
f259830daf79f1e7c02a2fb61af6029ad0ebc8be
app/controllers/PlatformController.java
app/controllers/PlatformController.java
package controllers; import models.Game; import play.mvc.Controller; import play.mvc.Result; import views.html.platform_read; import java.util.List; public class PlatformController extends Controller { public static Result read(final String platformName) { if (platformName == null) { return notFound(); } List<Game> games = getGamesByPlatform(platformName); return ok(platform_read.render(platformName, games)); } public static List<Game> getGamesByPlatform(final String platformName) { return Game.finder.where().ieq("platforms.name", platformName).findList(); } }
package controllers; import models.Game; import play.mvc.Controller; import play.mvc.Result; import views.html.platform_read; import java.util.List; public class PlatformController extends Controller { public static Result read(final String platformName) { if (platformName == null) { return notFound(); } List<Game> games = getGamesByPlatform(platformName); return ok(platform_read.render(platformName, games)); } public static List<Game> getGamesByPlatform(final String platformName) { return Game.finder.where().ieq("platforms.name", platformName).order("title").findList(); } }
Order one cc by game title
Order one cc by game title
Java
apache-2.0
jsmadja/shmuphiscores,jsmadja/shmuphiscores,jsmadja/shmuphiscores
java
## Code Before: package controllers; import models.Game; import play.mvc.Controller; import play.mvc.Result; import views.html.platform_read; import java.util.List; public class PlatformController extends Controller { public static Result read(final String platformName) { if (platformName == null) { return notFound(); } List<Game> games = getGamesByPlatform(platformName); return ok(platform_read.render(platformName, games)); } public static List<Game> getGamesByPlatform(final String platformName) { return Game.finder.where().ieq("platforms.name", platformName).findList(); } } ## Instruction: Order one cc by game title ## Code After: package controllers; import models.Game; import play.mvc.Controller; import play.mvc.Result; import views.html.platform_read; import java.util.List; public class PlatformController extends Controller { public static Result read(final String platformName) { if (platformName == null) { return notFound(); } List<Game> games = getGamesByPlatform(platformName); return ok(platform_read.render(platformName, games)); } public static List<Game> getGamesByPlatform(final String platformName) { return Game.finder.where().ieq("platforms.name", platformName).order("title").findList(); } }
// ... existing code ... } public static List<Game> getGamesByPlatform(final String platformName) { return Game.finder.where().ieq("platforms.name", platformName).order("title").findList(); } } // ... rest of the code ...
33ceea40e41d9f568b11e30779b8b7c16ba8f5b8
bench/split-file.py
bench/split-file.py
import sys prefix = sys.argv[1] filename = sys.argv[2] f = open(filename) sf = None for line in f: if line.startswith('Processing database:'): if sf: sf.close() line2 = line.split(':')[1] # Check if entry is compressed and if has to be processed line2 = line2[:line2.rfind('.')] params = line2.split('-') optlevel = 0 complib = None for param in params: if param[0] == 'O' and param[1].isdigit(): optlevel = int(param[1]) elif param[:-1] in ('zlib', 'lzo'): complib = param if complib: sfilename = "%s-O%s-%s.out" % (prefix, optlevel, complib) else: sfilename = "%s-O%s.out" % (prefix, optlevel,) sf = file(sfilename, 'a') sf.write(line) f.close()
import sys prefix = sys.argv[1] filename = sys.argv[2] f = open(filename) sf = None for line in f: if line.startswith('Processing database:'): if sf: sf.close() line2 = line.split(':')[1] # Check if entry is compressed and if has to be processed line2 = line2[:line2.rfind('.')] params = line2.split('-') optlevel = 0 complib = None for param in params: if param[0] == 'O' and param[1].isdigit(): optlevel = int(param[1]) elif param[:-1] in ('zlib', 'lzo'): complib = param if 'PyTables' in prefix: if complib: sfilename = "%s-O%s-%s.out" % (prefix, optlevel, complib) else: sfilename = "%s-O%s.out" % (prefix, optlevel,) else: sfilename = "%s.out" % (prefix,) sf = file(sfilename, 'a') if sf: sf.write(line) f.close()
Support for splitting outputs for PyTables and Postgres indexing benchmarks all in one.
Support for splitting outputs for PyTables and Postgres indexing benchmarks all in one. git-svn-id: 92c705c98a17f0f7623a131b3c42ed50fcde59b4@2885 1b98710c-d8ec-0310-ae81-f5f2bcd8cb94
Python
bsd-3-clause
jennolsen84/PyTables,rabernat/PyTables,avalentino/PyTables,jack-pappas/PyTables,rdhyee/PyTables,gdementen/PyTables,joonro/PyTables,PyTables/PyTables,mohamed-ali/PyTables,andreabedini/PyTables,tp199911/PyTables,jennolsen84/PyTables,tp199911/PyTables,dotsdl/PyTables,cpcloud/PyTables,tp199911/PyTables,FrancescAlted/PyTables,PyTables/PyTables,dotsdl/PyTables,cpcloud/PyTables,rabernat/PyTables,rabernat/PyTables,andreabedini/PyTables,mohamed-ali/PyTables,gdementen/PyTables,jack-pappas/PyTables,jack-pappas/PyTables,rdhyee/PyTables,mohamed-ali/PyTables,FrancescAlted/PyTables,rdhyee/PyTables,PyTables/PyTables,cpcloud/PyTables,avalentino/PyTables,avalentino/PyTables,rdhyee/PyTables,gdementen/PyTables,rabernat/PyTables,jennolsen84/PyTables,jennolsen84/PyTables,tp199911/PyTables,andreabedini/PyTables,dotsdl/PyTables,mohamed-ali/PyTables,joonro/PyTables,joonro/PyTables,andreabedini/PyTables,jack-pappas/PyTables,dotsdl/PyTables,jack-pappas/PyTables,gdementen/PyTables,cpcloud/PyTables,FrancescAlted/PyTables,joonro/PyTables
python
## Code Before: import sys prefix = sys.argv[1] filename = sys.argv[2] f = open(filename) sf = None for line in f: if line.startswith('Processing database:'): if sf: sf.close() line2 = line.split(':')[1] # Check if entry is compressed and if has to be processed line2 = line2[:line2.rfind('.')] params = line2.split('-') optlevel = 0 complib = None for param in params: if param[0] == 'O' and param[1].isdigit(): optlevel = int(param[1]) elif param[:-1] in ('zlib', 'lzo'): complib = param if complib: sfilename = "%s-O%s-%s.out" % (prefix, optlevel, complib) else: sfilename = "%s-O%s.out" % (prefix, optlevel,) sf = file(sfilename, 'a') sf.write(line) f.close() ## Instruction: Support for splitting outputs for PyTables and Postgres indexing benchmarks all in one. git-svn-id: 92c705c98a17f0f7623a131b3c42ed50fcde59b4@2885 1b98710c-d8ec-0310-ae81-f5f2bcd8cb94 ## Code After: import sys prefix = sys.argv[1] filename = sys.argv[2] f = open(filename) sf = None for line in f: if line.startswith('Processing database:'): if sf: sf.close() line2 = line.split(':')[1] # Check if entry is compressed and if has to be processed line2 = line2[:line2.rfind('.')] params = line2.split('-') optlevel = 0 complib = None for param in params: if param[0] == 'O' and param[1].isdigit(): optlevel = int(param[1]) elif param[:-1] in ('zlib', 'lzo'): complib = param if 'PyTables' in prefix: if complib: sfilename = "%s-O%s-%s.out" % (prefix, optlevel, complib) else: sfilename = "%s-O%s.out" % (prefix, optlevel,) else: sfilename = "%s.out" % (prefix,) sf = file(sfilename, 'a') if sf: sf.write(line) f.close()
// ... existing code ... optlevel = int(param[1]) elif param[:-1] in ('zlib', 'lzo'): complib = param if 'PyTables' in prefix: if complib: sfilename = "%s-O%s-%s.out" % (prefix, optlevel, complib) else: sfilename = "%s-O%s.out" % (prefix, optlevel,) else: sfilename = "%s.out" % (prefix,) sf = file(sfilename, 'a') if sf: sf.write(line) f.close() // ... rest of the code ...
7efce87f280e015217514c73097a080a47a56f05
src/wclock_test.c
src/wclock_test.c
static unsigned int sleep(unsigned int x) { Sleep(x * 1000); return 0; } #else # include <unistd.h> #endif int main(void) { double res, t1, t2; wclock clock; if (wclock_init(&clock)) { abort(); } res = wclock_get_res(&clock); printf("%.17g\n", res); assert(res > 0); assert(res < 2e-3); /* presumably the clock has at least ms precision! */ t1 = wclock_get(&clock); printf("%.17g\n", t1); sleep(1); t2 = wclock_get(&clock); printf("%.17g\n", t2); printf("%.17g\n", t2 - t1); assert(fabs(t2 - t1 - 1.) < 1e-1); return 0; }
static unsigned int sleep(unsigned int x) { Sleep(x * 1000); return 0; } #else # include <unistd.h> #endif int main(void) { double res, t1, t2; wclock clock; if (wclock_init(&clock)) { abort(); } res = wclock_get_res(&clock); printf("%.17g\n", res); assert(res > 0); assert(res < 2e-3); /* presumably the clock has at least ms precision! */ t1 = wclock_get(&clock); printf("%.17g\n", t1); sleep(1); t2 = wclock_get(&clock); printf("%.17g\n", t2); printf("%.17g\n", t2 - t1); assert(t2 - t1 >= 0.9 && t2 - t1 < 1.4); return 0; }
Increase time tolerance to reduce flakiness on slow systems
Increase time tolerance to reduce flakiness on slow systems
C
mit
Rufflewind/calico,Rufflewind/calico,Rufflewind/calico
c
## Code Before: static unsigned int sleep(unsigned int x) { Sleep(x * 1000); return 0; } #else # include <unistd.h> #endif int main(void) { double res, t1, t2; wclock clock; if (wclock_init(&clock)) { abort(); } res = wclock_get_res(&clock); printf("%.17g\n", res); assert(res > 0); assert(res < 2e-3); /* presumably the clock has at least ms precision! */ t1 = wclock_get(&clock); printf("%.17g\n", t1); sleep(1); t2 = wclock_get(&clock); printf("%.17g\n", t2); printf("%.17g\n", t2 - t1); assert(fabs(t2 - t1 - 1.) < 1e-1); return 0; } ## Instruction: Increase time tolerance to reduce flakiness on slow systems ## Code After: static unsigned int sleep(unsigned int x) { Sleep(x * 1000); return 0; } #else # include <unistd.h> #endif int main(void) { double res, t1, t2; wclock clock; if (wclock_init(&clock)) { abort(); } res = wclock_get_res(&clock); printf("%.17g\n", res); assert(res > 0); assert(res < 2e-3); /* presumably the clock has at least ms precision! */ t1 = wclock_get(&clock); printf("%.17g\n", t1); sleep(1); t2 = wclock_get(&clock); printf("%.17g\n", t2); printf("%.17g\n", t2 - t1); assert(t2 - t1 >= 0.9 && t2 - t1 < 1.4); return 0; }
# ... existing code ... t2 = wclock_get(&clock); printf("%.17g\n", t2); printf("%.17g\n", t2 - t1); assert(t2 - t1 >= 0.9 && t2 - t1 < 1.4); return 0; } # ... rest of the code ...
462656f9653ae43ea69080414735927b18e0debf
stats/random_walk.py
stats/random_walk.py
import neo4j import random from logbook import Logger log = Logger('trinity.topics') DEFAULT_DEPTH = 5 NUM_WALKS = 100 # Passed sorted list (desc order), return top nodes TO_RETURN = lambda x: x[:10] random.seed() def random_walk(graph, node, depth=DEFAULT_DEPTH): # Pick random neighbor neighbors = {} i = 0 for r in node.relationships().outgoing: #TODO replace with i + r['count'] neighbors[(i, i + 1)] = r.getOtherNode(node) i += 1 choice = random.range(i) for x,y in neighbors: if x <= i and i < y: return [node].extend(random_walk(graph, neighbors[(x,y)], depth-1)) def run(graph, index, node): nodes = {} for i in range(NUM_WALKS): with graph.transaction: walked_nodes = random_walk(graph, node) # Loop through nodes (that aren't the start node), count for n in filter(lambda m: m.id != node.id, walked_nodes): if nodes.has_key(n): nodes[n]++ else nodes[n] = 1 return TO_RETURN(sorted(nodes, key=nodes.__getitem__))
import neo4j import random DEFAULT_DEPTH = 5 NUM_WALKS = 100 # Passed sorted list (desc order), return top nodes TO_RETURN = lambda x: x[:10] random.seed() def random_walk(graph, node, depth=DEFAULT_DEPTH): if depth == 0: return [node] # Pick random neighbor neighbors = {} i = 0 for r in node.relationships().outgoing: neighbors[(i, i + int(r['count']))] = r.getOtherNode(node) i += int(r['count']) if i == 0: # No neighbors return [node] r = random.randrange(i) for x,y in neighbors: if x <= r and r < y: return [node] + random_walk(graph, neighbors[(x,y)], depth-1) def run(graph, index, node): nodes = {} for i in range(NUM_WALKS): with graph.transaction: walked_nodes = random_walk(graph, node) # Loop through nodes (that aren't the start node), count for n in filter(lambda m: m.id != node.id, walked_nodes): if nodes.has_key(n): nodes[n] += 1 else: nodes[n] = 1 return TO_RETURN([{'name': n['name'], 'count': nodes[n]} for n in sorted(nodes, key=nodes.__getitem__)])
Modify random walk so that it works.
Modify random walk so that it works.
Python
mit
peplin/trinity
python
## Code Before: import neo4j import random from logbook import Logger log = Logger('trinity.topics') DEFAULT_DEPTH = 5 NUM_WALKS = 100 # Passed sorted list (desc order), return top nodes TO_RETURN = lambda x: x[:10] random.seed() def random_walk(graph, node, depth=DEFAULT_DEPTH): # Pick random neighbor neighbors = {} i = 0 for r in node.relationships().outgoing: #TODO replace with i + r['count'] neighbors[(i, i + 1)] = r.getOtherNode(node) i += 1 choice = random.range(i) for x,y in neighbors: if x <= i and i < y: return [node].extend(random_walk(graph, neighbors[(x,y)], depth-1)) def run(graph, index, node): nodes = {} for i in range(NUM_WALKS): with graph.transaction: walked_nodes = random_walk(graph, node) # Loop through nodes (that aren't the start node), count for n in filter(lambda m: m.id != node.id, walked_nodes): if nodes.has_key(n): nodes[n]++ else nodes[n] = 1 return TO_RETURN(sorted(nodes, key=nodes.__getitem__)) ## Instruction: Modify random walk so that it works. ## Code After: import neo4j import random DEFAULT_DEPTH = 5 NUM_WALKS = 100 # Passed sorted list (desc order), return top nodes TO_RETURN = lambda x: x[:10] random.seed() def random_walk(graph, node, depth=DEFAULT_DEPTH): if depth == 0: return [node] # Pick random neighbor neighbors = {} i = 0 for r in node.relationships().outgoing: neighbors[(i, i + int(r['count']))] = r.getOtherNode(node) i += int(r['count']) if i == 0: # No neighbors return [node] r = random.randrange(i) for x,y in neighbors: if x <= r and r < y: return [node] + random_walk(graph, neighbors[(x,y)], depth-1) def run(graph, index, node): nodes = {} for i in range(NUM_WALKS): with graph.transaction: walked_nodes = random_walk(graph, node) # Loop through nodes (that aren't the start node), count for n in filter(lambda m: m.id != node.id, walked_nodes): if nodes.has_key(n): nodes[n] += 1 else: nodes[n] = 1 return TO_RETURN([{'name': n['name'], 'count': nodes[n]} for n in sorted(nodes, key=nodes.__getitem__)])
// ... existing code ... import neo4j import random DEFAULT_DEPTH = 5 // ... modified code ... random.seed() def random_walk(graph, node, depth=DEFAULT_DEPTH): if depth == 0: return [node] # Pick random neighbor neighbors = {} i = 0 for r in node.relationships().outgoing: neighbors[(i, i + int(r['count']))] = r.getOtherNode(node) i += int(r['count']) if i == 0: # No neighbors return [node] r = random.randrange(i) for x,y in neighbors: if x <= r and r < y: return [node] + random_walk(graph, neighbors[(x,y)], depth-1) def run(graph, index, node): nodes = {} ... # Loop through nodes (that aren't the start node), count for n in filter(lambda m: m.id != node.id, walked_nodes): if nodes.has_key(n): nodes[n] += 1 else: nodes[n] = 1 return TO_RETURN([{'name': n['name'], 'count': nodes[n]} for n in sorted(nodes, key=nodes.__getitem__)]) // ... rest of the code ...
042720760a71b5e372489af2335c2fccc5b4905b
ynr/apps/uk_results/views/api.py
ynr/apps/uk_results/views/api.py
from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ProductFilter(filterset.FilterSet): election_id = filters.CharFilter(name="post_election__election__slug") election_date = filters.DateFilter( name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ProductFilter
from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ResultSetFilter(filterset.FilterSet): election_id = filters.CharFilter(field_name="post_election__election__slug") election_date = filters.DateFilter( field_name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ResultSetFilter
Update filter args and fix name
Update filter args and fix name The newer version of django-filter uses `field_name` rather than `name`
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
python
## Code Before: from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ProductFilter(filterset.FilterSet): election_id = filters.CharFilter(name="post_election__election__slug") election_date = filters.DateFilter( name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ProductFilter ## Instruction: Update filter args and fix name The newer version of django-filter uses `field_name` rather than `name` ## Code After: from rest_framework import viewsets from django_filters import filters, filterset from api.v09.views import ResultsSetPagination from ..models import CandidateResult, ResultSet from ..serializers import CandidateResultSerializer, ResultSetSerializer class CandidateResultViewSet(viewsets.ModelViewSet): queryset = CandidateResult.objects.select_related( "membership__party", "membership__post", "membership__person" ).order_by("id") serializer_class = CandidateResultSerializer pagination_class = ResultsSetPagination class ResultSetFilter(filterset.FilterSet): election_id = filters.CharFilter(field_name="post_election__election__slug") election_date = filters.DateFilter( field_name="post_election__election__election_date" ) class Meta: model = ResultSet fields = ["election_date", "election_id"] class ResultSetViewSet(viewsets.ModelViewSet): queryset = ResultSet.objects.select_related( "post_election__post", "user" ).order_by("id") serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ResultSetFilter
# ... existing code ... pagination_class = ResultsSetPagination class ResultSetFilter(filterset.FilterSet): election_id = filters.CharFilter(field_name="post_election__election__slug") election_date = filters.DateFilter( field_name="post_election__election__election_date" ) class Meta: # ... modified code ... serializer_class = ResultSetSerializer pagination_class = ResultsSetPagination filter_class = ResultSetFilter # ... rest of the code ...
34cb26b961b88efd40065c9653d566273fb99fe0
src/test/java/appstore/TestThisWillFailAbunch.java
src/test/java/appstore/TestThisWillFailAbunch.java
package appstore; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; public class TestThisWillFailAbunch { @Test public void aFailingTest() { assertTrue("I expected this to pass!", true); } @Ignore @Test public void aFailingTest2() { assertTrue("I expected this to pass!", true); } @Ignore @Test public void aFailingTest3() { assertTrue("I expected this to pass!", false); } //@Ignore @Test public void aFailingTest4() { doSomething(); } @Ignore @Test public void aNewFailingTest31() { assertTrue("I expected this to pass!", true); } @Test public void aNotherNewFailingTest4() { assertTrue("I expected this to pass!", true); } @Test public void aFailingTest5() { doSomething(); } @Test public void aFailingTest6() { assertTrue("I expected this to pass!", false); } @Test public void aPassingTest3() { assertTrue("Success!", true); } @Test public void aPassingTest4() { assertTrue("Success!", true); } private void doSomething() { interesting(); } private void interesting() { RubeGoldburgMachine machine = new RubeGoldburgMachine(); machine.processPayment(); } private class RubeGoldburgMachine { void processPayment() { throw new IllegalStateException("bad payment code"); } } }
package appstore; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; public class TestThisWillFailAbunch { @Test public void aFailingTest() { assertTrue("I expected this to pass!", true); } @Ignore @Test public void aFailingTest2() { assertTrue("I expected this to pass!", true); } @Ignore @Test public void aFailingTest3() { assertTrue("I expected this to pass!", false); } //@Ignore @Test public void aFailingTest4() { assertTrue("I expected this to pass!", true); } @Ignore @Test public void aNewFailingTest31() { assertTrue("I expected this to pass!", true); } @Test public void aNotherNewFailingTest4() { assertTrue("I expected this to pass!", true); } @Test public void aFailingTest5() { assertTrue("I expected this to pass!", true); } @Test public void aFailingTest6() { assertTrue("I expected this to pass!", false); } @Test public void aPassingTest3() { assertTrue("Success!", true); } @Test public void aPassingTest4() { assertTrue("Success!", true); } private void doSomething() { interesting(); } private void interesting() { RubeGoldburgMachine machine = new RubeGoldburgMachine(); machine.processPayment(); } private class RubeGoldburgMachine { void processPayment() { throw new IllegalStateException("bad payment code"); } } }
Fix payment processor test failures
Fix payment processor test failures
Java
mit
i386/app-store-demo,multibranchorg/app-store-demo
java
## Code Before: package appstore; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; public class TestThisWillFailAbunch { @Test public void aFailingTest() { assertTrue("I expected this to pass!", true); } @Ignore @Test public void aFailingTest2() { assertTrue("I expected this to pass!", true); } @Ignore @Test public void aFailingTest3() { assertTrue("I expected this to pass!", false); } //@Ignore @Test public void aFailingTest4() { doSomething(); } @Ignore @Test public void aNewFailingTest31() { assertTrue("I expected this to pass!", true); } @Test public void aNotherNewFailingTest4() { assertTrue("I expected this to pass!", true); } @Test public void aFailingTest5() { doSomething(); } @Test public void aFailingTest6() { assertTrue("I expected this to pass!", false); } @Test public void aPassingTest3() { assertTrue("Success!", true); } @Test public void aPassingTest4() { assertTrue("Success!", true); } private void doSomething() { interesting(); } private void interesting() { RubeGoldburgMachine machine = new RubeGoldburgMachine(); machine.processPayment(); } private class RubeGoldburgMachine { void processPayment() { throw new IllegalStateException("bad payment code"); } } } ## Instruction: Fix payment processor test failures ## Code After: package appstore; import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; public class TestThisWillFailAbunch { @Test public void aFailingTest() { assertTrue("I expected this to pass!", true); } @Ignore @Test public void aFailingTest2() { assertTrue("I expected this to pass!", true); } @Ignore @Test public void aFailingTest3() { assertTrue("I expected this to pass!", false); } //@Ignore @Test public void aFailingTest4() { assertTrue("I expected this to pass!", true); } @Ignore @Test public void aNewFailingTest31() { assertTrue("I expected this to pass!", true); } @Test public void aNotherNewFailingTest4() { assertTrue("I expected this to pass!", true); } @Test public void aFailingTest5() { assertTrue("I expected this to pass!", true); } @Test public void aFailingTest6() { assertTrue("I expected this to pass!", false); } @Test public void aPassingTest3() { assertTrue("Success!", true); } @Test public void aPassingTest4() { assertTrue("Success!", true); } private void doSomething() { interesting(); } private void interesting() { RubeGoldburgMachine machine = new RubeGoldburgMachine(); machine.processPayment(); } private class RubeGoldburgMachine { void processPayment() { throw new IllegalStateException("bad payment code"); } } }
// ... existing code ... //@Ignore @Test public void aFailingTest4() { assertTrue("I expected this to pass!", true); } @Ignore // ... modified code ... @Test public void aFailingTest5() { assertTrue("I expected this to pass!", true); } @Test // ... rest of the code ...
37fdbd56a6601848536f2a5ca64d66cf4aa3717a
cu-manager/src/main/java/fr/treeptik/cloudunit/hooks/HookAction.java
cu-manager/src/main/java/fr/treeptik/cloudunit/hooks/HookAction.java
package fr.treeptik.cloudunit.hooks; /** * Created by nicolas on 19/04/2016. */ public enum HookAction { APPLICATION_POST_START("Application post start", "/cloudunit/appconf/hooks/application-post-start.sh"), APPLICATION_POST_STOP("Application post stop", "/cloudunit/appconf/hooks/application-post-stop.sh"), APPLICATION_PRE_START("Application pre start", "/cloudunit/appconf/hooks/application-pre-start.sh"), APPLICATION_PRE_STOP("Application pre stop", "/cloudunit/appconf/hooks/application-pre-stop.sh"); private final String label; private final String command; HookAction(String label, String command) { this.label = label; this.command = command; } public String getLabel() { return label; } public String[] getCommand() { String[] commandBash = new String[2]; commandBash[0] = "bash"; commandBash[1] = command; return commandBash; } }
package fr.treeptik.cloudunit.hooks; /** * Created by nicolas on 19/04/2016. */ public enum HookAction { APPLICATION_POST_START("Application post start", "/cloudunit/appconf/hooks/application-post-start.sh"), APPLICATION_POST_STOP("Application post stop", "/cloudunit/appconf/hooks/application-post-stop.sh"), APPLICATION_PRE_START("Application pre start", "/cloudunit/appconf/hooks/application-pre-start.sh"), APPLICATION_PRE_STOP("Application pre stop", "/cloudunit/appconf/hooks/application-pre-stop.sh"), SNAPSHOT_PRE_ACTION("Before Snapshot", "/cloudunit/appconf/hooks/snapshot-pre-action.sh"), SNAPSHOT_POST_ACTION("After Snapshot", "/cloudunit/appconf/hooks/snapshot-post-action.sh"), CLONE_PRE_ACTION("Before restoring an application", "/cloudunit/appconf/hooks/clone-pre-action.sh"), CLONE_POST_ACTION("After restoring an application", "/cloudunit/appconf/hooks/clone-post-action.sh"); private final String label; private final String command; HookAction(String label, String command) { this.label = label; this.command = command; } public String getLabel() { return label; } public String[] getCommand() { String[] commandBash = new String[2]; commandBash[0] = "bash"; commandBash[1] = command; return commandBash; } }
Add new Hooks. Not yet called into code
Add new Hooks. Not yet called into code
Java
agpl-3.0
Treeptik/cloudunit,Treeptik/cloudunit,Treeptik/cloudunit,Treeptik/cloudunit,Treeptik/cloudunit,Treeptik/cloudunit
java
## Code Before: package fr.treeptik.cloudunit.hooks; /** * Created by nicolas on 19/04/2016. */ public enum HookAction { APPLICATION_POST_START("Application post start", "/cloudunit/appconf/hooks/application-post-start.sh"), APPLICATION_POST_STOP("Application post stop", "/cloudunit/appconf/hooks/application-post-stop.sh"), APPLICATION_PRE_START("Application pre start", "/cloudunit/appconf/hooks/application-pre-start.sh"), APPLICATION_PRE_STOP("Application pre stop", "/cloudunit/appconf/hooks/application-pre-stop.sh"); private final String label; private final String command; HookAction(String label, String command) { this.label = label; this.command = command; } public String getLabel() { return label; } public String[] getCommand() { String[] commandBash = new String[2]; commandBash[0] = "bash"; commandBash[1] = command; return commandBash; } } ## Instruction: Add new Hooks. Not yet called into code ## Code After: package fr.treeptik.cloudunit.hooks; /** * Created by nicolas on 19/04/2016. */ public enum HookAction { APPLICATION_POST_START("Application post start", "/cloudunit/appconf/hooks/application-post-start.sh"), APPLICATION_POST_STOP("Application post stop", "/cloudunit/appconf/hooks/application-post-stop.sh"), APPLICATION_PRE_START("Application pre start", "/cloudunit/appconf/hooks/application-pre-start.sh"), APPLICATION_PRE_STOP("Application pre stop", "/cloudunit/appconf/hooks/application-pre-stop.sh"), SNAPSHOT_PRE_ACTION("Before Snapshot", "/cloudunit/appconf/hooks/snapshot-pre-action.sh"), SNAPSHOT_POST_ACTION("After Snapshot", "/cloudunit/appconf/hooks/snapshot-post-action.sh"), CLONE_PRE_ACTION("Before restoring an application", "/cloudunit/appconf/hooks/clone-pre-action.sh"), CLONE_POST_ACTION("After restoring an application", "/cloudunit/appconf/hooks/clone-post-action.sh"); private final String label; private final String command; HookAction(String label, String command) { this.label = label; this.command = command; } public String getLabel() { return label; } public String[] getCommand() { String[] commandBash = new String[2]; commandBash[0] = "bash"; commandBash[1] = command; return commandBash; } }
// ... existing code ... APPLICATION_POST_START("Application post start", "/cloudunit/appconf/hooks/application-post-start.sh"), APPLICATION_POST_STOP("Application post stop", "/cloudunit/appconf/hooks/application-post-stop.sh"), APPLICATION_PRE_START("Application pre start", "/cloudunit/appconf/hooks/application-pre-start.sh"), APPLICATION_PRE_STOP("Application pre stop", "/cloudunit/appconf/hooks/application-pre-stop.sh"), SNAPSHOT_PRE_ACTION("Before Snapshot", "/cloudunit/appconf/hooks/snapshot-pre-action.sh"), SNAPSHOT_POST_ACTION("After Snapshot", "/cloudunit/appconf/hooks/snapshot-post-action.sh"), CLONE_PRE_ACTION("Before restoring an application", "/cloudunit/appconf/hooks/clone-pre-action.sh"), CLONE_POST_ACTION("After restoring an application", "/cloudunit/appconf/hooks/clone-post-action.sh"); private final String label; private final String command; // ... rest of the code ...
198a941c8c71802b72c33f5ef89d1d4d46e52eac
scripts/fetch_all_urls_to_disk.py
scripts/fetch_all_urls_to_disk.py
import urllib import os import hashlib with open('media_urls.txt','r') as f: for url in f: imagename = os.path.basename(url) m = hashlib.md5(url).hexdigest() if '.jpg' in url: shortname = m + '.jpg' elif '.png' in url: shortname = m + '.png' else: print 'no jpg nor png' print shortname with open(shortname, 'wb') as imgfile: imgfile.write(urllib.urlopen(url).read()) imgfile.close()
import urllib import os import hashlib with open('media_urls.txt','r') as f: for url in f: imagename = os.path.basename(url) m = hashlib.md5(url).hexdigest() if '.jpg' in url: shortname = m + '.jpg' elif '.png' in url: shortname = m + '.png' else: print 'no jpg nor png' continue print shortname with open(shortname, 'wb') as imgfile: imgfile.write(urllib.urlopen(url).read()) imgfile.close()
Add continue when no extension ".jpg" nor ".png" is found in URL
Add continue when no extension ".jpg" nor ".png" is found in URL
Python
mit
mixbe/kerstkaart2013,mixbe/kerstkaart2013
python
## Code Before: import urllib import os import hashlib with open('media_urls.txt','r') as f: for url in f: imagename = os.path.basename(url) m = hashlib.md5(url).hexdigest() if '.jpg' in url: shortname = m + '.jpg' elif '.png' in url: shortname = m + '.png' else: print 'no jpg nor png' print shortname with open(shortname, 'wb') as imgfile: imgfile.write(urllib.urlopen(url).read()) imgfile.close() ## Instruction: Add continue when no extension ".jpg" nor ".png" is found in URL ## Code After: import urllib import os import hashlib with open('media_urls.txt','r') as f: for url in f: imagename = os.path.basename(url) m = hashlib.md5(url).hexdigest() if '.jpg' in url: shortname = m + '.jpg' elif '.png' in url: shortname = m + '.png' else: print 'no jpg nor png' continue print shortname with open(shortname, 'wb') as imgfile: imgfile.write(urllib.urlopen(url).read()) imgfile.close()
... shortname = m + '.png' else: print 'no jpg nor png' continue print shortname with open(shortname, 'wb') as imgfile: ...
1e8cc5743f32bb5f6e2e9bcbee0f78e3df357449
tests/test_fastpbkdf2.py
tests/test_fastpbkdf2.py
import pytest from fastpbkdf2 import pbkdf2_hmac def test_unsupported_algorithm(): with pytest.raises(ValueError): pbkdf2_hmac("foo", b"password", b"salt", 1)
import binascii import pytest from fastpbkdf2 import pbkdf2_hmac def test_unsupported_algorithm(): with pytest.raises(ValueError): pbkdf2_hmac("foo", b"password", b"salt", 1) @pytest.mark.parametrize("password,salt,iterations,length,derived_key", [ (b"password", b"salt", 1, 20, b"0c60c80f961f0e71f3a9b524af6012062fe037a6"), (b"password", b"salt", 2, 20, b"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"), (b"password", b"salt", 4096, 20, b"4b007901b765489abead49d926f721d065a429c1"), (b"password", b"salt", 16777216, 20, b"eefe3d61cd4da4e4e9945b3d6ba2158c2634e984"), (b"passwordPASSWORDpassword", b"saltSALTsaltSALTsaltSALTsaltSALTsalt", 4096, 25, b"3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"), (b"pass\0word", b"sa\0lt", 4096, 16, b"56fa6aa75548099dcc37d7f03425e0c3"), ]) def test_with_vectors(password, salt, iterations, length, derived_key): assert binascii.hexlify( pbkdf2_hmac("sha1", password, salt, iterations, length) ) == derived_key
Add test for RFC 6070 vectors.
Add test for RFC 6070 vectors.
Python
apache-2.0
Ayrx/python-fastpbkdf2,Ayrx/python-fastpbkdf2
python
## Code Before: import pytest from fastpbkdf2 import pbkdf2_hmac def test_unsupported_algorithm(): with pytest.raises(ValueError): pbkdf2_hmac("foo", b"password", b"salt", 1) ## Instruction: Add test for RFC 6070 vectors. ## Code After: import binascii import pytest from fastpbkdf2 import pbkdf2_hmac def test_unsupported_algorithm(): with pytest.raises(ValueError): pbkdf2_hmac("foo", b"password", b"salt", 1) @pytest.mark.parametrize("password,salt,iterations,length,derived_key", [ (b"password", b"salt", 1, 20, b"0c60c80f961f0e71f3a9b524af6012062fe037a6"), (b"password", b"salt", 2, 20, b"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"), (b"password", b"salt", 4096, 20, b"4b007901b765489abead49d926f721d065a429c1"), (b"password", b"salt", 16777216, 20, b"eefe3d61cd4da4e4e9945b3d6ba2158c2634e984"), (b"passwordPASSWORDpassword", b"saltSALTsaltSALTsaltSALTsaltSALTsalt", 4096, 25, b"3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"), (b"pass\0word", b"sa\0lt", 4096, 16, b"56fa6aa75548099dcc37d7f03425e0c3"), ]) def test_with_vectors(password, salt, iterations, length, derived_key): assert binascii.hexlify( pbkdf2_hmac("sha1", password, salt, iterations, length) ) == derived_key
// ... existing code ... import binascii import pytest from fastpbkdf2 import pbkdf2_hmac // ... modified code ... def test_unsupported_algorithm(): with pytest.raises(ValueError): pbkdf2_hmac("foo", b"password", b"salt", 1) @pytest.mark.parametrize("password,salt,iterations,length,derived_key", [ (b"password", b"salt", 1, 20, b"0c60c80f961f0e71f3a9b524af6012062fe037a6"), (b"password", b"salt", 2, 20, b"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957"), (b"password", b"salt", 4096, 20, b"4b007901b765489abead49d926f721d065a429c1"), (b"password", b"salt", 16777216, 20, b"eefe3d61cd4da4e4e9945b3d6ba2158c2634e984"), (b"passwordPASSWORDpassword", b"saltSALTsaltSALTsaltSALTsaltSALTsalt", 4096, 25, b"3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038"), (b"pass\0word", b"sa\0lt", 4096, 16, b"56fa6aa75548099dcc37d7f03425e0c3"), ]) def test_with_vectors(password, salt, iterations, length, derived_key): assert binascii.hexlify( pbkdf2_hmac("sha1", password, salt, iterations, length) ) == derived_key // ... rest of the code ...
133a085f40f1536d5ebb26e912d15fa3bddcc82c
manager.py
manager.py
from cement.core.foundation import CementApp import command import util.config util.config.Configuration() class Manager(CementApp): class Meta: label = 'QLDS-Manager' handlers = [ command.default.ManagerBaseController, command.setup.SetupController ] with Manager() as app: app.run()
from cement.core.foundation import CementApp import command import util.config class Manager(CementApp): class Meta: label = 'QLDS-Manager' handlers = command.commands with Manager() as app: app.run()
Use handlers defined in command package
Use handlers defined in command package
Python
mit
rzeka/QLDS-Manager
python
## Code Before: from cement.core.foundation import CementApp import command import util.config util.config.Configuration() class Manager(CementApp): class Meta: label = 'QLDS-Manager' handlers = [ command.default.ManagerBaseController, command.setup.SetupController ] with Manager() as app: app.run() ## Instruction: Use handlers defined in command package ## Code After: from cement.core.foundation import CementApp import command import util.config class Manager(CementApp): class Meta: label = 'QLDS-Manager' handlers = command.commands with Manager() as app: app.run()
# ... existing code ... import command import util.config class Manager(CementApp): class Meta: label = 'QLDS-Manager' handlers = command.commands with Manager() as app: # ... rest of the code ...
8adfceb0e4c482b5cc3119dbeffc2c4335c9d553
jctools-core/src/main/java/org/jctools/util/UnsafeAccess.java
jctools-core/src/main/java/org/jctools/util/UnsafeAccess.java
package org.jctools.util; import java.lang.reflect.Field; import sun.misc.Unsafe; public class UnsafeAccess { public static final Unsafe UNSAFE; static { try { // This is a bit of voodoo to force the unsafe object into // visibility and acquire it. // This is not playing nice, but as an established back door it is // not likely to be // taken away. final Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); UNSAFE = (Unsafe) field.get(null); } catch (Exception e) { throw new RuntimeException(e); } } }
package org.jctools.util; import java.lang.reflect.Field; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import sun.misc.Unsafe; /** * Why should we resort to using Unsafe?<br> * <ol> * <li>To construct class fields which allow volatile/ordered/plain access: This requirement is covered by * {@link AtomicReferenceFieldUpdater} and similar but their performance is arguably worse than the DIY approach * (depending on JVM version) while Unsafe intrinsification is a far lesser challenge for JIT compilers. * <li>To construct flavors of {@link AtomicReferenceArray}. * <li>Other use cases exist but are not present in this library yet. * <ol> * * @author nitsanw * */ public class UnsafeAccess { public static final Unsafe UNSAFE; static { try { /* * This is a bit of voodoo to force the unsafe object into visibility and acquire it. This is not playing * nice, but as an established back door it is not likely to be taken away. */ final Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); UNSAFE = (Unsafe) field.get(null); } catch (Exception e) { throw new RuntimeException(e); } } }
Add comment justifying the use of UNSAFE.
Add comment justifying the use of UNSAFE.
Java
apache-2.0
franz1981/JCTools,fengjiachun/JCTools,akarnokd/JCTools,thomasdarimont/JCTools,mackstone/JCTools,JCTools/JCTools
java
## Code Before: package org.jctools.util; import java.lang.reflect.Field; import sun.misc.Unsafe; public class UnsafeAccess { public static final Unsafe UNSAFE; static { try { // This is a bit of voodoo to force the unsafe object into // visibility and acquire it. // This is not playing nice, but as an established back door it is // not likely to be // taken away. final Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); UNSAFE = (Unsafe) field.get(null); } catch (Exception e) { throw new RuntimeException(e); } } } ## Instruction: Add comment justifying the use of UNSAFE. ## Code After: package org.jctools.util; import java.lang.reflect.Field; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import sun.misc.Unsafe; /** * Why should we resort to using Unsafe?<br> * <ol> * <li>To construct class fields which allow volatile/ordered/plain access: This requirement is covered by * {@link AtomicReferenceFieldUpdater} and similar but their performance is arguably worse than the DIY approach * (depending on JVM version) while Unsafe intrinsification is a far lesser challenge for JIT compilers. * <li>To construct flavors of {@link AtomicReferenceArray}. * <li>Other use cases exist but are not present in this library yet. * <ol> * * @author nitsanw * */ public class UnsafeAccess { public static final Unsafe UNSAFE; static { try { /* * This is a bit of voodoo to force the unsafe object into visibility and acquire it. This is not playing * nice, but as an established back door it is not likely to be taken away. */ final Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); UNSAFE = (Unsafe) field.get(null); } catch (Exception e) { throw new RuntimeException(e); } } }
// ... existing code ... package org.jctools.util; import java.lang.reflect.Field; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import sun.misc.Unsafe; /** * Why should we resort to using Unsafe?<br> * <ol> * <li>To construct class fields which allow volatile/ordered/plain access: This requirement is covered by * {@link AtomicReferenceFieldUpdater} and similar but their performance is arguably worse than the DIY approach * (depending on JVM version) while Unsafe intrinsification is a far lesser challenge for JIT compilers. * <li>To construct flavors of {@link AtomicReferenceArray}. * <li>Other use cases exist but are not present in this library yet. * <ol> * * @author nitsanw * */ public class UnsafeAccess { public static final Unsafe UNSAFE; static { try { /* * This is a bit of voodoo to force the unsafe object into visibility and acquire it. This is not playing * nice, but as an established back door it is not likely to be taken away. */ final Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); UNSAFE = (Unsafe) field.get(null); // ... rest of the code ...
4510a4a22965d002bd41293fd8fe629c8285800d
tests/test_errors.py
tests/test_errors.py
import pytest from pyxl.codec.register import pyxl_decode from pyxl.codec.parser import ParseError def test_malformed_if(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> this is incorrect! <else>bar</else> </frag>""") def test_multiple_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else>bar</else> <else>baz</else> </frag>""") def test_nested_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else><else>bar</else></else> </frag>""")
import pytest from pyxl.codec.register import pyxl_decode from pyxl.codec.parser import ParseError from pyxl.codec.html_tokenizer import BadCharError def test_malformed_if(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> this is incorrect! <else>bar</else> </frag>""") def test_multiple_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else>bar</else> <else>baz</else> </frag>""") def test_nested_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else><else>bar</else></else> </frag>""") def test_bad_char(): with pytest.raises(BadCharError): pyxl_decode(b"""<_bad_element></lm>""")
Add test for BadCharError exception.
Add test for BadCharError exception.
Python
apache-2.0
pyxl4/pyxl4
python
## Code Before: import pytest from pyxl.codec.register import pyxl_decode from pyxl.codec.parser import ParseError def test_malformed_if(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> this is incorrect! <else>bar</else> </frag>""") def test_multiple_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else>bar</else> <else>baz</else> </frag>""") def test_nested_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else><else>bar</else></else> </frag>""") ## Instruction: Add test for BadCharError exception. ## Code After: import pytest from pyxl.codec.register import pyxl_decode from pyxl.codec.parser import ParseError from pyxl.codec.html_tokenizer import BadCharError def test_malformed_if(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> this is incorrect! <else>bar</else> </frag>""") def test_multiple_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else>bar</else> <else>baz</else> </frag>""") def test_nested_else(): with pytest.raises(ParseError): pyxl_decode(b""" <frag> <if cond="{true}">foo</if> <else><else>bar</else></else> </frag>""") def test_bad_char(): with pytest.raises(BadCharError): pyxl_decode(b"""<_bad_element></lm>""")
# ... existing code ... from pyxl.codec.register import pyxl_decode from pyxl.codec.parser import ParseError from pyxl.codec.html_tokenizer import BadCharError def test_malformed_if(): with pytest.raises(ParseError): # ... modified code ... <if cond="{true}">foo</if> <else><else>bar</else></else> </frag>""") def test_bad_char(): with pytest.raises(BadCharError): pyxl_decode(b"""<_bad_element></lm>""") # ... rest of the code ...
End of preview. Expand in Data Studio

Code Apply

Processed EditPackFT-Multi Python, Java, Kotlin, and C splits with fuzzy diff generated using heuristics.

Dataset Preparation

Steps to replicate. For this version --min_lines_between_chunks=3 was used.

Columns

  1. old_contents the old code
  2. new_contents the new code
  3. fuzzy_diff the code segment extracted from diff between old_contents and new_contents

Example

Diff

  from kombu import BrokerConnection
  from kombu.common import maybe_declare
  from kombu.pools import producers
  
  from sentry.conf import settings
  from sentry.queue.queues import task_queues, task_exchange
  
  
  class Broker(object):
      def __init__(self, config):
          self.connection = BrokerConnection(**config)
+         with producers[self.connection].acquire(block=False) as producer:
+             for queue in task_queues:
+                 maybe_declare(queue, producer.channel)
  
      def delay(self, func, *args, **kwargs):
          payload = {
              "func": func,
              "args": args,
              "kwargs": kwargs,
          }
  
          with producers[self.connection].acquire(block=False) as producer:
-             for queue in task_queues:
-                 maybe_declare(queue, producer.channel)
              producer.publish(payload,
                  exchange=task_exchange,
                  serializer="pickle",
                  compression="bzip2",
                  queue='default',
                  routing_key='default',
              )
  
  broker = Broker(settings.QUEUE)

Snippet

# ... existing code ... 


        self.connection = BrokerConnection(**config)
        with producers[self.connection].acquire(block=False) as producer:
            for queue in task_queues:
                maybe_declare(queue, producer.channel)

    def delay(self, func, *args, **kwargs):


# ... modified code ... 


        with producers[self.connection].acquire(block=False) as producer:
            producer.publish(payload,
                exchange=task_exchange,


# ... rest of the code ...

Partial apply

from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers

from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange


class Broker(object):
    def __init__(self, config):
        self.connection = BrokerConnection(**config)
        with producers[self.connection].acquire(block=False) as producer:
            for queue in task_queues:
                maybe_declare(queue, producer.channel)

    def delay(self, func, *args, **kwargs):
        payload = {
            "func": func,
            "args": args,
            "kwargs": kwargs,
        }

        with producers[self.connection].acquire(block=False) as producer:
            for queue in task_queues:
                maybe_declare(queue, producer.channel)
            producer.publish(payload,
                exchange=task_exchange,
                serializer="pickle",
                compression="bzip2",
                queue='default',
                routing_key='default',
            )

broker = Broker(settings.QUEUE)

Downloads last month
12