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
1c51c772d4b21eba70cd09429e603f1873b2c13c
examples/demo.py
examples/demo.py
import pytaf taf_str = """ TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001 TEMPO 2914/2915 1SM -BR CLR FM291500 04006KT P6SM SKC TEMPO 2915/2917 2SM BR OVC008 FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB FM300100 31007KT P6SM SCT070 BKN120 +FC FM300500 23006KT P6SM SCT120 $ """ t = pytaf.TAF(taf_str) d = pytaf.Decoder(t) print taf_str print dec = d.decode_taf() print dec
import pytaf taf_str = """ TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001 TEMPO 2914/2915 1SM -BR CLR FM291500 04006KT P6SM SKC TEMPO 2915/2917 2SM BR OVC008 FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB FM300100 31007KT P6SM SCT070 BKN120 +FC FM300500 23006KT P6SM SCT120 $ """ # Create a parsed TAF object from string t = pytaf.TAF(taf_str) # Create a decoder object from the TAF object d = pytaf.Decoder(t) # Print the raw string for the reference print(taf_str) # Decode and print the decoded string dec = d.decode_taf() print(dec)
Update the example script to work with python3.
Update the example script to work with python3.
Python
mit
dmbaturin/pytaf
python
## Code Before: import pytaf taf_str = """ TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001 TEMPO 2914/2915 1SM -BR CLR FM291500 04006KT P6SM SKC TEMPO 2915/2917 2SM BR OVC008 FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB FM300100 31007KT P6SM SCT070 BKN120 +FC FM300500 23006KT P6SM SCT120 $ """ t = pytaf.TAF(taf_str) d = pytaf.Decoder(t) print taf_str print dec = d.decode_taf() print dec ## Instruction: Update the example script to work with python3. ## Code After: import pytaf taf_str = """ TAF AMD KDEN 291134Z 2912/3018 32006KT 1/4SM FG OVC001 TEMPO 2914/2915 1SM -BR CLR FM291500 04006KT P6SM SKC TEMPO 2915/2917 2SM BR OVC008 FM291900 05007KT P6SM SCT050 BKN090 WS010/13040KT PROB30 2921/3001 VRB20G30KT -TSRA BKN050CB FM300100 31007KT P6SM SCT070 BKN120 +FC FM300500 23006KT P6SM SCT120 $ """ # Create a parsed TAF object from string t = pytaf.TAF(taf_str) # Create a decoder object from the TAF object d = pytaf.Decoder(t) # Print the raw string for the reference print(taf_str) # Decode and print the decoded string dec = d.decode_taf() print(dec)
# ... existing code ... FM300500 23006KT P6SM SCT120 $ """ # Create a parsed TAF object from string t = pytaf.TAF(taf_str) # Create a decoder object from the TAF object d = pytaf.Decoder(t) # Print the raw string for the reference print(taf_str) # Decode and print the decoded string dec = d.decode_taf() print(dec) # ... rest of the code ...
4dd28beddc2df9efeef798491d1963800113f801
django_bootstrap_calendar/models.py
django_bootstrap_calendar/models.py
__author__ = 'sandlbn' from django.db import models from django.utils.translation import ugettext_lazy as _ from utils import datetime_to_timestamp class CalendarEvent(models.Model): """ Calendar Events """ CSS_CLASS_CHOICES = ( ('', _('Normal')), ('event-warning', _('Warning')), ('event-info', _('Info')), ('event-success', _('Success')), ('event-inverse', _('Inverse')), ('event-special', _('Special')), ('event-important', _('Important')), ) title = models.CharField(max_length=255, verbose_name=_('Title')) url = models.URLField(verbose_name=_('URL'), null=True, blank=True) css_class = models.CharField(max_length=20, verbose_name=_('CSS Class'), choices=CSS_CLASS_CHOICES) start = models.DateTimeField(verbose_name=_('Start Date')) end = models.DateTimeField(verbose_name=_('End Date'), null=True, blank=True) @property def start_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.start) @property def end_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.end) def __unicode__(self): return self.title
__author__ = 'sandlbn' from django.db import models from django.utils.translation import ugettext_lazy as _ from utils import datetime_to_timestamp class CalendarEvent(models.Model): """ Calendar Events """ CSS_CLASS_CHOICES = ( ('', _('Normal')), ('event-warning', _('Warning')), ('event-info', _('Info')), ('event-success', _('Success')), ('event-inverse', _('Inverse')), ('event-special', _('Special')), ('event-important', _('Important')), ) title = models.CharField(max_length=255, verbose_name=_('Title')) url = models.URLField(verbose_name=_('URL'), null=True, blank=True) css_class = models.CharField(blank=True, max_length=20, verbose_name=_('CSS Class'), choices=CSS_CLASS_CHOICES) start = models.DateTimeField(verbose_name=_('Start Date')) end = models.DateTimeField(verbose_name=_('End Date'), null=True, blank=True) @property def start_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.start) @property def end_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.end) def __unicode__(self): return self.title
Allow `css_class` to have blank value.
Allow `css_class` to have blank value. Currently the default value for the `css_class` field (name `Normal`) has the value of a blank string. To allow the value to be used `blank=True` must be set.
Python
bsd-3-clause
sandlbn/django-bootstrap-calendar,sandlbn/django-bootstrap-calendar,sandlbn/django-bootstrap-calendar
python
## Code Before: __author__ = 'sandlbn' from django.db import models from django.utils.translation import ugettext_lazy as _ from utils import datetime_to_timestamp class CalendarEvent(models.Model): """ Calendar Events """ CSS_CLASS_CHOICES = ( ('', _('Normal')), ('event-warning', _('Warning')), ('event-info', _('Info')), ('event-success', _('Success')), ('event-inverse', _('Inverse')), ('event-special', _('Special')), ('event-important', _('Important')), ) title = models.CharField(max_length=255, verbose_name=_('Title')) url = models.URLField(verbose_name=_('URL'), null=True, blank=True) css_class = models.CharField(max_length=20, verbose_name=_('CSS Class'), choices=CSS_CLASS_CHOICES) start = models.DateTimeField(verbose_name=_('Start Date')) end = models.DateTimeField(verbose_name=_('End Date'), null=True, blank=True) @property def start_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.start) @property def end_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.end) def __unicode__(self): return self.title ## Instruction: Allow `css_class` to have blank value. Currently the default value for the `css_class` field (name `Normal`) has the value of a blank string. To allow the value to be used `blank=True` must be set. ## Code After: __author__ = 'sandlbn' from django.db import models from django.utils.translation import ugettext_lazy as _ from utils import datetime_to_timestamp class CalendarEvent(models.Model): """ Calendar Events """ CSS_CLASS_CHOICES = ( ('', _('Normal')), ('event-warning', _('Warning')), ('event-info', _('Info')), ('event-success', _('Success')), ('event-inverse', _('Inverse')), ('event-special', _('Special')), ('event-important', _('Important')), ) title = models.CharField(max_length=255, verbose_name=_('Title')) url = models.URLField(verbose_name=_('URL'), null=True, blank=True) css_class = models.CharField(blank=True, max_length=20, verbose_name=_('CSS Class'), choices=CSS_CLASS_CHOICES) start = models.DateTimeField(verbose_name=_('Start Date')) end = models.DateTimeField(verbose_name=_('End Date'), null=True, blank=True) @property def start_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.start) @property def end_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.end) def __unicode__(self): return self.title
# ... existing code ... ) title = models.CharField(max_length=255, verbose_name=_('Title')) url = models.URLField(verbose_name=_('URL'), null=True, blank=True) css_class = models.CharField(blank=True, max_length=20, verbose_name=_('CSS Class'), choices=CSS_CLASS_CHOICES) start = models.DateTimeField(verbose_name=_('Start Date')) end = models.DateTimeField(verbose_name=_('End Date'), null=True, # ... rest of the code ...
27ab3ad3d1ce869baec85264b840da49ff43f82f
scripts/sync_exceeded_traffic_limits.py
scripts/sync_exceeded_traffic_limits.py
import os from flask import _request_ctx_stack, g, request from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from pycroft.model import session from pycroft.model.session import set_scoped_session from scripts.schema import AlembicHelper, SchemaStrategist from pycroft.lib import traffic def main(): try: connection_string = os.environ['PYCROFT_DB_URI'] except KeyError: raise RuntimeError("Environment variable PYCROFT_DB_URI must be " "set to an SQLAlchemy connection string.") engine = create_engine(connection_string) connection = engine.connect() state = AlembicHelper(connection) strategy = SchemaStrategist(state).determine_schema_strategy() strategy() engine = create_engine(connection_string) set_scoped_session(scoped_session(sessionmaker(bind=engine), scopefunc=lambda: _request_ctx_stack.top)) print("Starting synchronization of exceeded traffic limits.") traffic.sync_exceeded_traffic_limits() session.session.commit() print("Finished synchronization.") if __name__ == "__main__": main()
import os from flask import _request_ctx_stack, g, request from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from pycroft.model import session from pycroft.model.session import set_scoped_session from scripts.schema import AlembicHelper, SchemaStrategist from pycroft.lib import traffic def main(): try: connection_string = os.environ['PYCROFT_DB_URI'] except KeyError: raise RuntimeError("Environment variable PYCROFT_DB_URI must be " "set to an SQLAlchemy connection string.") engine = create_engine(connection_string) connection = engine.connect() state = AlembicHelper(connection) strategist = SchemaStrategist(state) is_up_to_date = strategist.helper.running_version == strategist.helper.desired_version if not is_up_to_date: print("Schema is not up to date!") return set_scoped_session(scoped_session(sessionmaker(bind=engine), scopefunc=lambda: _request_ctx_stack.top)) print("Starting synchronization of exceeded traffic limits.") traffic.sync_exceeded_traffic_limits() session.session.commit() print("Finished synchronization.") if __name__ == "__main__": main()
Add schema version check to sync script
Add schema version check to sync script
Python
apache-2.0
agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,agdsn/pycroft
python
## Code Before: import os from flask import _request_ctx_stack, g, request from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from pycroft.model import session from pycroft.model.session import set_scoped_session from scripts.schema import AlembicHelper, SchemaStrategist from pycroft.lib import traffic def main(): try: connection_string = os.environ['PYCROFT_DB_URI'] except KeyError: raise RuntimeError("Environment variable PYCROFT_DB_URI must be " "set to an SQLAlchemy connection string.") engine = create_engine(connection_string) connection = engine.connect() state = AlembicHelper(connection) strategy = SchemaStrategist(state).determine_schema_strategy() strategy() engine = create_engine(connection_string) set_scoped_session(scoped_session(sessionmaker(bind=engine), scopefunc=lambda: _request_ctx_stack.top)) print("Starting synchronization of exceeded traffic limits.") traffic.sync_exceeded_traffic_limits() session.session.commit() print("Finished synchronization.") if __name__ == "__main__": main() ## Instruction: Add schema version check to sync script ## Code After: import os from flask import _request_ctx_stack, g, request from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from pycroft.model import session from pycroft.model.session import set_scoped_session from scripts.schema import AlembicHelper, SchemaStrategist from pycroft.lib import traffic def main(): try: connection_string = os.environ['PYCROFT_DB_URI'] except KeyError: raise RuntimeError("Environment variable PYCROFT_DB_URI must be " "set to an SQLAlchemy connection string.") engine = create_engine(connection_string) connection = engine.connect() state = AlembicHelper(connection) strategist = SchemaStrategist(state) is_up_to_date = strategist.helper.running_version == strategist.helper.desired_version if not is_up_to_date: print("Schema is not up to date!") return set_scoped_session(scoped_session(sessionmaker(bind=engine), scopefunc=lambda: _request_ctx_stack.top)) print("Starting synchronization of exceeded traffic limits.") traffic.sync_exceeded_traffic_limits() session.session.commit() print("Finished synchronization.") if __name__ == "__main__": main()
... engine = create_engine(connection_string) connection = engine.connect() state = AlembicHelper(connection) strategist = SchemaStrategist(state) is_up_to_date = strategist.helper.running_version == strategist.helper.desired_version if not is_up_to_date: print("Schema is not up to date!") return set_scoped_session(scoped_session(sessionmaker(bind=engine), scopefunc=lambda: _request_ctx_stack.top)) ...
4863b1ccaf85c57f7b84b20377b5ff8470da99b7
fake-koji/src/main/java/org/fakekoji/api/http/rest/RestUtils.java
fake-koji/src/main/java/org/fakekoji/api/http/rest/RestUtils.java
package org.fakekoji.api.http.rest; import java.util.List; import java.util.Map; import java.util.Optional; class RestUtils { static Optional<String> extractParamValue(Map<String, List<String>> paramsMap, String param) { return Optional.ofNullable(paramsMap.get(param)) .filter(list -> list.size() == 1) .map(list -> list.get(0)); } }
package org.fakekoji.api.http.rest; import org.fakekoji.functional.Result; import org.fakekoji.functional.Tuple; import org.fakekoji.jobmanager.model.Product; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; class RestUtils { static Optional<String> extractParamValue(Map<String, List<String>> paramsMap, String param) { return Optional.ofNullable(paramsMap.get(param)) .filter(list -> list.size() == 1) .map(list -> list.get(0)); } static Result<String, OToolError> extractMandatoryParamValue(Map<String, List<String>> paramsMap, String param) { return extractParamValue(paramsMap, param).<Result<String, OToolError>>map(Result::ok) .orElseGet(() -> Result.err(new OToolError( "Missing mandatory parameter: '" + param + "'!", 400 ))); } static Result<Tuple<Product, Product>, OToolError> extractProducts(final Map<String, List<String>> paramsMap) { return extractMandatoryParamValue(paramsMap, "from").flatMap(fromValue -> extractProduct(fromValue).flatMap(fromProduct -> extractMandatoryParamValue(paramsMap, "to").flatMap(toValue -> extractProduct(toValue).flatMap(toProduct -> Result.ok(new Tuple<>(fromProduct, toProduct)) ) ) ) ); } static Result<Product, OToolError> extractProduct(final String paramValue) { final String[] split = paramValue.split(","); if (split.length != 2 || split[0].trim().isEmpty() || split[1].trim().isEmpty()) { return Result.err(new OToolError("Expected format jdkVersionId,packageName", 400)); } return Result.ok(new Product(split[0], split[1])); } static Result<List<String>, OToolError> extractProjectIds(Map<String, List<String>> paramsMap) { final Optional<String> projectIdsOptional = extractParamValue(paramsMap, "projects"); return projectIdsOptional.<Result<List<String>, OToolError>>map(s -> Result.ok(Arrays.asList(s.split(","))) ).orElseGet(() -> Result.err(new OToolError( "projects are mandatory. Use get/projects?as=list to get them all", 400 ))); } }
Create helper methods for product bump
Create helper methods for product bump
Java
mit
judovana/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin
java
## Code Before: package org.fakekoji.api.http.rest; import java.util.List; import java.util.Map; import java.util.Optional; class RestUtils { static Optional<String> extractParamValue(Map<String, List<String>> paramsMap, String param) { return Optional.ofNullable(paramsMap.get(param)) .filter(list -> list.size() == 1) .map(list -> list.get(0)); } } ## Instruction: Create helper methods for product bump ## Code After: package org.fakekoji.api.http.rest; import org.fakekoji.functional.Result; import org.fakekoji.functional.Tuple; import org.fakekoji.jobmanager.model.Product; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; class RestUtils { static Optional<String> extractParamValue(Map<String, List<String>> paramsMap, String param) { return Optional.ofNullable(paramsMap.get(param)) .filter(list -> list.size() == 1) .map(list -> list.get(0)); } static Result<String, OToolError> extractMandatoryParamValue(Map<String, List<String>> paramsMap, String param) { return extractParamValue(paramsMap, param).<Result<String, OToolError>>map(Result::ok) .orElseGet(() -> Result.err(new OToolError( "Missing mandatory parameter: '" + param + "'!", 400 ))); } static Result<Tuple<Product, Product>, OToolError> extractProducts(final Map<String, List<String>> paramsMap) { return extractMandatoryParamValue(paramsMap, "from").flatMap(fromValue -> extractProduct(fromValue).flatMap(fromProduct -> extractMandatoryParamValue(paramsMap, "to").flatMap(toValue -> extractProduct(toValue).flatMap(toProduct -> Result.ok(new Tuple<>(fromProduct, toProduct)) ) ) ) ); } static Result<Product, OToolError> extractProduct(final String paramValue) { final String[] split = paramValue.split(","); if (split.length != 2 || split[0].trim().isEmpty() || split[1].trim().isEmpty()) { return Result.err(new OToolError("Expected format jdkVersionId,packageName", 400)); } return Result.ok(new Product(split[0], split[1])); } static Result<List<String>, OToolError> extractProjectIds(Map<String, List<String>> paramsMap) { final Optional<String> projectIdsOptional = extractParamValue(paramsMap, "projects"); return projectIdsOptional.<Result<List<String>, OToolError>>map(s -> Result.ok(Arrays.asList(s.split(","))) ).orElseGet(() -> Result.err(new OToolError( "projects are mandatory. Use get/projects?as=list to get them all", 400 ))); } }
... package org.fakekoji.api.http.rest; import org.fakekoji.functional.Result; import org.fakekoji.functional.Tuple; import org.fakekoji.jobmanager.model.Product; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; ... .map(list -> list.get(0)); } static Result<String, OToolError> extractMandatoryParamValue(Map<String, List<String>> paramsMap, String param) { return extractParamValue(paramsMap, param).<Result<String, OToolError>>map(Result::ok) .orElseGet(() -> Result.err(new OToolError( "Missing mandatory parameter: '" + param + "'!", 400 ))); } static Result<Tuple<Product, Product>, OToolError> extractProducts(final Map<String, List<String>> paramsMap) { return extractMandatoryParamValue(paramsMap, "from").flatMap(fromValue -> extractProduct(fromValue).flatMap(fromProduct -> extractMandatoryParamValue(paramsMap, "to").flatMap(toValue -> extractProduct(toValue).flatMap(toProduct -> Result.ok(new Tuple<>(fromProduct, toProduct)) ) ) ) ); } static Result<Product, OToolError> extractProduct(final String paramValue) { final String[] split = paramValue.split(","); if (split.length != 2 || split[0].trim().isEmpty() || split[1].trim().isEmpty()) { return Result.err(new OToolError("Expected format jdkVersionId,packageName", 400)); } return Result.ok(new Product(split[0], split[1])); } static Result<List<String>, OToolError> extractProjectIds(Map<String, List<String>> paramsMap) { final Optional<String> projectIdsOptional = extractParamValue(paramsMap, "projects"); return projectIdsOptional.<Result<List<String>, OToolError>>map(s -> Result.ok(Arrays.asList(s.split(","))) ).orElseGet(() -> Result.err(new OToolError( "projects are mandatory. Use get/projects?as=list to get them all", 400 ))); } } ...
d28fa7874d7b0602eb5064d9f43b8b01674de69f
presentation/models.py
presentation/models.py
from django.db import models from model_utils.models import TimeStampedModel from warp.users.models import User class Presentation(TimeStampedModel): subject = models.CharField(max_length=50) author = models.ForeignKey(User, on_delete=models.CASCADE) views = models.IntegerField(default=0) is_public = models.BooleanField(default=True) def __str__(self): return self.subject class Slide(TimeStampedModel): presentation = models.ForeignKey(Presentation, on_delete=models.CASCADE) slide_order = models.PositiveSmallIntegerField() markdown = models.TextField() def __str__(self): return self.markdown
from django.db import models from django.db.models import Manager from django.db.models import QuerySet from model_utils.models import TimeStampedModel from warp.users.models import User class PresentationQuerySet(QuerySet): def public(self): return self.filter(is_public=True) def authored_by(self, author): return self.filter(author__username=author) class PresentationManager(Manager): def get_queryset(self): return PresentationQuerySet(self.model, using=self._db) def public(self): return self.get_queryset().public() def authored_by(self, author): return self.get_queryset().authored_by(author) class Presentation(TimeStampedModel): subject = models.CharField(max_length=50) author = models.ForeignKey(User, on_delete=models.CASCADE) views = models.IntegerField(default=0) is_public = models.BooleanField(default=True) objects = PresentationManager() def __str__(self): return self.subject class Slide(TimeStampedModel): presentation = models.ForeignKey(Presentation, on_delete=models.CASCADE) slide_order = models.PositiveSmallIntegerField() markdown = models.TextField() def __str__(self): return self.markdown
Add presentation queryset and model manager
Add presentation queryset and model manager
Python
mit
SaturDJang/warp,SaturDJang/warp,SaturDJang/warp,SaturDJang/warp
python
## Code Before: from django.db import models from model_utils.models import TimeStampedModel from warp.users.models import User class Presentation(TimeStampedModel): subject = models.CharField(max_length=50) author = models.ForeignKey(User, on_delete=models.CASCADE) views = models.IntegerField(default=0) is_public = models.BooleanField(default=True) def __str__(self): return self.subject class Slide(TimeStampedModel): presentation = models.ForeignKey(Presentation, on_delete=models.CASCADE) slide_order = models.PositiveSmallIntegerField() markdown = models.TextField() def __str__(self): return self.markdown ## Instruction: Add presentation queryset and model manager ## Code After: from django.db import models from django.db.models import Manager from django.db.models import QuerySet from model_utils.models import TimeStampedModel from warp.users.models import User class PresentationQuerySet(QuerySet): def public(self): return self.filter(is_public=True) def authored_by(self, author): return self.filter(author__username=author) class PresentationManager(Manager): def get_queryset(self): return PresentationQuerySet(self.model, using=self._db) def public(self): return self.get_queryset().public() def authored_by(self, author): return self.get_queryset().authored_by(author) class Presentation(TimeStampedModel): subject = models.CharField(max_length=50) author = models.ForeignKey(User, on_delete=models.CASCADE) views = models.IntegerField(default=0) is_public = models.BooleanField(default=True) objects = PresentationManager() def __str__(self): return self.subject class Slide(TimeStampedModel): presentation = models.ForeignKey(Presentation, on_delete=models.CASCADE) slide_order = models.PositiveSmallIntegerField() markdown = models.TextField() def __str__(self): return self.markdown
// ... existing code ... from django.db import models from django.db.models import Manager from django.db.models import QuerySet from model_utils.models import TimeStampedModel from warp.users.models import User class PresentationQuerySet(QuerySet): def public(self): return self.filter(is_public=True) def authored_by(self, author): return self.filter(author__username=author) class PresentationManager(Manager): def get_queryset(self): return PresentationQuerySet(self.model, using=self._db) def public(self): return self.get_queryset().public() def authored_by(self, author): return self.get_queryset().authored_by(author) class Presentation(TimeStampedModel): // ... modified code ... author = models.ForeignKey(User, on_delete=models.CASCADE) views = models.IntegerField(default=0) is_public = models.BooleanField(default=True) objects = PresentationManager() def __str__(self): return self.subject // ... rest of the code ...
cbe07cd63d07f021ccd404cba2bcfe2a6933457b
tests/test_misc.py
tests/test_misc.py
import billboard import unittest from nose.tools import raises from requests.exceptions import ConnectionError import six class MiscTest(unittest.TestCase): @raises(ConnectionError) def test_timeout(self): """Checks that using a very small timeout prevents connection.""" billboard.ChartData('hot-100', timeout=1e-9) @raises(billboard.BillboardNotFoundException) def test_non_existent_chart(self): """Checks that requesting a non-existent chart fails.""" billboard.ChartData('does-not-exist') def test_unicode(self): """Checks that the Billboard website does not use Unicode characters.""" chart = billboard.ChartData('hot-100', date='2018-01-27') self.assertEqual(chart[97].title, six.text_type( 'El Bano')) # With Unicode this should be "El Baño" def test_difficult_title_casing(self): """Checks that a difficult chart title receives proper casing.""" chart = billboard.ChartData('greatest-r-b-hip-hop-songs') self.assertEqual(chart.title, 'Greatest of All Time Hot R&B/Hip-Hop Songs')
import billboard import unittest from nose.tools import raises from requests.exceptions import ConnectionError import six class MiscTest(unittest.TestCase): @raises(ConnectionError) def test_timeout(self): """Checks that using a very small timeout prevents connection.""" billboard.ChartData('hot-100', timeout=1e-9) @raises(billboard.BillboardNotFoundException) def test_non_existent_chart(self): """Checks that requesting a non-existent chart fails.""" billboard.ChartData('does-not-exist') def test_unicode(self): """Checks that the Billboard website does not use Unicode characters.""" chart = billboard.ChartData('hot-100', date='2018-01-27') self.assertEqual(chart[97].title, six.text_type( 'El Bano')) # With Unicode this should be "El Baño" def test_difficult_title_casing(self): """Checks that a difficult chart title receives proper casing.""" chart = billboard.ChartData('greatest-r-b-hip-hop-songs') self.assertEqual(chart.title, 'Greatest of All Time Hot R&B/Hip-Hop Songs') def test_charts(self): """Checks that the function for listing all charts returns reasonable results.""" charts = billboard.charts() self.assertTrue('hot-100' in charts) self.assertTrue(200 <= len(charts) <= 400)
Add test for tests function
Add test for tests function
Python
mit
guoguo12/billboard-charts,guoguo12/billboard-charts
python
## Code Before: import billboard import unittest from nose.tools import raises from requests.exceptions import ConnectionError import six class MiscTest(unittest.TestCase): @raises(ConnectionError) def test_timeout(self): """Checks that using a very small timeout prevents connection.""" billboard.ChartData('hot-100', timeout=1e-9) @raises(billboard.BillboardNotFoundException) def test_non_existent_chart(self): """Checks that requesting a non-existent chart fails.""" billboard.ChartData('does-not-exist') def test_unicode(self): """Checks that the Billboard website does not use Unicode characters.""" chart = billboard.ChartData('hot-100', date='2018-01-27') self.assertEqual(chart[97].title, six.text_type( 'El Bano')) # With Unicode this should be "El Baño" def test_difficult_title_casing(self): """Checks that a difficult chart title receives proper casing.""" chart = billboard.ChartData('greatest-r-b-hip-hop-songs') self.assertEqual(chart.title, 'Greatest of All Time Hot R&B/Hip-Hop Songs') ## Instruction: Add test for tests function ## Code After: import billboard import unittest from nose.tools import raises from requests.exceptions import ConnectionError import six class MiscTest(unittest.TestCase): @raises(ConnectionError) def test_timeout(self): """Checks that using a very small timeout prevents connection.""" billboard.ChartData('hot-100', timeout=1e-9) @raises(billboard.BillboardNotFoundException) def test_non_existent_chart(self): """Checks that requesting a non-existent chart fails.""" billboard.ChartData('does-not-exist') def test_unicode(self): """Checks that the Billboard website does not use Unicode characters.""" chart = billboard.ChartData('hot-100', date='2018-01-27') self.assertEqual(chart[97].title, six.text_type( 'El Bano')) # With Unicode this should be "El Baño" def test_difficult_title_casing(self): """Checks that a difficult chart title receives proper casing.""" chart = billboard.ChartData('greatest-r-b-hip-hop-songs') self.assertEqual(chart.title, 'Greatest of All Time Hot R&B/Hip-Hop Songs') def test_charts(self): """Checks that the function for listing all charts returns reasonable results.""" charts = billboard.charts() self.assertTrue('hot-100' in charts) self.assertTrue(200 <= len(charts) <= 400)
# ... existing code ... chart = billboard.ChartData('hot-100', date='2018-01-27') self.assertEqual(chart[97].title, six.text_type( 'El Bano')) # With Unicode this should be "El Baño" def test_difficult_title_casing(self): """Checks that a difficult chart title receives proper casing.""" chart = billboard.ChartData('greatest-r-b-hip-hop-songs') # ... modified code ... self.assertEqual(chart.title, 'Greatest of All Time Hot R&B/Hip-Hop Songs') def test_charts(self): """Checks that the function for listing all charts returns reasonable results.""" charts = billboard.charts() self.assertTrue('hot-100' in charts) self.assertTrue(200 <= len(charts) <= 400) # ... rest of the code ...
c015d11303339f50254a10be7335fd33546911ab
modules/activiti-modeler/src/main/java/org/activiti/rest/editor/main/StencilsetRestResource.java
modules/activiti-modeler/src/main/java/org/activiti/rest/editor/main/StencilsetRestResource.java
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.rest.editor.main; import java.io.InputStream; import org.activiti.engine.ActivitiException; import org.apache.commons.io.IOUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** * @author Tijs Rademakers */ @RestController public class StencilsetRestResource { @RequestMapping(value="/editor/stencilset", method = RequestMethod.GET, produces = "application/json") public @ResponseBody String getStencilset() { InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json"); try { return IOUtils.toString(stencilsetStream); } catch (Exception e) { throw new ActivitiException("Error while loading stencil set", e); } } }
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.rest.editor.main; import java.io.InputStream; import org.activiti.engine.ActivitiException; import org.apache.commons.io.IOUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** * @author Tijs Rademakers */ @RestController public class StencilsetRestResource { @RequestMapping(value="/editor/stencilset", method = RequestMethod.GET, produces = "application/json;charset=utf-8") public @ResponseBody String getStencilset() { InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json"); try { return IOUtils.toString(stencilsetStream, "utf-8"); } catch (Exception e) { throw new ActivitiException("Error while loading stencil set", e); } } }
Fix read stencilset.json gibberish when in other languages
Fix read stencilset.json gibberish when in other languages
Java
apache-2.0
yvoswillens/flowable-engine,lsmall/flowable-engine,lsmall/flowable-engine,robsoncardosoti/flowable-engine,marcus-nl/flowable-engine,gro-mar/flowable-engine,dbmalkovsky/flowable-engine,sibok666/flowable-engine,yvoswillens/flowable-engine,flowable/flowable-engine,marcus-nl/flowable-engine,stefan-ziel/Activiti,flowable/flowable-engine,stephraleigh/flowable-engine,lsmall/flowable-engine,robsoncardosoti/flowable-engine,dbmalkovsky/flowable-engine,stephraleigh/flowable-engine,gro-mar/flowable-engine,Activiti/Activiti,lsmall/flowable-engine,yvoswillens/flowable-engine,sibok666/flowable-engine,martin-grofcik/flowable-engine,gro-mar/flowable-engine,marcus-nl/flowable-engine,roberthafner/flowable-engine,robsoncardosoti/flowable-engine,paulstapleton/flowable-engine,sibok666/flowable-engine,dbmalkovsky/flowable-engine,stefan-ziel/Activiti,paulstapleton/flowable-engine,dbmalkovsky/flowable-engine,sibok666/flowable-engine,gro-mar/flowable-engine,motorina0/flowable-engine,stephraleigh/flowable-engine,zwets/flowable-engine,paulstapleton/flowable-engine,roberthafner/flowable-engine,marcus-nl/flowable-engine,paulstapleton/flowable-engine,zwets/flowable-engine,zwets/flowable-engine,motorina0/flowable-engine,motorina0/flowable-engine,yvoswillens/flowable-engine,martin-grofcik/flowable-engine,roberthafner/flowable-engine,martin-grofcik/flowable-engine,flowable/flowable-engine,Activiti/Activiti,flowable/flowable-engine,stephraleigh/flowable-engine,zwets/flowable-engine,stefan-ziel/Activiti,roberthafner/flowable-engine,robsoncardosoti/flowable-engine,motorina0/flowable-engine,stefan-ziel/Activiti,martin-grofcik/flowable-engine
java
## Code Before: /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.rest.editor.main; import java.io.InputStream; import org.activiti.engine.ActivitiException; import org.apache.commons.io.IOUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** * @author Tijs Rademakers */ @RestController public class StencilsetRestResource { @RequestMapping(value="/editor/stencilset", method = RequestMethod.GET, produces = "application/json") public @ResponseBody String getStencilset() { InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json"); try { return IOUtils.toString(stencilsetStream); } catch (Exception e) { throw new ActivitiException("Error while loading stencil set", e); } } } ## Instruction: Fix read stencilset.json gibberish when in other languages ## Code After: /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.rest.editor.main; import java.io.InputStream; import org.activiti.engine.ActivitiException; import org.apache.commons.io.IOUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** * @author Tijs Rademakers */ @RestController public class StencilsetRestResource { @RequestMapping(value="/editor/stencilset", method = RequestMethod.GET, produces = "application/json;charset=utf-8") public @ResponseBody String getStencilset() { InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json"); try { return IOUtils.toString(stencilsetStream, "utf-8"); } catch (Exception e) { throw new ActivitiException("Error while loading stencil set", e); } } }
... @RestController public class StencilsetRestResource { @RequestMapping(value="/editor/stencilset", method = RequestMethod.GET, produces = "application/json;charset=utf-8") public @ResponseBody String getStencilset() { InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json"); try { return IOUtils.toString(stencilsetStream, "utf-8"); } catch (Exception e) { throw new ActivitiException("Error while loading stencil set", e); } ...
d01b09256f8fda4b222f3e26366817f4ac5b4c5a
zinnia/tests/test_admin_forms.py
zinnia/tests/test_admin_forms.py
"""Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) def test_initial_sites(self): form = EntryAdminForm() self.assertEqual( len(form.fields['sites'].initial), 1) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid())
"""Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid())
Remove now useless test for initial sites value in form
Remove now useless test for initial sites value in form
Python
bsd-3-clause
extertioner/django-blog-zinnia,Maplecroft/django-blog-zinnia,Zopieux/django-blog-zinnia,ghachey/django-blog-zinnia,dapeng0802/django-blog-zinnia,bywbilly/django-blog-zinnia,dapeng0802/django-blog-zinnia,Zopieux/django-blog-zinnia,aorzh/django-blog-zinnia,Zopieux/django-blog-zinnia,bywbilly/django-blog-zinnia,aorzh/django-blog-zinnia,aorzh/django-blog-zinnia,extertioner/django-blog-zinnia,ZuluPro/django-blog-zinnia,petecummings/django-blog-zinnia,Fantomas42/django-blog-zinnia,marctc/django-blog-zinnia,petecummings/django-blog-zinnia,ZuluPro/django-blog-zinnia,ZuluPro/django-blog-zinnia,Fantomas42/django-blog-zinnia,ghachey/django-blog-zinnia,Maplecroft/django-blog-zinnia,petecummings/django-blog-zinnia,marctc/django-blog-zinnia,bywbilly/django-blog-zinnia,extertioner/django-blog-zinnia,Maplecroft/django-blog-zinnia,Fantomas42/django-blog-zinnia,ghachey/django-blog-zinnia,dapeng0802/django-blog-zinnia,marctc/django-blog-zinnia
python
## Code Before: """Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) def test_initial_sites(self): form = EntryAdminForm() self.assertEqual( len(form.fields['sites'].initial), 1) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid()) ## Instruction: Remove now useless test for initial sites value in form ## Code After: """Test cases for Zinnia's admin forms""" from django.test import TestCase from django.contrib.admin.widgets import RelatedFieldWidgetWrapper from zinnia.models import Category from zinnia.admin.forms import EntryAdminForm from zinnia.admin.forms import CategoryAdminForm class EntryAdminFormTestCase(TestCase): def test_categories_has_related_widget(self): form = EntryAdminForm() self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) class CategoryAdminFormTestCase(TestCase): def test_parent_has_related_widget(self): form = CategoryAdminForm() self.assertTrue( isinstance(form.fields['parent'].widget, RelatedFieldWidgetWrapper)) def test_clean_parent(self): category = Category.objects.create( title='Category 1', slug='cat-1') datas = {'parent': category.pk, 'title': category.title, 'slug': category.slug} form = CategoryAdminForm(datas, instance=category) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors['parent']), 1) subcategory = Category.objects.create( title='Category 2', slug='cat-2') self.assertEqual(subcategory.parent, None) datas = {'parent': category.pk, 'title': subcategory.title, 'slug': subcategory.slug} form = CategoryAdminForm(datas, instance=subcategory) self.assertTrue(form.is_valid())
# ... existing code ... self.assertTrue( isinstance(form.fields['categories'].widget, RelatedFieldWidgetWrapper)) class CategoryAdminFormTestCase(TestCase): # ... rest of the code ...
ce111bb421052a813c00feb7fe278499700a4136
src/pro/java/com/antew/redditinpictures/ApplicationModulePro.java
src/pro/java/com/antew/redditinpictures/ApplicationModulePro.java
package com.antew.redditinpictures; import com.antew.redditinpictures.library.ui.ImageDetailActivity; import com.antew.redditinpictures.library.ui.ImageDetailFragment; import com.antew.redditinpictures.library.ui.ImageGridActivity; import com.antew.redditinpictures.library.ui.ImageGridFragment; import com.antew.redditinpictures.library.ui.ImageListFragment; import com.antew.redditinpictures.library.ui.ImgurAlbumActivity; import com.antew.redditinpictures.library.ui.RedditFragmentActivity; import com.antew.redditinpictures.library.ui.RedditImageGridFragment; import com.antew.redditinpictures.library.ui.RedditImageListFragment; import dagger.Module; @Module( complete = false, overrides = true, injects = { ImageGridFragment.class, ImageListFragment.class, ImageGridActivity.class, ImageDetailActivity.class, ImageDetailFragment.class, ImgurAlbumActivity.class, RedditFragmentActivity.class, RedditImageListFragment.class, RedditImageGridFragment.class, }, library = true ) public class ApplicationModulePro { }
package com.antew.redditinpictures; import com.antew.redditinpictures.library.ui.ImageDetailActivity; import com.antew.redditinpictures.library.ui.ImageDetailFragment; import com.antew.redditinpictures.library.ui.ImageGridActivity; import com.antew.redditinpictures.library.ui.ImageGridFragment; import com.antew.redditinpictures.library.ui.ImageListFragment; import com.antew.redditinpictures.library.ui.ImgurAlbumActivity; import com.antew.redditinpictures.library.ui.ImgurAlbumFragment; import com.antew.redditinpictures.library.ui.RedditFragmentActivity; import com.antew.redditinpictures.library.ui.RedditImageGridFragment; import com.antew.redditinpictures.library.ui.RedditImageListFragment; import dagger.Module; @Module( complete = false, overrides = true, injects = { ImageGridFragment.class, ImageListFragment.class, ImageGridActivity.class, ImageDetailActivity.class, ImageDetailFragment.class, ImgurAlbumActivity.class, RedditFragmentActivity.class, RedditImageListFragment.class, RedditImageGridFragment.class, ImgurAlbumFragment.class, }, library = true ) public class ApplicationModulePro { }
Fix galleries crashing due to missing injection declaration.
Fix galleries crashing due to missing injection declaration.
Java
apache-2.0
antew/RedditInPictures
java
## Code Before: package com.antew.redditinpictures; import com.antew.redditinpictures.library.ui.ImageDetailActivity; import com.antew.redditinpictures.library.ui.ImageDetailFragment; import com.antew.redditinpictures.library.ui.ImageGridActivity; import com.antew.redditinpictures.library.ui.ImageGridFragment; import com.antew.redditinpictures.library.ui.ImageListFragment; import com.antew.redditinpictures.library.ui.ImgurAlbumActivity; import com.antew.redditinpictures.library.ui.RedditFragmentActivity; import com.antew.redditinpictures.library.ui.RedditImageGridFragment; import com.antew.redditinpictures.library.ui.RedditImageListFragment; import dagger.Module; @Module( complete = false, overrides = true, injects = { ImageGridFragment.class, ImageListFragment.class, ImageGridActivity.class, ImageDetailActivity.class, ImageDetailFragment.class, ImgurAlbumActivity.class, RedditFragmentActivity.class, RedditImageListFragment.class, RedditImageGridFragment.class, }, library = true ) public class ApplicationModulePro { } ## Instruction: Fix galleries crashing due to missing injection declaration. ## Code After: package com.antew.redditinpictures; import com.antew.redditinpictures.library.ui.ImageDetailActivity; import com.antew.redditinpictures.library.ui.ImageDetailFragment; import com.antew.redditinpictures.library.ui.ImageGridActivity; import com.antew.redditinpictures.library.ui.ImageGridFragment; import com.antew.redditinpictures.library.ui.ImageListFragment; import com.antew.redditinpictures.library.ui.ImgurAlbumActivity; import com.antew.redditinpictures.library.ui.ImgurAlbumFragment; import com.antew.redditinpictures.library.ui.RedditFragmentActivity; import com.antew.redditinpictures.library.ui.RedditImageGridFragment; import com.antew.redditinpictures.library.ui.RedditImageListFragment; import dagger.Module; @Module( complete = false, overrides = true, injects = { ImageGridFragment.class, ImageListFragment.class, ImageGridActivity.class, ImageDetailActivity.class, ImageDetailFragment.class, ImgurAlbumActivity.class, RedditFragmentActivity.class, RedditImageListFragment.class, RedditImageGridFragment.class, ImgurAlbumFragment.class, }, library = true ) public class ApplicationModulePro { }
... import com.antew.redditinpictures.library.ui.ImageGridFragment; import com.antew.redditinpictures.library.ui.ImageListFragment; import com.antew.redditinpictures.library.ui.ImgurAlbumActivity; import com.antew.redditinpictures.library.ui.ImgurAlbumFragment; import com.antew.redditinpictures.library.ui.RedditFragmentActivity; import com.antew.redditinpictures.library.ui.RedditImageGridFragment; import com.antew.redditinpictures.library.ui.RedditImageListFragment; ... ImageGridFragment.class, ImageListFragment.class, ImageGridActivity.class, ImageDetailActivity.class, ImageDetailFragment.class, ImgurAlbumActivity.class, RedditFragmentActivity.class, RedditImageListFragment.class, RedditImageGridFragment.class, ImgurAlbumFragment.class, }, library = true ) public class ApplicationModulePro { ...
3784b04109b2ca92633a788cc02562898064282c
factor.py
factor.py
import numpy as np def LU(A): m = A.shape[0] U = A.copy() L = np.eye( m ) for j in range(m): for i in range(j+1,m): L[i,j] = U[i,j]/U[j,j] U[i,:] -= L[i,j]*U[j,:] return L, U
import numpy as np def LU(A): r"""Factor a square matrix by Gaussian elimination. The argument A should be a square matrix (an m-by-m numpy array). The outputs L and U are also m-by-m. L is lower-triangular with unit diagonal entries and U is strictly upper-triangular. This implementation does not use pivoting and can be unstable for moderately large matrices, due to amplification of roundoff errors. See, e.g., Lectures 20-22 of the book by Trefethen & Bau for a discussion. Example:: >>> import factor >>> import numpy as np >>> A = np.array([[2.,1.,1.,0.],[4.,3.,3.,1.],[8.,7.,9.,5.],[6.,7.,9.,8.]]) >>> print A [[ 2. 1. 1. 0.] [ 4. 3. 3. 1.] [ 8. 7. 9. 5.] [ 6. 7. 9. 8.]] >>> L, U = factor.LU(A) >>> print L [[ 1. 0. 0. 0.] [ 2. 1. 0. 0.] [ 4. 3. 1. 0.] [ 3. 4. 1. 1.]] >>> print U [[ 2. 1. 1. 0.] [ 0. 1. 1. 1.] [ 0. 0. 2. 2.] [ 0. 0. 0. 2.]] """ m = A.shape[0] U = A.copy() L = np.eye( m ) for j in range(m): for i in range(j+1,m): L[i,j] = U[i,j]/U[j,j] U[i,:] -= L[i,j]*U[j,:] return L, U
Add docstring, with an example.
Add docstring, with an example.
Python
bsd-2-clause
ketch/rock-solid-code-demo
python
## Code Before: import numpy as np def LU(A): m = A.shape[0] U = A.copy() L = np.eye( m ) for j in range(m): for i in range(j+1,m): L[i,j] = U[i,j]/U[j,j] U[i,:] -= L[i,j]*U[j,:] return L, U ## Instruction: Add docstring, with an example. ## Code After: import numpy as np def LU(A): r"""Factor a square matrix by Gaussian elimination. The argument A should be a square matrix (an m-by-m numpy array). The outputs L and U are also m-by-m. L is lower-triangular with unit diagonal entries and U is strictly upper-triangular. This implementation does not use pivoting and can be unstable for moderately large matrices, due to amplification of roundoff errors. See, e.g., Lectures 20-22 of the book by Trefethen & Bau for a discussion. Example:: >>> import factor >>> import numpy as np >>> A = np.array([[2.,1.,1.,0.],[4.,3.,3.,1.],[8.,7.,9.,5.],[6.,7.,9.,8.]]) >>> print A [[ 2. 1. 1. 0.] [ 4. 3. 3. 1.] [ 8. 7. 9. 5.] [ 6. 7. 9. 8.]] >>> L, U = factor.LU(A) >>> print L [[ 1. 0. 0. 0.] [ 2. 1. 0. 0.] [ 4. 3. 1. 0.] [ 3. 4. 1. 1.]] >>> print U [[ 2. 1. 1. 0.] [ 0. 1. 1. 1.] [ 0. 0. 2. 2.] [ 0. 0. 0. 2.]] """ m = A.shape[0] U = A.copy() L = np.eye( m ) for j in range(m): for i in range(j+1,m): L[i,j] = U[i,j]/U[j,j] U[i,:] -= L[i,j]*U[j,:] return L, U
# ... existing code ... import numpy as np def LU(A): r"""Factor a square matrix by Gaussian elimination. The argument A should be a square matrix (an m-by-m numpy array). The outputs L and U are also m-by-m. L is lower-triangular with unit diagonal entries and U is strictly upper-triangular. This implementation does not use pivoting and can be unstable for moderately large matrices, due to amplification of roundoff errors. See, e.g., Lectures 20-22 of the book by Trefethen & Bau for a discussion. Example:: >>> import factor >>> import numpy as np >>> A = np.array([[2.,1.,1.,0.],[4.,3.,3.,1.],[8.,7.,9.,5.],[6.,7.,9.,8.]]) >>> print A [[ 2. 1. 1. 0.] [ 4. 3. 3. 1.] [ 8. 7. 9. 5.] [ 6. 7. 9. 8.]] >>> L, U = factor.LU(A) >>> print L [[ 1. 0. 0. 0.] [ 2. 1. 0. 0.] [ 4. 3. 1. 0.] [ 3. 4. 1. 1.]] >>> print U [[ 2. 1. 1. 0.] [ 0. 1. 1. 1.] [ 0. 0. 2. 2.] [ 0. 0. 0. 2.]] """ m = A.shape[0] U = A.copy() L = np.eye( m ) # ... rest of the code ...
393743e391575d6cf4a3bfffb4f53cfa0848c49e
tests/test_donemail.py
tests/test_donemail.py
from mock import Mock import pytest import smtplib from donemail import donemail BOB = '[email protected]' @pytest.fixture(autouse=True) def monkeypatch_send_email(monkeypatch): monkeypatch.setattr('smtplib.SMTP', Mock()) def test_context_manager(): assert_num_emails(0) with donemail(BOB): pass assert_num_emails(1) def assert_num_emails(expected_num_emails): assert smtplib.SMTP.return_value.sendmail.call_count == expected_num_emails def test_decorator(): @donemail(BOB) def add(x, y): return x + y assert_num_emails(0) add(1, y=2) assert_num_emails(1) def test_context_manager_with_exception(): assert_num_emails(0) with pytest.raises(ZeroDivisionError): with donemail(BOB): 1 / 0 assert_num_emails(1) def test_decorator_with_exception(): @donemail(BOB) def divide(x, y): return x / y assert_num_emails(0) with pytest.raises(ZeroDivisionError): divide(1, 0) assert_num_emails(1)
from mock import ANY, Mock import pytest import smtplib from donemail import donemail BOB = '[email protected]' @pytest.fixture(autouse=True) def monkeypatch_send_email(monkeypatch): mock_smtp_class = Mock() mock_smtp_class.return_value = Mock() monkeypatch.setattr('smtplib.SMTP', mock_smtp_class) def test_context_manager(): assert_num_emails(0) with donemail(BOB): pass assert_sent_email(ANY, [BOB], ANY) def assert_num_emails(expected_num_emails): assert get_mock_smtp().sendmail.call_count == expected_num_emails def assert_sent_email(from_addr, to_addrs, msg): get_mock_smtp().sendmail.assert_called_once_with(from_addr, to_addrs, msg) def get_mock_smtp(): return smtplib.SMTP() def test_decorator(): @donemail(BOB) def add(x, y): return x + y assert_num_emails(0) add(1, y=2) assert_sent_email(ANY, [BOB], ANY) def test_context_manager_with_exception(): assert_num_emails(0) with pytest.raises(ZeroDivisionError): with donemail(BOB): 1 / 0 assert_sent_email(ANY, [BOB], ANY) def test_decorator_with_exception(): @donemail(BOB) def divide(x, y): return x / y assert_num_emails(0) with pytest.raises(ZeroDivisionError): divide(1, 0) assert_sent_email(ANY, [BOB], ANY)
Check that test emails are sent to BOB
Check that test emails are sent to BOB
Python
mit
alexandershov/donemail
python
## Code Before: from mock import Mock import pytest import smtplib from donemail import donemail BOB = '[email protected]' @pytest.fixture(autouse=True) def monkeypatch_send_email(monkeypatch): monkeypatch.setattr('smtplib.SMTP', Mock()) def test_context_manager(): assert_num_emails(0) with donemail(BOB): pass assert_num_emails(1) def assert_num_emails(expected_num_emails): assert smtplib.SMTP.return_value.sendmail.call_count == expected_num_emails def test_decorator(): @donemail(BOB) def add(x, y): return x + y assert_num_emails(0) add(1, y=2) assert_num_emails(1) def test_context_manager_with_exception(): assert_num_emails(0) with pytest.raises(ZeroDivisionError): with donemail(BOB): 1 / 0 assert_num_emails(1) def test_decorator_with_exception(): @donemail(BOB) def divide(x, y): return x / y assert_num_emails(0) with pytest.raises(ZeroDivisionError): divide(1, 0) assert_num_emails(1) ## Instruction: Check that test emails are sent to BOB ## Code After: from mock import ANY, Mock import pytest import smtplib from donemail import donemail BOB = '[email protected]' @pytest.fixture(autouse=True) def monkeypatch_send_email(monkeypatch): mock_smtp_class = Mock() mock_smtp_class.return_value = Mock() monkeypatch.setattr('smtplib.SMTP', mock_smtp_class) def test_context_manager(): assert_num_emails(0) with donemail(BOB): pass assert_sent_email(ANY, [BOB], ANY) def assert_num_emails(expected_num_emails): assert get_mock_smtp().sendmail.call_count == expected_num_emails def assert_sent_email(from_addr, to_addrs, msg): get_mock_smtp().sendmail.assert_called_once_with(from_addr, to_addrs, msg) def get_mock_smtp(): return smtplib.SMTP() def test_decorator(): @donemail(BOB) def add(x, y): return x + y assert_num_emails(0) add(1, y=2) assert_sent_email(ANY, [BOB], ANY) def test_context_manager_with_exception(): assert_num_emails(0) with pytest.raises(ZeroDivisionError): with donemail(BOB): 1 / 0 assert_sent_email(ANY, [BOB], ANY) def test_decorator_with_exception(): @donemail(BOB) def divide(x, y): return x / y assert_num_emails(0) with pytest.raises(ZeroDivisionError): divide(1, 0) assert_sent_email(ANY, [BOB], ANY)
... from mock import ANY, Mock import pytest import smtplib ... @pytest.fixture(autouse=True) def monkeypatch_send_email(monkeypatch): mock_smtp_class = Mock() mock_smtp_class.return_value = Mock() monkeypatch.setattr('smtplib.SMTP', mock_smtp_class) def test_context_manager(): ... assert_num_emails(0) with donemail(BOB): pass assert_sent_email(ANY, [BOB], ANY) def assert_num_emails(expected_num_emails): assert get_mock_smtp().sendmail.call_count == expected_num_emails def assert_sent_email(from_addr, to_addrs, msg): get_mock_smtp().sendmail.assert_called_once_with(from_addr, to_addrs, msg) def get_mock_smtp(): return smtplib.SMTP() def test_decorator(): ... assert_num_emails(0) add(1, y=2) assert_sent_email(ANY, [BOB], ANY) def test_context_manager_with_exception(): ... with pytest.raises(ZeroDivisionError): with donemail(BOB): 1 / 0 assert_sent_email(ANY, [BOB], ANY) def test_decorator_with_exception(): ... assert_num_emails(0) with pytest.raises(ZeroDivisionError): divide(1, 0) assert_sent_email(ANY, [BOB], ANY) ...
d792679461357fa17b1f852d7a72921aed2fe271
bermann/rdd_test.py
bermann/rdd_test.py
import unittest from bermann import RDD class TestRDD(unittest.TestCase): def test_cache_is_noop(self): rdd = RDD([1, 2, 3]) cached = rdd.cache() self.assertEqual(rdd, cached) # collect # count # countByKey # conntByValue # distinct # filter # first # flatMap # flatMapValues # foreach # groupBy # groupByKey # isEmpty # keyBy # keys # map # mapValues # max # min # name if __name__ == '__main__': unittest.main()
import unittest from bermann import RDD class TestRDD(unittest.TestCase): def test_cache_is_noop(self): rdd = RDD([1, 2, 3]) cached = rdd.cache() self.assertEqual(rdd, cached) def test_collect_empty_rdd_returns_empty_list(self): rdd = RDD() self.assertEqual([], rdd.collect()) def test_collect_non_empty_rdd_returns_contents(self): rdd = RDD([1, 2, 3]) self.assertEqual(rdd.contents, rdd.collect()) def test_count_empty_rdd_returns_zero(self): rdd = RDD() self.assertEqual(0, rdd.count()) def test_collect_non_empty_rdd_returns_length(self): rdd = RDD([1, 2, 3]) self.assertEqual(3, rdd.count()) # countByKey # conntByValue # distinct # filter # first # flatMap # flatMapValues # foreach # groupBy # groupByKey # isEmpty # keyBy # keys # map # mapValues # max # min # name if __name__ == '__main__': unittest.main()
Add tests for count and collect
Add tests for count and collect
Python
mit
oli-hall/bermann
python
## Code Before: import unittest from bermann import RDD class TestRDD(unittest.TestCase): def test_cache_is_noop(self): rdd = RDD([1, 2, 3]) cached = rdd.cache() self.assertEqual(rdd, cached) # collect # count # countByKey # conntByValue # distinct # filter # first # flatMap # flatMapValues # foreach # groupBy # groupByKey # isEmpty # keyBy # keys # map # mapValues # max # min # name if __name__ == '__main__': unittest.main() ## Instruction: Add tests for count and collect ## Code After: import unittest from bermann import RDD class TestRDD(unittest.TestCase): def test_cache_is_noop(self): rdd = RDD([1, 2, 3]) cached = rdd.cache() self.assertEqual(rdd, cached) def test_collect_empty_rdd_returns_empty_list(self): rdd = RDD() self.assertEqual([], rdd.collect()) def test_collect_non_empty_rdd_returns_contents(self): rdd = RDD([1, 2, 3]) self.assertEqual(rdd.contents, rdd.collect()) def test_count_empty_rdd_returns_zero(self): rdd = RDD() self.assertEqual(0, rdd.count()) def test_collect_non_empty_rdd_returns_length(self): rdd = RDD([1, 2, 3]) self.assertEqual(3, rdd.count()) # countByKey # conntByValue # distinct # filter # first # flatMap # flatMapValues # foreach # groupBy # groupByKey # isEmpty # keyBy # keys # map # mapValues # max # min # name if __name__ == '__main__': unittest.main()
// ... existing code ... self.assertEqual(rdd, cached) def test_collect_empty_rdd_returns_empty_list(self): rdd = RDD() self.assertEqual([], rdd.collect()) def test_collect_non_empty_rdd_returns_contents(self): rdd = RDD([1, 2, 3]) self.assertEqual(rdd.contents, rdd.collect()) def test_count_empty_rdd_returns_zero(self): rdd = RDD() self.assertEqual(0, rdd.count()) def test_collect_non_empty_rdd_returns_length(self): rdd = RDD([1, 2, 3]) self.assertEqual(3, rdd.count()) # countByKey // ... rest of the code ...
0a13a9a8a779102dbcb2beead7d8aa9143f4c79b
tests/pytests/unit/client/ssh/test_shell.py
tests/pytests/unit/client/ssh/test_shell.py
import os import subprocess import pytest import salt.client.ssh.shell as shell @pytest.fixture def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" yield {"pub_key": str(pub_key), "priv_key": str(priv_key)} @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) class TestSSHShell: def test_ssh_shell_key_gen(self, keys): """ Test ssh key_gen """ shell.gen_key(keys["priv_key"]) for fp in keys.keys(): assert os.path.exists(keys[fp]) # verify there is not a passphrase set on key ret = subprocess.check_output( ["ssh-keygen", "-f", keys["priv_key"], "-y"], timeout=30, ) assert ret.decode().startswith("ssh-rsa")
import subprocess import types import pytest import salt.client.ssh.shell as shell @pytest.fixture def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" return types.SimpleNamespace(pub_key=pub_key, priv_key=priv_key) @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) def test_ssh_shell_key_gen(keys): """ Test ssh key_gen """ shell.gen_key(str(keys.priv_key)) assert keys.priv_key.exists() assert keys.pub_key.exists() # verify there is not a passphrase set on key ret = subprocess.check_output( ["ssh-keygen", "-f", str(keys.priv_key), "-y"], timeout=30, ) assert ret.decode().startswith("ssh-rsa")
Use commit suggestion to use types
Use commit suggestion to use types Co-authored-by: Pedro Algarvio <[email protected]>
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
python
## Code Before: import os import subprocess import pytest import salt.client.ssh.shell as shell @pytest.fixture def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" yield {"pub_key": str(pub_key), "priv_key": str(priv_key)} @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) class TestSSHShell: def test_ssh_shell_key_gen(self, keys): """ Test ssh key_gen """ shell.gen_key(keys["priv_key"]) for fp in keys.keys(): assert os.path.exists(keys[fp]) # verify there is not a passphrase set on key ret = subprocess.check_output( ["ssh-keygen", "-f", keys["priv_key"], "-y"], timeout=30, ) assert ret.decode().startswith("ssh-rsa") ## Instruction: Use commit suggestion to use types Co-authored-by: Pedro Algarvio <[email protected]> ## Code After: import subprocess import types import pytest import salt.client.ssh.shell as shell @pytest.fixture def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" return types.SimpleNamespace(pub_key=pub_key, priv_key=priv_key) @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) def test_ssh_shell_key_gen(keys): """ Test ssh key_gen """ shell.gen_key(str(keys.priv_key)) assert keys.priv_key.exists() assert keys.pub_key.exists() # verify there is not a passphrase set on key ret = subprocess.check_output( ["ssh-keygen", "-f", str(keys.priv_key), "-y"], timeout=30, ) assert ret.decode().startswith("ssh-rsa")
... import subprocess import types import pytest import salt.client.ssh.shell as shell ... def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" return types.SimpleNamespace(pub_key=pub_key, priv_key=priv_key) @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) def test_ssh_shell_key_gen(keys): """ Test ssh key_gen """ shell.gen_key(str(keys.priv_key)) assert keys.priv_key.exists() assert keys.pub_key.exists() # verify there is not a passphrase set on key ret = subprocess.check_output( ["ssh-keygen", "-f", str(keys.priv_key), "-y"], timeout=30, ) assert ret.decode().startswith("ssh-rsa") ...
573f3fd726c7bf1495bfdfeb2201317abc2949e4
src/parser/menu_item.py
src/parser/menu_item.py
"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017""" class MenuItem: """ To store menu item information """ def __init__(self, txt, target, hidden): """ Constructor txt - Menu link text target - Can be several things -- Reference to another jahia page,using its uuid (like c058dc4f-247d-4b23-90d7-25e1206f7de3) -- hardcoded URL (absolute URL) -- link to sitemap (so equals 'sitemap') -- hardcoded URL to file (includes '/files/' in string) -- None if normal menu entry for page """ self.txt = txt self.target = target if self.target: self.target = self.target.strip() self.hidden = hidden self.children = [] self.children_sort_way = None def target_is_url(self): return False if self.target is None else self.target.startswith('http') def target_is_sitemap(self): return self.target == "sitemap" def target_is_file(self): return False if self.target is None else '/files/' in self.target def target_is_reference(self): # If it is not another possibility, it is a reference return not self.target_is_sitemap() and \ not self.target_is_url() and \ self.target is not None def sort_children(self, sort_way): self.children_sort_way = sort_way self.children.sort(key=lambda x: x.txt, reverse=(sort_way == 'desc'))
"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017""" class MenuItem: """ To store menu item information """ def __init__(self, txt, target, hidden): """ Constructor txt - Menu link text target - Can be several things -- Reference to another jahia page,using its uuid (like c058dc4f-247d-4b23-90d7-25e1206f7de3) -- hardcoded URL (absolute URL) -- link to sitemap (so equals 'sitemap') -- hardcoded URL to file (includes '/files/' in string) -- None if normal menu entry for page """ self.txt = txt self.target = target if self.target: self.target = self.target.strip() self.hidden = hidden self.children = [] self.children_sort_way = None def target_is_url(self): return False if self.target is None else self.target.startswith('http') def target_is_sitemap(self): return self.target == "sitemap" def target_is_file(self): return False if self.target is None else '/files/' in self.target def sort_children(self, sort_way): self.children_sort_way = sort_way self.children.sort(key=lambda x: x.txt, reverse=(sort_way == 'desc'))
Remove previously added method because finally not used...
Remove previously added method because finally not used...
Python
mit
epfl-idevelop/jahia2wp,epfl-idevelop/jahia2wp,epfl-idevelop/jahia2wp,epfl-idevelop/jahia2wp
python
## Code Before: """(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017""" class MenuItem: """ To store menu item information """ def __init__(self, txt, target, hidden): """ Constructor txt - Menu link text target - Can be several things -- Reference to another jahia page,using its uuid (like c058dc4f-247d-4b23-90d7-25e1206f7de3) -- hardcoded URL (absolute URL) -- link to sitemap (so equals 'sitemap') -- hardcoded URL to file (includes '/files/' in string) -- None if normal menu entry for page """ self.txt = txt self.target = target if self.target: self.target = self.target.strip() self.hidden = hidden self.children = [] self.children_sort_way = None def target_is_url(self): return False if self.target is None else self.target.startswith('http') def target_is_sitemap(self): return self.target == "sitemap" def target_is_file(self): return False if self.target is None else '/files/' in self.target def target_is_reference(self): # If it is not another possibility, it is a reference return not self.target_is_sitemap() and \ not self.target_is_url() and \ self.target is not None def sort_children(self, sort_way): self.children_sort_way = sort_way self.children.sort(key=lambda x: x.txt, reverse=(sort_way == 'desc')) ## Instruction: Remove previously added method because finally not used... ## Code After: """(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017""" class MenuItem: """ To store menu item information """ def __init__(self, txt, target, hidden): """ Constructor txt - Menu link text target - Can be several things -- Reference to another jahia page,using its uuid (like c058dc4f-247d-4b23-90d7-25e1206f7de3) -- hardcoded URL (absolute URL) -- link to sitemap (so equals 'sitemap') -- hardcoded URL to file (includes '/files/' in string) -- None if normal menu entry for page """ self.txt = txt self.target = target if self.target: self.target = self.target.strip() self.hidden = hidden self.children = [] self.children_sort_way = None def target_is_url(self): return False if self.target is None else self.target.startswith('http') def target_is_sitemap(self): return self.target == "sitemap" def target_is_file(self): return False if self.target is None else '/files/' in self.target def sort_children(self, sort_way): self.children_sort_way = sort_way self.children.sort(key=lambda x: x.txt, reverse=(sort_way == 'desc'))
// ... existing code ... def target_is_file(self): return False if self.target is None else '/files/' in self.target def sort_children(self, sort_way): self.children_sort_way = sort_way self.children.sort(key=lambda x: x.txt, reverse=(sort_way == 'desc')) // ... rest of the code ...
a6a8141bcc40ac124a0425a63594578538852a02
linter.py
linter.py
"""This module exports the jscs plugin class.""" from SublimeLinter.lint import Linter class Jscs(Linter): """Provides an interface to jscs.""" syntax = ('javascript', 'html', 'html 5') cmd = 'jscs -r checkstyle' config_file = ('-c', '.jscs.json') regex = ( r'^\s+?<error line="(?P<line>\d+)" ' r'column="(?P<col>\d+)" ' # jscs always reports with error severity; show as warning r'severity="(?P<warning>error)" ' r'message="(?P<message>.+?)"' ) multiline = True selectors = {'html': 'source.js.embedded.html'} tempfile_suffix = 'js'
"""This module exports the jscs plugin class.""" from SublimeLinter.lint import Linter class Jscs(Linter): """Provides an interface to jscs.""" syntax = ('javascript', 'html', 'html 5') cmd = 'jscs -r checkstyle' regex = ( r'^\s+?<error line="(?P<line>\d+)" ' r'column="(?P<col>\d+)" ' # jscs always reports with error severity; show as warning r'severity="(?P<warning>error)" ' r'message="(?P<message>.+?)"' ) multiline = True selectors = {'html': 'source.js.embedded.html'} tempfile_suffix = 'js' config_file = ('--config', '.jscs.json', '~')
Use the full option name for clarity and also search in the user's home directory
Use the full option name for clarity and also search in the user's home directory
Python
mit
roberthoog/SublimeLinter-jscs,SublimeLinter/SublimeLinter-jscs
python
## Code Before: """This module exports the jscs plugin class.""" from SublimeLinter.lint import Linter class Jscs(Linter): """Provides an interface to jscs.""" syntax = ('javascript', 'html', 'html 5') cmd = 'jscs -r checkstyle' config_file = ('-c', '.jscs.json') regex = ( r'^\s+?<error line="(?P<line>\d+)" ' r'column="(?P<col>\d+)" ' # jscs always reports with error severity; show as warning r'severity="(?P<warning>error)" ' r'message="(?P<message>.+?)"' ) multiline = True selectors = {'html': 'source.js.embedded.html'} tempfile_suffix = 'js' ## Instruction: Use the full option name for clarity and also search in the user's home directory ## Code After: """This module exports the jscs plugin class.""" from SublimeLinter.lint import Linter class Jscs(Linter): """Provides an interface to jscs.""" syntax = ('javascript', 'html', 'html 5') cmd = 'jscs -r checkstyle' regex = ( r'^\s+?<error line="(?P<line>\d+)" ' r'column="(?P<col>\d+)" ' # jscs always reports with error severity; show as warning r'severity="(?P<warning>error)" ' r'message="(?P<message>.+?)"' ) multiline = True selectors = {'html': 'source.js.embedded.html'} tempfile_suffix = 'js' config_file = ('--config', '.jscs.json', '~')
... syntax = ('javascript', 'html', 'html 5') cmd = 'jscs -r checkstyle' regex = ( r'^\s+?<error line="(?P<line>\d+)" ' r'column="(?P<col>\d+)" ' ... multiline = True selectors = {'html': 'source.js.embedded.html'} tempfile_suffix = 'js' config_file = ('--config', '.jscs.json', '~') ...
0aa3af24533a0aa605d05bd034a0bfdcc55c2993
backend/conferences/types.py
backend/conferences/types.py
import graphene from .models import Conference from graphene_django import DjangoObjectType from tickets.types import TicketType class ConferenceType(DjangoObjectType): tickets = graphene.List(graphene.NonNull(TicketType)) def resolve_tickets(self, info): return self.tickets.all() class Meta: model = Conference only_fields = ('id', 'start', 'end', 'name', 'slug')
import graphene from .models import Conference from graphene_django import DjangoObjectType from tickets.types import TicketType class ConferenceType(DjangoObjectType): tickets = graphene.List(graphene.NonNull(TicketType)) def resolve_tickets(self, info): return self.tickets.all() class Meta: model = Conference only_fields = ( 'id', 'name', 'slug', 'start', 'end', 'cfp_start', 'cfp_end', 'voting_start', 'voting_end', 'refund_start', 'refund_end' )
Add dates to Conference GraphQL type
Add dates to Conference GraphQL type
Python
mit
patrick91/pycon,patrick91/pycon
python
## Code Before: import graphene from .models import Conference from graphene_django import DjangoObjectType from tickets.types import TicketType class ConferenceType(DjangoObjectType): tickets = graphene.List(graphene.NonNull(TicketType)) def resolve_tickets(self, info): return self.tickets.all() class Meta: model = Conference only_fields = ('id', 'start', 'end', 'name', 'slug') ## Instruction: Add dates to Conference GraphQL type ## Code After: import graphene from .models import Conference from graphene_django import DjangoObjectType from tickets.types import TicketType class ConferenceType(DjangoObjectType): tickets = graphene.List(graphene.NonNull(TicketType)) def resolve_tickets(self, info): return self.tickets.all() class Meta: model = Conference only_fields = ( 'id', 'name', 'slug', 'start', 'end', 'cfp_start', 'cfp_end', 'voting_start', 'voting_end', 'refund_start', 'refund_end' )
// ... existing code ... class Meta: model = Conference only_fields = ( 'id', 'name', 'slug', 'start', 'end', 'cfp_start', 'cfp_end', 'voting_start', 'voting_end', 'refund_start', 'refund_end' ) // ... rest of the code ...
a893223d4964f946d9413a17e62871e2660843a8
flexget/plugins/input_listdir.py
flexget/plugins/input_listdir.py
import logging from flexget.plugin import * log = logging.getLogger('listdir') class InputListdir: """ Uses local path content as an input. Example: listdir: /storage/movies/ """ def validator(self): from flexget import validator root = validator.factory() root.accept('path') bundle = root.accept('list') bundle.accept('path') return root def get_config(self, feed): config = feed.config.get('listdir', None) #if only a single path is passed turn it into a 1 element list if isinstance(config, basestring): config = [config] return config def on_feed_input(self, feed): from flexget.feed import Entry import os config = self.get_config(feed) for path in config: for name in os.listdir(unicode(path)): e = Entry() e['title'] = name e['url'] = 'file://%s' % (os.path.join(path, name)) e['location'] = os.path.join(path, name) feed.entries.append(e) register_plugin(InputListdir, 'listdir')
import logging from flexget.plugin import register_plugin log = logging.getLogger('listdir') class InputListdir: """ Uses local path content as an input. Example: listdir: /storage/movies/ """ def validator(self): from flexget import validator root = validator.factory() root.accept('path') bundle = root.accept('list') bundle.accept('path') return root def get_config(self, feed): config = feed.config.get('listdir', None) # If only a single path is passed turn it into a 1 element list if isinstance(config, basestring): config = [config] return config def on_feed_input(self, feed): from flexget.feed import Entry import os config = self.get_config(feed) for path in config: for name in os.listdir(unicode(path)): e = Entry() e['title'] = name filepath = os.path.join(path, name) # Windows paths need an extra / prepended to them if not filepath.startswith('/'): filepath = '/' + filepath e['url'] = 'file://%s' % (filepath) e['location'] = os.path.join(path, name) feed.entries.append(e) register_plugin(InputListdir, 'listdir')
Fix url of entries made by listdir on Windows.
Fix url of entries made by listdir on Windows. git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1586 3942dd89-8c5d-46d7-aeed-044bccf3e60c
Python
mit
LynxyssCZ/Flexget,thalamus/Flexget,tvcsantos/Flexget,ibrahimkarahan/Flexget,patsissons/Flexget,oxc/Flexget,dsemi/Flexget,qvazzler/Flexget,poulpito/Flexget,crawln45/Flexget,Flexget/Flexget,ZefQ/Flexget,malkavi/Flexget,malkavi/Flexget,oxc/Flexget,JorisDeRieck/Flexget,crawln45/Flexget,sean797/Flexget,jawilson/Flexget,dsemi/Flexget,spencerjanssen/Flexget,ibrahimkarahan/Flexget,qvazzler/Flexget,qvazzler/Flexget,asm0dey/Flexget,Pretagonist/Flexget,ianstalk/Flexget,drwyrm/Flexget,ZefQ/Flexget,jawilson/Flexget,antivirtel/Flexget,spencerjanssen/Flexget,ratoaq2/Flexget,camon/Flexget,malkavi/Flexget,spencerjanssen/Flexget,lildadou/Flexget,tsnoam/Flexget,xfouloux/Flexget,voriux/Flexget,ratoaq2/Flexget,grrr2/Flexget,LynxyssCZ/Flexget,LynxyssCZ/Flexget,ianstalk/Flexget,X-dark/Flexget,tobinjt/Flexget,poulpito/Flexget,tarzasai/Flexget,jawilson/Flexget,OmgOhnoes/Flexget,dsemi/Flexget,qk4l/Flexget,OmgOhnoes/Flexget,patsissons/Flexget,tobinjt/Flexget,jacobmetrick/Flexget,ZefQ/Flexget,jacobmetrick/Flexget,Pretagonist/Flexget,JorisDeRieck/Flexget,crawln45/Flexget,Danfocus/Flexget,JorisDeRieck/Flexget,OmgOhnoes/Flexget,Flexget/Flexget,Pretagonist/Flexget,X-dark/Flexget,Danfocus/Flexget,LynxyssCZ/Flexget,thalamus/Flexget,tobinjt/Flexget,ianstalk/Flexget,vfrc2/Flexget,jawilson/Flexget,patsissons/Flexget,tvcsantos/Flexget,tsnoam/Flexget,tarzasai/Flexget,lildadou/Flexget,thalamus/Flexget,Flexget/Flexget,gazpachoking/Flexget,asm0dey/Flexget,antivirtel/Flexget,qk4l/Flexget,sean797/Flexget,Danfocus/Flexget,offbyone/Flexget,drwyrm/Flexget,asm0dey/Flexget,X-dark/Flexget,gazpachoking/Flexget,vfrc2/Flexget,ibrahimkarahan/Flexget,Flexget/Flexget,offbyone/Flexget,xfouloux/Flexget,lildadou/Flexget,grrr2/Flexget,antivirtel/Flexget,oxc/Flexget,tsnoam/Flexget,v17al/Flexget,offbyone/Flexget,drwyrm/Flexget,Danfocus/Flexget,v17al/Flexget,poulpito/Flexget,grrr2/Flexget,cvium/Flexget,cvium/Flexget,jacobmetrick/Flexget,sean797/Flexget,cvium/Flexget,JorisDeRieck/Flexget,tobinjt/Flexget,crawln45/Flexget,vfrc2/Flexget,tarzasai/Flexget,qk4l/Flexget,ratoaq2/Flexget,v17al/Flexget,camon/Flexget,voriux/Flexget,malkavi/Flexget,xfouloux/Flexget
python
## Code Before: import logging from flexget.plugin import * log = logging.getLogger('listdir') class InputListdir: """ Uses local path content as an input. Example: listdir: /storage/movies/ """ def validator(self): from flexget import validator root = validator.factory() root.accept('path') bundle = root.accept('list') bundle.accept('path') return root def get_config(self, feed): config = feed.config.get('listdir', None) #if only a single path is passed turn it into a 1 element list if isinstance(config, basestring): config = [config] return config def on_feed_input(self, feed): from flexget.feed import Entry import os config = self.get_config(feed) for path in config: for name in os.listdir(unicode(path)): e = Entry() e['title'] = name e['url'] = 'file://%s' % (os.path.join(path, name)) e['location'] = os.path.join(path, name) feed.entries.append(e) register_plugin(InputListdir, 'listdir') ## Instruction: Fix url of entries made by listdir on Windows. git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1586 3942dd89-8c5d-46d7-aeed-044bccf3e60c ## Code After: import logging from flexget.plugin import register_plugin log = logging.getLogger('listdir') class InputListdir: """ Uses local path content as an input. Example: listdir: /storage/movies/ """ def validator(self): from flexget import validator root = validator.factory() root.accept('path') bundle = root.accept('list') bundle.accept('path') return root def get_config(self, feed): config = feed.config.get('listdir', None) # If only a single path is passed turn it into a 1 element list if isinstance(config, basestring): config = [config] return config def on_feed_input(self, feed): from flexget.feed import Entry import os config = self.get_config(feed) for path in config: for name in os.listdir(unicode(path)): e = Entry() e['title'] = name filepath = os.path.join(path, name) # Windows paths need an extra / prepended to them if not filepath.startswith('/'): filepath = '/' + filepath e['url'] = 'file://%s' % (filepath) e['location'] = os.path.join(path, name) feed.entries.append(e) register_plugin(InputListdir, 'listdir')
# ... existing code ... import logging from flexget.plugin import register_plugin log = logging.getLogger('listdir') # ... modified code ... class InputListdir: """ Uses local path content as an input. Example: listdir: /storage/movies/ """ def validator(self): from flexget import validator root = validator.factory() ... bundle = root.accept('list') bundle.accept('path') return root def get_config(self, feed): config = feed.config.get('listdir', None) # If only a single path is passed turn it into a 1 element list if isinstance(config, basestring): config = [config] return config ... from flexget.feed import Entry import os config = self.get_config(feed) for path in config: for name in os.listdir(unicode(path)): e = Entry() e['title'] = name filepath = os.path.join(path, name) # Windows paths need an extra / prepended to them if not filepath.startswith('/'): filepath = '/' + filepath e['url'] = 'file://%s' % (filepath) e['location'] = os.path.join(path, name) feed.entries.append(e) # ... rest of the code ...
a9fe5d311909b20ea275fb985a7b12eb794180e6
source/common/halfling_sys.h
source/common/halfling_sys.h
/* The Halfling Project - A Graphics Engine and Projects * * The Halfling Project is the legal property of Adrian Astley * Copyright Adrian Astley 2013 */ #ifndef COMMON_HALFLING_SYS_H #define COMMON_HALFLING_SYS_H #include "common/typedefs.h" // Only include the base windows libraries #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <comip.h> // GDI+ #include <gdiplus.h> // Un-define min and max from the windows headers #ifdef min #undef min #endif #ifdef max #undef max #endif #endif
/* The Halfling Project - A Graphics Engine and Projects * * The Halfling Project is the legal property of Adrian Astley * Copyright Adrian Astley 2013 */ #ifndef COMMON_HALFLING_SYS_H #define COMMON_HALFLING_SYS_H #include "common/typedefs.h" // Only include the base windows libraries #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <comip.h> // GDI+ #include <gdiplus.h> // Un-define min and max from the windows headers #ifdef min #undef min #endif #ifdef max #undef max #endif #define AssertMsg(condition, message) \ do { \ if (!(condition)) { \ std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \ << " line " << __LINE__ << ": " << message << std::endl; \ std::exit(EXIT_FAILURE); \ } \ } while (false) #endif
Create define for asserting with a message
COMMON: Create define for asserting with a message
C
apache-2.0
RichieSams/thehalflingproject,RichieSams/thehalflingproject,RichieSams/thehalflingproject
c
## Code Before: /* The Halfling Project - A Graphics Engine and Projects * * The Halfling Project is the legal property of Adrian Astley * Copyright Adrian Astley 2013 */ #ifndef COMMON_HALFLING_SYS_H #define COMMON_HALFLING_SYS_H #include "common/typedefs.h" // Only include the base windows libraries #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <comip.h> // GDI+ #include <gdiplus.h> // Un-define min and max from the windows headers #ifdef min #undef min #endif #ifdef max #undef max #endif #endif ## Instruction: COMMON: Create define for asserting with a message ## Code After: /* The Halfling Project - A Graphics Engine and Projects * * The Halfling Project is the legal property of Adrian Astley * Copyright Adrian Astley 2013 */ #ifndef COMMON_HALFLING_SYS_H #define COMMON_HALFLING_SYS_H #include "common/typedefs.h" // Only include the base windows libraries #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <comip.h> // GDI+ #include <gdiplus.h> // Un-define min and max from the windows headers #ifdef min #undef min #endif #ifdef max #undef max #endif #define AssertMsg(condition, message) \ do { \ if (!(condition)) { \ std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \ << " line " << __LINE__ << ": " << message << std::endl; \ std::exit(EXIT_FAILURE); \ } \ } while (false) #endif
# ... existing code ... #ifdef max #undef max #endif #define AssertMsg(condition, message) \ do { \ if (!(condition)) { \ std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \ << " line " << __LINE__ << ": " << message << std::endl; \ std::exit(EXIT_FAILURE); \ } \ } while (false) #endif # ... rest of the code ...
b42896e796e6f4d2984547a34978bb34c66ba749
blanc_basic_news/news/views.py
blanc_basic_news/news/views.py
from django.views.generic import ListView, MonthArchiveView, DateDetailView from django.shortcuts import get_object_or_404 from django.utils import timezone from django.conf import settings from .models import Category, Post class PostListView(ListView): paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10) def get_queryset(self): return Post.objects.select_related().filter( published=True, date__lte=timezone.now()) class PostListCategoryView(ListView): paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10) template_name_suffix = '_list_category' def get_queryset(self): self.category = get_object_or_404(Category, slug=self.kwargs['slug']) return Post.objects.select_related().filter( published=True, date__lte=timezone.now(), category=self.category) def get_context_data(self, **kwargs): context = super(PostListCategoryView, self).get_context_data(**kwargs) context['category'] = self.category return context class PostListMonthView(MonthArchiveView): queryset = Post.objects.filter(published=True) month_format = '%m' date_field = 'date_url' class PostDetailView(DateDetailView): queryset = Post.objects.filter(published=True) month_format = '%m' date_field = 'date_url'
from django.views.generic import ArchiveIndexView, MonthArchiveView, DateDetailView from django.shortcuts import get_object_or_404 from django.conf import settings from .models import Category, Post class PostListView(ArchiveIndexView): queryset = Post.objects.select_related().filter(published=True) date_field = 'date' paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10) template_name_suffix = '_list' context_object_name = 'object_list' class PostListCategoryView(PostListView): template_name_suffix = '_list_category' def get_queryset(self): qs = super(PostListCategoryView, self).get_queryset() self.category = get_object_or_404(Category, slug=self.kwargs['slug']) return qs.filter(category=self.category) def get_context_data(self, **kwargs): context = super(PostListCategoryView, self).get_context_data(**kwargs) context['category'] = self.category return context class PostListMonthView(MonthArchiveView): queryset = Post.objects.filter(published=True) month_format = '%m' date_field = 'date_url' class PostDetailView(DateDetailView): queryset = Post.objects.filter(published=True) month_format = '%m' date_field = 'date_url'
Use ArchiveIndexView to reduce code
Use ArchiveIndexView to reduce code
Python
bsd-3-clause
blancltd/blanc-basic-news
python
## Code Before: from django.views.generic import ListView, MonthArchiveView, DateDetailView from django.shortcuts import get_object_or_404 from django.utils import timezone from django.conf import settings from .models import Category, Post class PostListView(ListView): paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10) def get_queryset(self): return Post.objects.select_related().filter( published=True, date__lte=timezone.now()) class PostListCategoryView(ListView): paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10) template_name_suffix = '_list_category' def get_queryset(self): self.category = get_object_or_404(Category, slug=self.kwargs['slug']) return Post.objects.select_related().filter( published=True, date__lte=timezone.now(), category=self.category) def get_context_data(self, **kwargs): context = super(PostListCategoryView, self).get_context_data(**kwargs) context['category'] = self.category return context class PostListMonthView(MonthArchiveView): queryset = Post.objects.filter(published=True) month_format = '%m' date_field = 'date_url' class PostDetailView(DateDetailView): queryset = Post.objects.filter(published=True) month_format = '%m' date_field = 'date_url' ## Instruction: Use ArchiveIndexView to reduce code ## Code After: from django.views.generic import ArchiveIndexView, MonthArchiveView, DateDetailView from django.shortcuts import get_object_or_404 from django.conf import settings from .models import Category, Post class PostListView(ArchiveIndexView): queryset = Post.objects.select_related().filter(published=True) date_field = 'date' paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10) template_name_suffix = '_list' context_object_name = 'object_list' class PostListCategoryView(PostListView): template_name_suffix = '_list_category' def get_queryset(self): qs = super(PostListCategoryView, self).get_queryset() self.category = get_object_or_404(Category, slug=self.kwargs['slug']) return qs.filter(category=self.category) def get_context_data(self, **kwargs): context = super(PostListCategoryView, self).get_context_data(**kwargs) context['category'] = self.category return context class PostListMonthView(MonthArchiveView): queryset = Post.objects.filter(published=True) month_format = '%m' date_field = 'date_url' class PostDetailView(DateDetailView): queryset = Post.objects.filter(published=True) month_format = '%m' date_field = 'date_url'
# ... existing code ... from django.views.generic import ArchiveIndexView, MonthArchiveView, DateDetailView from django.shortcuts import get_object_or_404 from django.conf import settings from .models import Category, Post class PostListView(ArchiveIndexView): queryset = Post.objects.select_related().filter(published=True) date_field = 'date' paginate_by = getattr(settings, 'NEWS_PER_PAGE', 10) template_name_suffix = '_list' context_object_name = 'object_list' class PostListCategoryView(PostListView): template_name_suffix = '_list_category' def get_queryset(self): qs = super(PostListCategoryView, self).get_queryset() self.category = get_object_or_404(Category, slug=self.kwargs['slug']) return qs.filter(category=self.category) def get_context_data(self, **kwargs): context = super(PostListCategoryView, self).get_context_data(**kwargs) # ... rest of the code ...
c320f36d4dbe61dc0e40620a009ffaf560fa69dc
src/main/java/redis/embedded/cluster/Client.java
src/main/java/redis/embedded/cluster/Client.java
package redis.embedded.cluster; import redis.clients.jedis.*; import java.io.*; // TODO Remove dependency on Jedis class Client implements Closeable { private final Jedis jedis; Client(String host, int port) { this.jedis = new Jedis(host, port); } public String clusterReplicate(final String nodeId) { return jedis.clusterReplicate(nodeId); } public void close() { jedis.close(); } public String clusterAddSlots(final int... slots) { return jedis.clusterAddSlots(slots); } public String clusterNodes() { return jedis.clusterNodes(); } public String getNodeId() { return clusterNodes().split(" :")[0]; } public String clusterMeet(final String ip, final int port) { return jedis.clusterMeet(ip, port); } public String clusterInfo() { return jedis.clusterInfo(); } }
package redis.embedded.cluster; import redis.clients.jedis.*; import java.io.*; /** * A minimal client implementation to pass some commands to a single redis server. * This implementation rely on Jedis to make the all calls (removing the dependency on Jedis could be done * but will add a serious complexity to this project, hence the dependency). */ class Client implements Closeable { private final Jedis jedis; Client(String host, int port) { this.jedis = new Jedis(host, port); } public String clusterReplicate(final String nodeId) { return jedis.clusterReplicate(nodeId); } public void close() { jedis.close(); } public String clusterAddSlots(final int... slots) { return jedis.clusterAddSlots(slots); } public String clusterNodes() { return jedis.clusterNodes(); } public String getNodeId() { return clusterNodes().split(" :")[0]; } public String clusterMeet(final String ip, final int port) { return jedis.clusterMeet(ip, port); } public String clusterInfo() { return jedis.clusterInfo(); } }
Add explanation as to why we depend on Jedis
Add explanation as to why we depend on Jedis
Java
apache-2.0
fmonniot/embedded-redis,fmonniot/embedded-redis
java
## Code Before: package redis.embedded.cluster; import redis.clients.jedis.*; import java.io.*; // TODO Remove dependency on Jedis class Client implements Closeable { private final Jedis jedis; Client(String host, int port) { this.jedis = new Jedis(host, port); } public String clusterReplicate(final String nodeId) { return jedis.clusterReplicate(nodeId); } public void close() { jedis.close(); } public String clusterAddSlots(final int... slots) { return jedis.clusterAddSlots(slots); } public String clusterNodes() { return jedis.clusterNodes(); } public String getNodeId() { return clusterNodes().split(" :")[0]; } public String clusterMeet(final String ip, final int port) { return jedis.clusterMeet(ip, port); } public String clusterInfo() { return jedis.clusterInfo(); } } ## Instruction: Add explanation as to why we depend on Jedis ## Code After: package redis.embedded.cluster; import redis.clients.jedis.*; import java.io.*; /** * A minimal client implementation to pass some commands to a single redis server. * This implementation rely on Jedis to make the all calls (removing the dependency on Jedis could be done * but will add a serious complexity to this project, hence the dependency). */ class Client implements Closeable { private final Jedis jedis; Client(String host, int port) { this.jedis = new Jedis(host, port); } public String clusterReplicate(final String nodeId) { return jedis.clusterReplicate(nodeId); } public void close() { jedis.close(); } public String clusterAddSlots(final int... slots) { return jedis.clusterAddSlots(slots); } public String clusterNodes() { return jedis.clusterNodes(); } public String getNodeId() { return clusterNodes().split(" :")[0]; } public String clusterMeet(final String ip, final int port) { return jedis.clusterMeet(ip, port); } public String clusterInfo() { return jedis.clusterInfo(); } }
# ... existing code ... import java.io.*; /** * A minimal client implementation to pass some commands to a single redis server. * This implementation rely on Jedis to make the all calls (removing the dependency on Jedis could be done * but will add a serious complexity to this project, hence the dependency). */ class Client implements Closeable { private final Jedis jedis; # ... rest of the code ...
38833f68daabe845650250e3edf9cb4b3cc9cb62
events/templatetags/humantime.py
events/templatetags/humantime.py
from django.template.defaultfilters import stringfilter from datetime import datetime, timedelta from django import template register = template.Library() @register.filter def event_time(start, end): today = datetime.today () result = "" if start == today: result += "aujourd'hui " else: result += "le %s " % start.strftime ("%A %d %B %Y") if start.day == end.day and start.month == end.month and start.year == end.year: result += "de %s " % start.strftime ("%H:%M") result += "à %s " % end.strftime ("%H:%M") else: result += "à %s" % start.strftime ("%H:%M") result += "jusqu'au %s" % end.strftime ("%A %d %B %Y à %H:%M") return result
from django.template.defaultfilters import stringfilter from datetime import datetime, timedelta from django import template import locale register = template.Library() @register.filter def event_time(start, end): today = datetime.today () result = "" # Hack! get the correct user local from the request loc = locale.getlocale() locale.setlocale(locale.LC_ALL, 'fr_CA.UTF8') if start == today: result += "Aujourd'hui " else: result += "Le %s " % start.strftime ("%A %d %B %Y") if start.day == end.day and start.month == end.month and start.year == end.year: result += "de %s " % start.strftime ("%H:%M") result += "à %s " % end.strftime ("%H:%M") else: result += "à %s" % start.strftime ("%H:%M") result += "jusqu'au %s" % end.strftime ("%A %d %B %Y à %H:%M") locale.setlocale(locale.LC_ALL, loc) return result
Print date in fr_CA locale
hack: Print date in fr_CA locale
Python
agpl-3.0
mlhamel/agendadulibre,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,vcorreze/agendaEteAccoord
python
## Code Before: from django.template.defaultfilters import stringfilter from datetime import datetime, timedelta from django import template register = template.Library() @register.filter def event_time(start, end): today = datetime.today () result = "" if start == today: result += "aujourd'hui " else: result += "le %s " % start.strftime ("%A %d %B %Y") if start.day == end.day and start.month == end.month and start.year == end.year: result += "de %s " % start.strftime ("%H:%M") result += "à %s " % end.strftime ("%H:%M") else: result += "à %s" % start.strftime ("%H:%M") result += "jusqu'au %s" % end.strftime ("%A %d %B %Y à %H:%M") return result ## Instruction: hack: Print date in fr_CA locale ## Code After: from django.template.defaultfilters import stringfilter from datetime import datetime, timedelta from django import template import locale register = template.Library() @register.filter def event_time(start, end): today = datetime.today () result = "" # Hack! get the correct user local from the request loc = locale.getlocale() locale.setlocale(locale.LC_ALL, 'fr_CA.UTF8') if start == today: result += "Aujourd'hui " else: result += "Le %s " % start.strftime ("%A %d %B %Y") if start.day == end.day and start.month == end.month and start.year == end.year: result += "de %s " % start.strftime ("%H:%M") result += "à %s " % end.strftime ("%H:%M") else: result += "à %s" % start.strftime ("%H:%M") result += "jusqu'au %s" % end.strftime ("%A %d %B %Y à %H:%M") locale.setlocale(locale.LC_ALL, loc) return result
// ... existing code ... from django.template.defaultfilters import stringfilter from datetime import datetime, timedelta from django import template import locale register = template.Library() // ... modified code ... today = datetime.today () result = "" # Hack! get the correct user local from the request loc = locale.getlocale() locale.setlocale(locale.LC_ALL, 'fr_CA.UTF8') if start == today: result += "Aujourd'hui " else: result += "Le %s " % start.strftime ("%A %d %B %Y") if start.day == end.day and start.month == end.month and start.year == end.year: result += "de %s " % start.strftime ("%H:%M") ... result += "à %s" % start.strftime ("%H:%M") result += "jusqu'au %s" % end.strftime ("%A %d %B %Y à %H:%M") locale.setlocale(locale.LC_ALL, loc) return result // ... rest of the code ...
ae1de4000a6e9f3fc70d14c6214038e83772a5f6
Part2/main.py
Part2/main.py
import detectLang import graph # ==================================================================================================== # La detection est rapide car toute les perplexites sont stockées dans les fichiers binaires pp_EN etc # Pour regénerer les fichiers : # Executer detectLang.create_all_pp_and_save_to_disc() # Les resultats des perplexités pour tous les fichiers seront serialisés dans les fichiers binaires. # ces fichiers sont necessaire à la fontions detectLang.detect_language() # Pour serialisé les dictionaires j'utilise la bibliotheque intégrer à python => pickle # ==================================================================================================== test_file_number = 19 # detect_language(Numéro du fichier dans le repertoire de test, N du modele nGram) # Print le code de la langue reconnue et la perplexité du modèle choisis. detectLang.detect_language(test_file_number,1) detectLang.detect_language(test_file_number,2) detectLang.detect_language(test_file_number,3) # ==================================================================================================== # Nécessite matplotlib # Installé matplotlib avec => pip install matplotlib # ==================================================================================================== # graphFile(Numéro du fichier dans le repertoire de test) graph.graphFile(test_file_number)
import detectLang import graph # ==================================================================================================== # La detection est rapide car toute les perplexites sont stockées dans les fichiers binaires pp_EN etc # Pour regénerer les fichiers : # Executer detectLang.create_all_pp_and_save_to_disc(), décommenter la ligne suivante # detectLang.create_all_pp_and_save_to_disc() # Les resultats des perplexités pour tous les fichiers seront serialisés dans les fichiers binaires. # ces fichiers sont necessaire à la fontions detectLang.detect_language() # Pour serialisé les dictionaires j'utilise la bibliotheque intégrer à python => pickle # ==================================================================================================== test_file_number = 13 # detect_language(Numéro du fichier dans le repertoire de test, N du modele nGram) # Print le code de la langue reconnue et la perplexité du modèle choisis. # detectLang.detect_language(test_file_number,1) # detectLang.detect_language(test_file_number,2) # detectLang.detect_language(test_file_number,3) # ==================================================================================================== # Nécessite matplotlib # Installé matplotlib avec => pip install matplotlib # ==================================================================================================== # Affiche sur un graphique les perplexité de tous les modeles sur un même fichier # graph.graphFile(test_file_number) # Pour donner le resultat sur tous les fichier test dans la console detectLang.show_all_result()
Update doc and add one call
Update doc and add one call
Python
mit
Focom/NLPWork1,Focom/NLPWork1,Focom/NLPWork1
python
## Code Before: import detectLang import graph # ==================================================================================================== # La detection est rapide car toute les perplexites sont stockées dans les fichiers binaires pp_EN etc # Pour regénerer les fichiers : # Executer detectLang.create_all_pp_and_save_to_disc() # Les resultats des perplexités pour tous les fichiers seront serialisés dans les fichiers binaires. # ces fichiers sont necessaire à la fontions detectLang.detect_language() # Pour serialisé les dictionaires j'utilise la bibliotheque intégrer à python => pickle # ==================================================================================================== test_file_number = 19 # detect_language(Numéro du fichier dans le repertoire de test, N du modele nGram) # Print le code de la langue reconnue et la perplexité du modèle choisis. detectLang.detect_language(test_file_number,1) detectLang.detect_language(test_file_number,2) detectLang.detect_language(test_file_number,3) # ==================================================================================================== # Nécessite matplotlib # Installé matplotlib avec => pip install matplotlib # ==================================================================================================== # graphFile(Numéro du fichier dans le repertoire de test) graph.graphFile(test_file_number) ## Instruction: Update doc and add one call ## Code After: import detectLang import graph # ==================================================================================================== # La detection est rapide car toute les perplexites sont stockées dans les fichiers binaires pp_EN etc # Pour regénerer les fichiers : # Executer detectLang.create_all_pp_and_save_to_disc(), décommenter la ligne suivante # detectLang.create_all_pp_and_save_to_disc() # Les resultats des perplexités pour tous les fichiers seront serialisés dans les fichiers binaires. # ces fichiers sont necessaire à la fontions detectLang.detect_language() # Pour serialisé les dictionaires j'utilise la bibliotheque intégrer à python => pickle # ==================================================================================================== test_file_number = 13 # detect_language(Numéro du fichier dans le repertoire de test, N du modele nGram) # Print le code de la langue reconnue et la perplexité du modèle choisis. # detectLang.detect_language(test_file_number,1) # detectLang.detect_language(test_file_number,2) # detectLang.detect_language(test_file_number,3) # ==================================================================================================== # Nécessite matplotlib # Installé matplotlib avec => pip install matplotlib # ==================================================================================================== # Affiche sur un graphique les perplexité de tous les modeles sur un même fichier # graph.graphFile(test_file_number) # Pour donner le resultat sur tous les fichier test dans la console detectLang.show_all_result()
# ... existing code ... # ==================================================================================================== # La detection est rapide car toute les perplexites sont stockées dans les fichiers binaires pp_EN etc # Pour regénerer les fichiers : # Executer detectLang.create_all_pp_and_save_to_disc(), décommenter la ligne suivante # detectLang.create_all_pp_and_save_to_disc() # Les resultats des perplexités pour tous les fichiers seront serialisés dans les fichiers binaires. # ces fichiers sont necessaire à la fontions detectLang.detect_language() # Pour serialisé les dictionaires j'utilise la bibliotheque intégrer à python => pickle # ==================================================================================================== test_file_number = 13 # detect_language(Numéro du fichier dans le repertoire de test, N du modele nGram) # Print le code de la langue reconnue et la perplexité du modèle choisis. # detectLang.detect_language(test_file_number,1) # detectLang.detect_language(test_file_number,2) # detectLang.detect_language(test_file_number,3) # ==================================================================================================== # Nécessite matplotlib # ... modified code ... # Installé matplotlib avec => pip install matplotlib # ==================================================================================================== # Affiche sur un graphique les perplexité de tous les modeles sur un même fichier # graph.graphFile(test_file_number) # Pour donner le resultat sur tous les fichier test dans la console detectLang.show_all_result() # ... rest of the code ...
3c25f2802f70a16869e93fb301428c31452c00f0
plyer/platforms/macosx/uniqueid.py
plyer/platforms/macosx/uniqueid.py
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID()
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] if old_lang is None: environ.pop('LANG') else: environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID()
Fix TypeError if `LANG` is not set in on osx
Fix TypeError if `LANG` is not set in on osx In macosx.uniqueid, `$LANG` is retrieved with `old_lang = environ.get('LANG')`. This means that if `LANG` is not set, `old_lang` will be none. When plyer later tries to restore the original value of lang, `putenv` will complain that we're not supplying a string. I've corrected this by popping the inserted `LANG` value if `old_lang` is none.
Python
mit
kivy/plyer,kived/plyer,KeyWeeUsr/plyer,johnbolia/plyer,johnbolia/plyer,kivy/plyer,KeyWeeUsr/plyer,kived/plyer,KeyWeeUsr/plyer,kivy/plyer
python
## Code Before: from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID() ## Instruction: Fix TypeError if `LANG` is not set in on osx In macosx.uniqueid, `$LANG` is retrieved with `old_lang = environ.get('LANG')`. This means that if `LANG` is not set, `old_lang` will be none. When plyer later tries to restore the original value of lang, `putenv` will complain that we're not supplying a string. I've corrected this by popping the inserted `LANG` value if `old_lang` is none. ## Code After: from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] if old_lang is None: environ.pop('LANG') else: environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID()
# ... existing code ... ioreg_process.stdout.close() output = grep_process.communicate()[0] if old_lang is None: environ.pop('LANG') else: environ['LANG'] = old_lang if output: return output.split()[3][1:-1] # ... rest of the code ...
bf6d4c4622b9a0161fad3b03422747fb16faf5de
setup.py
setup.py
from distutils.core import setup setup( name='BitstampClient', version='0.1', packages=['bitstamp'], url='', license='MIT', author='Kamil Madac', author_email='[email protected]', description='Bitstamp API python implementation', requires=['requests'] )
from distutils.core import setup setup( name='bitstamp-python-client', version='0.1', packages=['bitstamp'], url='', license='MIT', author='Kamil Madac', author_email='[email protected]', description='Bitstamp API python implementation', requires=['requests'] )
Rename because of clash with original package.
Rename because of clash with original package.
Python
mit
nederhoed/bitstamp-python-client
python
## Code Before: from distutils.core import setup setup( name='BitstampClient', version='0.1', packages=['bitstamp'], url='', license='MIT', author='Kamil Madac', author_email='[email protected]', description='Bitstamp API python implementation', requires=['requests'] ) ## Instruction: Rename because of clash with original package. ## Code After: from distutils.core import setup setup( name='bitstamp-python-client', version='0.1', packages=['bitstamp'], url='', license='MIT', author='Kamil Madac', author_email='[email protected]', description='Bitstamp API python implementation', requires=['requests'] )
# ... existing code ... from distutils.core import setup setup( name='bitstamp-python-client', version='0.1', packages=['bitstamp'], url='', # ... rest of the code ...
b0afcb7cebb7b64f8e8c378ff3c5d117a2abb4cc
include/jive/arch/registers.h
include/jive/arch/registers.h
typedef struct jive_cpureg jive_cpureg; typedef struct jive_regcls jive_regcls; struct jive_cpureg { const char name[32]; }; #endif
typedef struct jive_cpureg jive_cpureg; typedef struct jive_regcls jive_regcls; struct jive_cpureg { const jive_regcls * regcls; const char name[32]; }; #endif
Add reference to register class to cpureg
Add reference to register class to cpureg Arch support is still incomplete, but this bit is required for other target-independent code.
C
lgpl-2.1
phate/jive,phate/jive,phate/jive
c
## Code Before: typedef struct jive_cpureg jive_cpureg; typedef struct jive_regcls jive_regcls; struct jive_cpureg { const char name[32]; }; #endif ## Instruction: Add reference to register class to cpureg Arch support is still incomplete, but this bit is required for other target-independent code. ## Code After: typedef struct jive_cpureg jive_cpureg; typedef struct jive_regcls jive_regcls; struct jive_cpureg { const jive_regcls * regcls; const char name[32]; }; #endif
// ... existing code ... typedef struct jive_regcls jive_regcls; struct jive_cpureg { const jive_regcls * regcls; const char name[32]; }; // ... rest of the code ...
896994488fa84eea3a8d0d431def7e4b9e808839
src/main/java/co/vorobyev/exitsign/ExitStatus.java
src/main/java/co/vorobyev/exitsign/ExitStatus.java
/* Copyright 2015 Anton Vorobyev Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package co.vorobyev.exitsign; /** * Constant class collecting exit status codes. * * @author <a href="http://vorobyev.co">Anton Vorobyev</a> * @since 0.1 */ public final class ExitStatus { /** * Don't create instance of this class, it is constant class. */ private ExitStatus() { throw new AssertionError(); } /** * Exit code returned when execution finishes successfully */ public static final int SUCCESS = 0; /** * Exit code returned when execution finishes successfully, synonym of SUCCESS */ public static final int OK = 0; /** * Exit code returned when execution finishes failingly */ public static final int FAILURE = 1; /** * Exit code returned when execution finishes failingly, synonym of FAILURE */ public static final int BAD = 1; }
/* Copyright 2015 Anton Vorobyev Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package co.vorobyev.exitsign; /** * Constant class collecting exit status codes. * * @author <a href="http://vorobyev.co">Anton Vorobyev</a> * @since 0.1 */ public final class ExitStatus { /** * Don't create instance of this class, it is constant class. */ private ExitStatus() { throw new AssertionError(); } /** * Exit code returned when execution finishes successfully */ public static final int SUCCESS = 0; /** * Exit code returned when execution finishes failingly */ public static final int FAILURE = 1; }
Remove synonyms of primitive statuses
Remove synonyms of primitive statuses Refers #1
Java
apache-2.0
antonvorobyev/exitsign
java
## Code Before: /* Copyright 2015 Anton Vorobyev Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package co.vorobyev.exitsign; /** * Constant class collecting exit status codes. * * @author <a href="http://vorobyev.co">Anton Vorobyev</a> * @since 0.1 */ public final class ExitStatus { /** * Don't create instance of this class, it is constant class. */ private ExitStatus() { throw new AssertionError(); } /** * Exit code returned when execution finishes successfully */ public static final int SUCCESS = 0; /** * Exit code returned when execution finishes successfully, synonym of SUCCESS */ public static final int OK = 0; /** * Exit code returned when execution finishes failingly */ public static final int FAILURE = 1; /** * Exit code returned when execution finishes failingly, synonym of FAILURE */ public static final int BAD = 1; } ## Instruction: Remove synonyms of primitive statuses Refers #1 ## Code After: /* Copyright 2015 Anton Vorobyev Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package co.vorobyev.exitsign; /** * Constant class collecting exit status codes. * * @author <a href="http://vorobyev.co">Anton Vorobyev</a> * @since 0.1 */ public final class ExitStatus { /** * Don't create instance of this class, it is constant class. */ private ExitStatus() { throw new AssertionError(); } /** * Exit code returned when execution finishes successfully */ public static final int SUCCESS = 0; /** * Exit code returned when execution finishes failingly */ public static final int FAILURE = 1; }
# ... existing code ... public static final int SUCCESS = 0; /** * Exit code returned when execution finishes failingly */ public static final int FAILURE = 1; } # ... rest of the code ...
82f2fb3c3956e4ad4c65b03b3918ea409593d4ef
gcloud/__init__.py
gcloud/__init__.py
"""GCloud API access in idiomatic Python.""" __version__ = '0.02.2'
"""GCloud API access in idiomatic Python.""" from pkg_resources import get_distribution __version__ = get_distribution('gcloud').version
Read module version from setup.py
Read module version from setup.py
Python
apache-2.0
googleapis/google-cloud-python,blowmage/gcloud-python,thesandlord/gcloud-python,calpeyser/google-cloud-python,CyrusBiotechnology/gcloud-python,waprin/gcloud-python,VitalLabs/gcloud-python,waprin/google-cloud-python,jonparrott/google-cloud-python,Fkawala/gcloud-python,tswast/google-cloud-python,waprin/gcloud-python,dhermes/gcloud-python,quom/google-cloud-python,tseaver/google-cloud-python,tartavull/google-cloud-python,optimizely/gcloud-python,lucemia/gcloud-python,CyrusBiotechnology/gcloud-python,tswast/google-cloud-python,VitalLabs/gcloud-python,GrimDerp/gcloud-python,tseaver/gcloud-python,blowmage/gcloud-python,vj-ug/gcloud-python,jbuberel/gcloud-python,tswast/google-cloud-python,jonparrott/google-cloud-python,tseaver/google-cloud-python,tartavull/google-cloud-python,dhermes/google-cloud-python,tseaver/google-cloud-python,dhermes/google-cloud-python,quom/google-cloud-python,tseaver/gcloud-python,optimizely/gcloud-python,jonparrott/gcloud-python,dhermes/gcloud-python,googleapis/google-cloud-python,EugenePig/gcloud-python,EugenePig/gcloud-python,GrimDerp/gcloud-python,lucemia/gcloud-python,daspecster/google-cloud-python,jonparrott/gcloud-python,daspecster/google-cloud-python,jgeewax/gcloud-python,GoogleCloudPlatform/gcloud-python,jbuberel/gcloud-python,waprin/google-cloud-python,elibixby/gcloud-python,thesandlord/gcloud-python,GoogleCloudPlatform/gcloud-python,calpeyser/google-cloud-python,Fkawala/gcloud-python,elibixby/gcloud-python,dhermes/google-cloud-python,optimizely/gcloud-python,vj-ug/gcloud-python,jgeewax/gcloud-python
python
## Code Before: """GCloud API access in idiomatic Python.""" __version__ = '0.02.2' ## Instruction: Read module version from setup.py ## Code After: """GCloud API access in idiomatic Python.""" from pkg_resources import get_distribution __version__ = get_distribution('gcloud').version
// ... existing code ... """GCloud API access in idiomatic Python.""" from pkg_resources import get_distribution __version__ = get_distribution('gcloud').version // ... rest of the code ...
e9a445a4c12986680654e1ccb2feb3917ccbd263
setup.py
setup.py
from setuptools import setup, find_packages setup(name='addressable', description='Use lists like you would dictionaries.', long_description=open('README.rst').read(), author='Stijn Debrouwere', author_email='[email protected]', url='http://stdbrouw.github.com/python-addressable/', download_url='http://www.github.com/stdbrouw/python-addressable/tarball/master', version='1.1.0', license='ISC', packages=find_packages(), keywords='utility', classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', ], )
from setuptools import setup, find_packages setup(name='addressable', description='Use lists like you would dictionaries.', long_description=open('README.rst').read(), author='Stijn Debrouwere', author_email='[email protected]', url='https://github.com/debrouwere/python-addressable/', download_url='http://www.github.com/debrouwere/python-addressable/tarball/master', version='1.1.1', license='ISC', packages=find_packages(), keywords='utility', classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', ], )
Fix faulty URL reference in the package metadata.
Fix faulty URL reference in the package metadata.
Python
isc
debrouwere/python-addressable
python
## Code Before: from setuptools import setup, find_packages setup(name='addressable', description='Use lists like you would dictionaries.', long_description=open('README.rst').read(), author='Stijn Debrouwere', author_email='[email protected]', url='http://stdbrouw.github.com/python-addressable/', download_url='http://www.github.com/stdbrouw/python-addressable/tarball/master', version='1.1.0', license='ISC', packages=find_packages(), keywords='utility', classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', ], ) ## Instruction: Fix faulty URL reference in the package metadata. ## Code After: from setuptools import setup, find_packages setup(name='addressable', description='Use lists like you would dictionaries.', long_description=open('README.rst').read(), author='Stijn Debrouwere', author_email='[email protected]', url='https://github.com/debrouwere/python-addressable/', download_url='http://www.github.com/debrouwere/python-addressable/tarball/master', version='1.1.1', license='ISC', packages=find_packages(), keywords='utility', classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities', ], )
# ... existing code ... description='Use lists like you would dictionaries.', long_description=open('README.rst').read(), author='Stijn Debrouwere', author_email='[email protected]', url='https://github.com/debrouwere/python-addressable/', download_url='http://www.github.com/debrouwere/python-addressable/tarball/master', version='1.1.1', license='ISC', packages=find_packages(), keywords='utility', # ... rest of the code ...
d6bc297b71c9cb2bce45bdcd20f99f9fe642cf01
plotting.py
plotting.py
class ColorMarker: def __init__(self): # A list of colors self._colors = ['k', 'b', 'g', 'c', 'm', 'y'] # A list of markers self._markers = ['o', 's', '^', 'D', 'd', 'h', 'x', '*', '+', 'v', '<', '>', '1', '2', '3', '4', '8', 'p', 'H'] def get_colors(self): """ Get a set of color/marker combinations. :rtype: list of tuple :returns: A list of tuples containing color|marker pairs. There are a total of 114 combinations. Red and white are not used in this color scheme. Red is reserved for coloring points beyond a threshold, and white does not show up on white backgrounds. """ comb = list() for i in self._markers: for j in self._colors: comb.append((j, i)) return comb
class ColorMarker: def __init__(self): # A list of colors self._colors = ['k', 'b', 'g', 'c', 'm', 'y'] # A list of markers self._markers = ['o', 's', '^', 'D', 'd', 'h', 'x', '*', '+', 'v', '<', '>', '1', '2', '3', '4', '8', 'p', 'H'] def get_colors(self): """ Get a set of color/marker combinations. :rtype: list of tuple :returns: A list of tuples containing color|marker pairs. There are a total of 114 combinations. Red and white are not used in this color scheme. Red is reserved for coloring points beyond a threshold, and white does not show up on white backgrounds. """ comb = list() for marker in self._markers: for color in self._colors: comb.append((color, marker)) return comb
Fix naming to folliwng naming conventions for mclab
Fix naming to folliwng naming conventions for mclab
Python
mit
secimTools/SECIMTools,secimTools/SECIMTools,secimTools/SECIMTools
python
## Code Before: class ColorMarker: def __init__(self): # A list of colors self._colors = ['k', 'b', 'g', 'c', 'm', 'y'] # A list of markers self._markers = ['o', 's', '^', 'D', 'd', 'h', 'x', '*', '+', 'v', '<', '>', '1', '2', '3', '4', '8', 'p', 'H'] def get_colors(self): """ Get a set of color/marker combinations. :rtype: list of tuple :returns: A list of tuples containing color|marker pairs. There are a total of 114 combinations. Red and white are not used in this color scheme. Red is reserved for coloring points beyond a threshold, and white does not show up on white backgrounds. """ comb = list() for i in self._markers: for j in self._colors: comb.append((j, i)) return comb ## Instruction: Fix naming to folliwng naming conventions for mclab ## Code After: class ColorMarker: def __init__(self): # A list of colors self._colors = ['k', 'b', 'g', 'c', 'm', 'y'] # A list of markers self._markers = ['o', 's', '^', 'D', 'd', 'h', 'x', '*', '+', 'v', '<', '>', '1', '2', '3', '4', '8', 'p', 'H'] def get_colors(self): """ Get a set of color/marker combinations. :rtype: list of tuple :returns: A list of tuples containing color|marker pairs. There are a total of 114 combinations. Red and white are not used in this color scheme. Red is reserved for coloring points beyond a threshold, and white does not show up on white backgrounds. """ comb = list() for marker in self._markers: for color in self._colors: comb.append((color, marker)) return comb
# ... existing code ... """ comb = list() for marker in self._markers: for color in self._colors: comb.append((color, marker)) return comb # ... rest of the code ...
9be232ab83a4c482eaf56ea99f7b1be81412c517
Bookie/fabfile/development.py
Bookie/fabfile/development.py
"""Fabric commands useful for working on developing Bookie are loaded here""" from fabric.api import hosts from fabric.api import local from fabric.contrib.project import rsync_project bootstrap_host = 'ubuntu@bmark' bootstrap_server = '/var/www/bootstrap.py' bootstrap_local = 'scripts/bootstrap/bootstrap.py' def gen_bootstrap(): """Run the generator that builds a custom virtualenv bootstrap file""" local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False) @hosts(bootstrap_host) def push_bootstrap(): """Sync the bootstrap.py up to the server for download""" rsync_project(bootstrap_server, bootstrap_local)
"""Fabric commands useful for working on developing Bookie are loaded here""" import os from fabric.api import hosts from fabric.api import local from fabric.contrib.project import rsync_project bootstrap_host = 'ubuntu@bmark' bootstrap_server = '/var/www/bootstrap.py' bootstrap_local = 'scripts/bootstrap/bootstrap.py' def gen_bootstrap(): """Run the generator that builds a custom virtualenv bootstrap file""" local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False) @hosts(bootstrap_host) def push_bootstrap(): """Sync the bootstrap.py up to the server for download""" rsync_project(bootstrap_server, bootstrap_local) def jstest(): """Launch the JS tests we have in the system Currently only the ones there are for extensions """ cwd = os.path.dirname(os.path.dirname(__file__)) local('google-chrome {0}/extensions/tests/index.html'.format(cwd))
Add a fab command to run jstests
Add a fab command to run jstests
Python
agpl-3.0
adamlincoln/Bookie,skmezanul/Bookie,charany1/Bookie,charany1/Bookie,adamlincoln/Bookie,bookieio/Bookie,wangjun/Bookie,teodesson/Bookie,GreenLunar/Bookie,wangjun/Bookie,teodesson/Bookie,GreenLunar/Bookie,pombredanne/Bookie,pombredanne/Bookie,charany1/Bookie,GreenLunar/Bookie,skmezanul/Bookie,teodesson/Bookie,wangjun/Bookie,teodesson/Bookie,bookieio/Bookie,adamlincoln/Bookie,adamlincoln/Bookie,bookieio/Bookie,bookieio/Bookie,GreenLunar/Bookie,skmezanul/Bookie,pombredanne/Bookie,skmezanul/Bookie,wangjun/Bookie
python
## Code Before: """Fabric commands useful for working on developing Bookie are loaded here""" from fabric.api import hosts from fabric.api import local from fabric.contrib.project import rsync_project bootstrap_host = 'ubuntu@bmark' bootstrap_server = '/var/www/bootstrap.py' bootstrap_local = 'scripts/bootstrap/bootstrap.py' def gen_bootstrap(): """Run the generator that builds a custom virtualenv bootstrap file""" local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False) @hosts(bootstrap_host) def push_bootstrap(): """Sync the bootstrap.py up to the server for download""" rsync_project(bootstrap_server, bootstrap_local) ## Instruction: Add a fab command to run jstests ## Code After: """Fabric commands useful for working on developing Bookie are loaded here""" import os from fabric.api import hosts from fabric.api import local from fabric.contrib.project import rsync_project bootstrap_host = 'ubuntu@bmark' bootstrap_server = '/var/www/bootstrap.py' bootstrap_local = 'scripts/bootstrap/bootstrap.py' def gen_bootstrap(): """Run the generator that builds a custom virtualenv bootstrap file""" local('python scripts/bootstrap/gen_bootstrap.py > scripts/bootstrap/bootstrap.py', capture=False) @hosts(bootstrap_host) def push_bootstrap(): """Sync the bootstrap.py up to the server for download""" rsync_project(bootstrap_server, bootstrap_local) def jstest(): """Launch the JS tests we have in the system Currently only the ones there are for extensions """ cwd = os.path.dirname(os.path.dirname(__file__)) local('google-chrome {0}/extensions/tests/index.html'.format(cwd))
// ... existing code ... """Fabric commands useful for working on developing Bookie are loaded here""" import os from fabric.api import hosts from fabric.api import local from fabric.contrib.project import rsync_project // ... modified code ... def push_bootstrap(): """Sync the bootstrap.py up to the server for download""" rsync_project(bootstrap_server, bootstrap_local) def jstest(): """Launch the JS tests we have in the system Currently only the ones there are for extensions """ cwd = os.path.dirname(os.path.dirname(__file__)) local('google-chrome {0}/extensions/tests/index.html'.format(cwd)) // ... rest of the code ...
c4b49a37178283d38d7a1a2b32cc985058c41dc1
app/src/main/java/com/doctoror/fuckoffmusicplayer/di/DaggerHolder.java
app/src/main/java/com/doctoror/fuckoffmusicplayer/di/DaggerHolder.java
/* * Copyright (C) 2017 Yaroslav Mytkalyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.doctoror.fuckoffmusicplayer.di; import android.content.Context; import android.support.annotation.NonNull; /** * Dagger2 {@link MainComponent} holder */ public final class DaggerHolder { private static volatile DaggerHolder instance; @NonNull public static DaggerHolder getInstance(@NonNull final Context context) { if (instance == null) { synchronized (DaggerHolder.class) { if (instance == null) { instance = new DaggerHolder(context.getApplicationContext()); } } } return instance; } @NonNull private final MainComponent mainComponent; private DaggerHolder(@NonNull final Context context) { final AppModule appContextModule = new AppModule(context); mainComponent = DaggerMainComponent.builder() .appContextModule(appContextModule) .build(); } @NonNull public MainComponent mainComponent() { return mainComponent; } }
/* * Copyright (C) 2017 Yaroslav Mytkalyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.doctoror.fuckoffmusicplayer.di; import android.content.Context; import android.support.annotation.NonNull; /** * Dagger2 {@link MainComponent} holder */ public final class DaggerHolder { private static volatile DaggerHolder instance; @NonNull public static DaggerHolder getInstance(@NonNull final Context context) { if (instance == null) { synchronized (DaggerHolder.class) { if (instance == null) { instance = new DaggerHolder(context.getApplicationContext()); } } } return instance; } @NonNull private final MainComponent mainComponent; private DaggerHolder(@NonNull final Context context) { final AppModule appModule = new AppModule(context); mainComponent = DaggerMainComponent.builder() .appModule(appModule) .build(); } @NonNull public MainComponent mainComponent() { return mainComponent; } }
Rename appContextModule variable to appModule.
Rename appContextModule variable to appModule.
Java
apache-2.0
Doctoror/PainlessMusicPlayer,Doctoror/PainlessMusicPlayer,Doctoror/PainlessMusicPlayer,Doctoror/FuckOffMusicPlayer,Doctoror/FuckOffMusicPlayer
java
## Code Before: /* * Copyright (C) 2017 Yaroslav Mytkalyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.doctoror.fuckoffmusicplayer.di; import android.content.Context; import android.support.annotation.NonNull; /** * Dagger2 {@link MainComponent} holder */ public final class DaggerHolder { private static volatile DaggerHolder instance; @NonNull public static DaggerHolder getInstance(@NonNull final Context context) { if (instance == null) { synchronized (DaggerHolder.class) { if (instance == null) { instance = new DaggerHolder(context.getApplicationContext()); } } } return instance; } @NonNull private final MainComponent mainComponent; private DaggerHolder(@NonNull final Context context) { final AppModule appContextModule = new AppModule(context); mainComponent = DaggerMainComponent.builder() .appContextModule(appContextModule) .build(); } @NonNull public MainComponent mainComponent() { return mainComponent; } } ## Instruction: Rename appContextModule variable to appModule. ## Code After: /* * Copyright (C) 2017 Yaroslav Mytkalyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.doctoror.fuckoffmusicplayer.di; import android.content.Context; import android.support.annotation.NonNull; /** * Dagger2 {@link MainComponent} holder */ public final class DaggerHolder { private static volatile DaggerHolder instance; @NonNull public static DaggerHolder getInstance(@NonNull final Context context) { if (instance == null) { synchronized (DaggerHolder.class) { if (instance == null) { instance = new DaggerHolder(context.getApplicationContext()); } } } return instance; } @NonNull private final MainComponent mainComponent; private DaggerHolder(@NonNull final Context context) { final AppModule appModule = new AppModule(context); mainComponent = DaggerMainComponent.builder() .appModule(appModule) .build(); } @NonNull public MainComponent mainComponent() { return mainComponent; } }
# ... existing code ... private final MainComponent mainComponent; private DaggerHolder(@NonNull final Context context) { final AppModule appModule = new AppModule(context); mainComponent = DaggerMainComponent.builder() .appModule(appModule) .build(); } # ... rest of the code ...
1efee7879cd4c6dda74f38f807155a8497fd046d
test/CodeGen/unsupported.c
test/CodeGen/unsupported.c
// RUN: clang -verify -emit-llvm -o - %s int f0(int x) { int vla[x]; return vla[x-1]; // expected-error {{cannot compile this return inside scope with VLA yet}} }
// RUN: clang -verify -emit-llvm -o - %s void *x = L"foo"; // expected-error {{cannot compile this wide string yet}}
Update test case; VLA's are now supported.
Update test case; VLA's are now supported. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@64168 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang
c
## Code Before: // RUN: clang -verify -emit-llvm -o - %s int f0(int x) { int vla[x]; return vla[x-1]; // expected-error {{cannot compile this return inside scope with VLA yet}} } ## Instruction: Update test case; VLA's are now supported. git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@64168 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: // RUN: clang -verify -emit-llvm -o - %s void *x = L"foo"; // expected-error {{cannot compile this wide string yet}}
// ... existing code ... // RUN: clang -verify -emit-llvm -o - %s void *x = L"foo"; // expected-error {{cannot compile this wide string yet}} // ... rest of the code ...
fcdc3974015499f822d9e3355a6fe937c18eaf9a
src/nodeconductor_assembly_waldur/slurm_invoices/models.py
src/nodeconductor_assembly_waldur/slurm_invoices/models.py
from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))])
from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): class Meta(object): verbose_name = _('SLURM package') verbose_name_plural = _('SLURM packages') PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))])
Add verbose name for SLURM package
Add verbose name for SLURM package [WAL-1141]
Python
mit
opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind
python
## Code Before: from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ## Instruction: Add verbose name for SLURM package [WAL-1141] ## Code After: from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): class Meta(object): verbose_name = _('SLURM package') verbose_name_plural = _('SLURM packages') PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))])
// ... existing code ... class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): class Meta(object): verbose_name = _('SLURM package') verbose_name_plural = _('SLURM packages') PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 // ... rest of the code ...
7139bbd8b0461f1549508206e7caf29b6fe85254
setup.py
setup.py
from setuptools import setup packages = [ 'cortex', 'cortex._lib', 'cortex.built_ins', 'cortex._lib.data', 'cortex.built_ins.datasets', 'cortex.built_ins.models', 'cortex.built_ins.networks', 'cortex.built_ins.transforms' ] install_requirements = [ 'imageio', 'torch', 'imageio', 'matplotlib', 'progressbar2', 'scipy', 'sklearn', 'torchvision', 'visdom', 'pyyaml', 'pathlib' ] setup( name='cortex', version='0.1', description='A library for wrapping your pytorch code', author='R Devon Hjelm', author_email='[email protected]', packages=packages, install_requires=install_requirements, entry_points={'console_scripts': ['cortex=cortex.main:main']}, zip_safe=False)
from setuptools import setup packages = [ 'cortex', 'cortex._lib', 'cortex.built_ins', 'cortex._lib.data', 'cortex.built_ins.datasets', 'cortex.built_ins.models', 'cortex.built_ins.networks', 'cortex.built_ins.transforms'] setup(name='cortex', version='0.1', description='A library for wrapping your pytorch code', author='R Devon Hjelm', author_email='[email protected]', packages=packages, install_requires=[ 'imageio', 'matplotlib', 'progressbar2', 'scipy', 'sklearn', 'torchvision', 'visdom', 'pyyaml'], entry_points={ 'console_scripts': [ 'cortex=cortex.main:run'] }, zip_safe=False)
Fix console_script out of date after branch reconstruction.
Fix console_script out of date after branch reconstruction.
Python
bsd-3-clause
rdevon/cortex,rdevon/cortex
python
## Code Before: from setuptools import setup packages = [ 'cortex', 'cortex._lib', 'cortex.built_ins', 'cortex._lib.data', 'cortex.built_ins.datasets', 'cortex.built_ins.models', 'cortex.built_ins.networks', 'cortex.built_ins.transforms' ] install_requirements = [ 'imageio', 'torch', 'imageio', 'matplotlib', 'progressbar2', 'scipy', 'sklearn', 'torchvision', 'visdom', 'pyyaml', 'pathlib' ] setup( name='cortex', version='0.1', description='A library for wrapping your pytorch code', author='R Devon Hjelm', author_email='[email protected]', packages=packages, install_requires=install_requirements, entry_points={'console_scripts': ['cortex=cortex.main:main']}, zip_safe=False) ## Instruction: Fix console_script out of date after branch reconstruction. ## Code After: from setuptools import setup packages = [ 'cortex', 'cortex._lib', 'cortex.built_ins', 'cortex._lib.data', 'cortex.built_ins.datasets', 'cortex.built_ins.models', 'cortex.built_ins.networks', 'cortex.built_ins.transforms'] setup(name='cortex', version='0.1', description='A library for wrapping your pytorch code', author='R Devon Hjelm', author_email='[email protected]', packages=packages, install_requires=[ 'imageio', 'matplotlib', 'progressbar2', 'scipy', 'sklearn', 'torchvision', 'visdom', 'pyyaml'], entry_points={ 'console_scripts': [ 'cortex=cortex.main:run'] }, zip_safe=False)
// ... existing code ... from setuptools import setup packages = [ 'cortex', 'cortex._lib', 'cortex.built_ins', 'cortex._lib.data', 'cortex.built_ins.datasets', 'cortex.built_ins.models', 'cortex.built_ins.networks', 'cortex.built_ins.transforms'] setup(name='cortex', version='0.1', description='A library for wrapping your pytorch code', author='R Devon Hjelm', author_email='[email protected]', packages=packages, install_requires=[ 'imageio', 'matplotlib', 'progressbar2', 'scipy', 'sklearn', 'torchvision', 'visdom', 'pyyaml'], entry_points={ 'console_scripts': [ 'cortex=cortex.main:run'] }, zip_safe=False) // ... rest of the code ...
7ea0e2d8387b622f671638613a476dcbff6438e1
rest_framework_swagger/urls.py
rest_framework_swagger/urls.py
from django.conf.urls import patterns from django.conf.urls import url from rest_framework_swagger.views import SwaggerResourcesView, SwaggerApiView, SwaggerUIView urlpatterns = patterns( '', url(r'^$', SwaggerUIView.as_view(), name="django.swagger.base.view"), url(r'^api-docs/$', SwaggerResourcesView.as_view(), name="django.swagger.resources.view"), url(r'^api-docs/(?P<path>.*)/?$', SwaggerApiView.as_view(), name='django.swagger.api.view'), )
from django.conf.urls import url from rest_framework_swagger.views import SwaggerResourcesView, SwaggerApiView, SwaggerUIView urlpatterns = [ url(r'^$', SwaggerUIView.as_view(), name="django.swagger.base.view"), url(r'^api-docs/$', SwaggerResourcesView.as_view(), name="django.swagger.resources.view"), url(r'^api-docs/(?P<path>.*)/?$', SwaggerApiView.as_view(), name='django.swagger.api.view'), ]
Use the new style urlpatterns syntax to fix Django deprecation warnings
Use the new style urlpatterns syntax to fix Django deprecation warnings The `patterns()` syntax is now deprecated: https://docs.djangoproject.com/en/1.8/releases/1.8/#django-conf-urls-patterns And so under Django 1.8 results in warnings: rest_framework_swagger/urls.py:10: RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead. Fixes #380.
Python
bsd-2-clause
pombredanne/django-rest-swagger,aioTV/django-rest-swagger,cancan101/django-rest-swagger,visasq/django-rest-swagger,aioTV/django-rest-swagger,marcgibbons/django-rest-swagger,marcgibbons/django-rest-swagger,aioTV/django-rest-swagger,cancan101/django-rest-swagger,pombredanne/django-rest-swagger,arc6373/django-rest-swagger,cancan101/django-rest-swagger,visasq/django-rest-swagger,arc6373/django-rest-swagger,marcgibbons/django-rest-swagger,pombredanne/django-rest-swagger,marcgibbons/django-rest-swagger,visasq/django-rest-swagger,arc6373/django-rest-swagger,pombredanne/django-rest-swagger
python
## Code Before: from django.conf.urls import patterns from django.conf.urls import url from rest_framework_swagger.views import SwaggerResourcesView, SwaggerApiView, SwaggerUIView urlpatterns = patterns( '', url(r'^$', SwaggerUIView.as_view(), name="django.swagger.base.view"), url(r'^api-docs/$', SwaggerResourcesView.as_view(), name="django.swagger.resources.view"), url(r'^api-docs/(?P<path>.*)/?$', SwaggerApiView.as_view(), name='django.swagger.api.view'), ) ## Instruction: Use the new style urlpatterns syntax to fix Django deprecation warnings The `patterns()` syntax is now deprecated: https://docs.djangoproject.com/en/1.8/releases/1.8/#django-conf-urls-patterns And so under Django 1.8 results in warnings: rest_framework_swagger/urls.py:10: RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead. Fixes #380. ## Code After: from django.conf.urls import url from rest_framework_swagger.views import SwaggerResourcesView, SwaggerApiView, SwaggerUIView urlpatterns = [ url(r'^$', SwaggerUIView.as_view(), name="django.swagger.base.view"), url(r'^api-docs/$', SwaggerResourcesView.as_view(), name="django.swagger.resources.view"), url(r'^api-docs/(?P<path>.*)/?$', SwaggerApiView.as_view(), name='django.swagger.api.view'), ]
// ... existing code ... from django.conf.urls import url from rest_framework_swagger.views import SwaggerResourcesView, SwaggerApiView, SwaggerUIView urlpatterns = [ url(r'^$', SwaggerUIView.as_view(), name="django.swagger.base.view"), url(r'^api-docs/$', SwaggerResourcesView.as_view(), name="django.swagger.resources.view"), url(r'^api-docs/(?P<path>.*)/?$', SwaggerApiView.as_view(), name='django.swagger.api.view'), ] // ... rest of the code ...
1dfbe495972a5f4d02ce374131f40d4474f24cc6
website/ember_osf_web/views.py
website/ember_osf_web/views.py
import os import json import requests from flask import send_from_directory, Response, stream_with_context from framework.sessions import session from website.settings import EXTERNAL_EMBER_APPS, PROXY_EMBER_APPS, EXTERNAL_EMBER_SERVER_TIMEOUT ember_osf_web_dir = os.path.abspath(os.path.join(os.getcwd(), EXTERNAL_EMBER_APPS['ember_osf_web']['path'])) routes = [ '/quickfiles/', '/<uid>/quickfiles/' ] def use_ember_app(**kwargs): if PROXY_EMBER_APPS: resp = requests.get(EXTERNAL_EMBER_APPS['ember_osf_web']['server'], stream=True, timeout=EXTERNAL_EMBER_SERVER_TIMEOUT) resp = Response(stream_with_context(resp.iter_content()), resp.status_code) else: resp = send_from_directory(ember_osf_web_dir, 'index.html') if session.data.get('status'): status = [{'id': stat.id if stat.id else stat.message, 'class': stat.css_class, 'jumbo': stat.jumbotron, 'dismiss': stat.dismissible, 'extra': stat.extra} for stat in session.data['status']] resp.set_cookie('status', json.dumps(status)) return resp
import os import json import requests from flask import send_from_directory, Response, stream_with_context from framework.sessions import session from website.settings import EXTERNAL_EMBER_APPS, PROXY_EMBER_APPS, EXTERNAL_EMBER_SERVER_TIMEOUT ember_osf_web_dir = os.path.abspath(os.path.join(os.getcwd(), EXTERNAL_EMBER_APPS['ember_osf_web']['path'])) routes = [ '/quickfiles/', '/<uid>/quickfiles/' ] def use_ember_app(**kwargs): if PROXY_EMBER_APPS: resp = requests.get(EXTERNAL_EMBER_APPS['ember_osf_web']['server'], stream=True, timeout=EXTERNAL_EMBER_SERVER_TIMEOUT) resp = Response(stream_with_context(resp.iter_content()), resp.status_code) else: resp = send_from_directory(ember_osf_web_dir, 'index.html') if session.data.get('status'): status = [{'id': stat[5] if stat[5] else stat[0], 'class': stat[2], 'jumbo': stat[1], 'dismiss': stat[3], 'extra': stat[6]} for stat in session.data['status']] resp.set_cookie('status', json.dumps(status)) return resp
Revert "Use namedtuple's getattr rather than indexing"
Revert "Use namedtuple's getattr rather than indexing" This reverts commit 5c4f93207c1fbfe9b9a478082d5f039a9e5ba720.
Python
apache-2.0
Johnetordoff/osf.io,adlius/osf.io,aaxelb/osf.io,felliott/osf.io,mfraezz/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,icereval/osf.io,cslzchen/osf.io,Johnetordoff/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,saradbowman/osf.io,mattclark/osf.io,aaxelb/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,sloria/osf.io,felliott/osf.io,felliott/osf.io,brianjgeiger/osf.io,binoculars/osf.io,pattisdr/osf.io,adlius/osf.io,sloria/osf.io,Johnetordoff/osf.io,mattclark/osf.io,mfraezz/osf.io,adlius/osf.io,mfraezz/osf.io,icereval/osf.io,cslzchen/osf.io,aaxelb/osf.io,erinspace/osf.io,aaxelb/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,icereval/osf.io,binoculars/osf.io,baylee-d/osf.io,baylee-d/osf.io,caseyrollins/osf.io,felliott/osf.io,erinspace/osf.io,caseyrollins/osf.io,saradbowman/osf.io,brianjgeiger/osf.io,brianjgeiger/osf.io,adlius/osf.io,baylee-d/osf.io,binoculars/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,sloria/osf.io
python
## Code Before: import os import json import requests from flask import send_from_directory, Response, stream_with_context from framework.sessions import session from website.settings import EXTERNAL_EMBER_APPS, PROXY_EMBER_APPS, EXTERNAL_EMBER_SERVER_TIMEOUT ember_osf_web_dir = os.path.abspath(os.path.join(os.getcwd(), EXTERNAL_EMBER_APPS['ember_osf_web']['path'])) routes = [ '/quickfiles/', '/<uid>/quickfiles/' ] def use_ember_app(**kwargs): if PROXY_EMBER_APPS: resp = requests.get(EXTERNAL_EMBER_APPS['ember_osf_web']['server'], stream=True, timeout=EXTERNAL_EMBER_SERVER_TIMEOUT) resp = Response(stream_with_context(resp.iter_content()), resp.status_code) else: resp = send_from_directory(ember_osf_web_dir, 'index.html') if session.data.get('status'): status = [{'id': stat.id if stat.id else stat.message, 'class': stat.css_class, 'jumbo': stat.jumbotron, 'dismiss': stat.dismissible, 'extra': stat.extra} for stat in session.data['status']] resp.set_cookie('status', json.dumps(status)) return resp ## Instruction: Revert "Use namedtuple's getattr rather than indexing" This reverts commit 5c4f93207c1fbfe9b9a478082d5f039a9e5ba720. ## Code After: import os import json import requests from flask import send_from_directory, Response, stream_with_context from framework.sessions import session from website.settings import EXTERNAL_EMBER_APPS, PROXY_EMBER_APPS, EXTERNAL_EMBER_SERVER_TIMEOUT ember_osf_web_dir = os.path.abspath(os.path.join(os.getcwd(), EXTERNAL_EMBER_APPS['ember_osf_web']['path'])) routes = [ '/quickfiles/', '/<uid>/quickfiles/' ] def use_ember_app(**kwargs): if PROXY_EMBER_APPS: resp = requests.get(EXTERNAL_EMBER_APPS['ember_osf_web']['server'], stream=True, timeout=EXTERNAL_EMBER_SERVER_TIMEOUT) resp = Response(stream_with_context(resp.iter_content()), resp.status_code) else: resp = send_from_directory(ember_osf_web_dir, 'index.html') if session.data.get('status'): status = [{'id': stat[5] if stat[5] else stat[0], 'class': stat[2], 'jumbo': stat[1], 'dismiss': stat[3], 'extra': stat[6]} for stat in session.data['status']] resp.set_cookie('status', json.dumps(status)) return resp
... else: resp = send_from_directory(ember_osf_web_dir, 'index.html') if session.data.get('status'): status = [{'id': stat[5] if stat[5] else stat[0], 'class': stat[2], 'jumbo': stat[1], 'dismiss': stat[3], 'extra': stat[6]} for stat in session.data['status']] resp.set_cookie('status', json.dumps(status)) return resp ...
a0605e1be5980f9c2f80fe0e751e736a3f4b48ef
fiji_skeleton_macro.py
fiji_skeleton_macro.py
import sys from ij import IJ def ij_binary_skeletonize(impath_in, impath_out): """Load image `impath`, skeletonize it, and save it to the same file. Parameters ---------- impath_in : string Path to a 3D image file. impath_out : string Path to which to write the skeleton image file. Returns ------- None """ imp = IJ.openImage(impath_in) IJ.run(imp, "Skeletonize (2D/3D)", "") IJ.saveAs(imp, "Tiff", impath_out) imp.close() if __name__ == '__main__': print sys.argv ij_binary_skeletonize(sys.argv[1], sys.argv[2])
import sys from ij import IJ def ij_binary_skeletonize(impath_in, impath_out): """Load image `impath`, skeletonize it, and save it to the same file. Parameters ---------- impath_in : string Path to a 3D image file. impath_out : string Path to which to write the skeleton image file. Returns ------- None """ imp = IJ.openImage(impath_in) IJ.run(imp, "Skeletonize (2D/3D)", "") IJ.run(imp, "Analyze Skeleton (2D/3D)", "prune=none prune") IJ.saveAs(imp, "Tiff", impath_out) imp.close() if __name__ == '__main__': print sys.argv ij_binary_skeletonize(sys.argv[1], sys.argv[2])
Add pruning step to skeletonization
Add pruning step to skeletonization This requires an updated Fiji, as detailed in this mailing list thread: https://list.nih.gov/cgi-bin/wa.exe?A1=ind1308&L=IMAGEJ#41 https://list.nih.gov/cgi-bin/wa.exe?A2=ind1308&L=IMAGEJ&F=&S=&P=36891
Python
bsd-3-clause
jni/skeletons
python
## Code Before: import sys from ij import IJ def ij_binary_skeletonize(impath_in, impath_out): """Load image `impath`, skeletonize it, and save it to the same file. Parameters ---------- impath_in : string Path to a 3D image file. impath_out : string Path to which to write the skeleton image file. Returns ------- None """ imp = IJ.openImage(impath_in) IJ.run(imp, "Skeletonize (2D/3D)", "") IJ.saveAs(imp, "Tiff", impath_out) imp.close() if __name__ == '__main__': print sys.argv ij_binary_skeletonize(sys.argv[1], sys.argv[2]) ## Instruction: Add pruning step to skeletonization This requires an updated Fiji, as detailed in this mailing list thread: https://list.nih.gov/cgi-bin/wa.exe?A1=ind1308&L=IMAGEJ#41 https://list.nih.gov/cgi-bin/wa.exe?A2=ind1308&L=IMAGEJ&F=&S=&P=36891 ## Code After: import sys from ij import IJ def ij_binary_skeletonize(impath_in, impath_out): """Load image `impath`, skeletonize it, and save it to the same file. Parameters ---------- impath_in : string Path to a 3D image file. impath_out : string Path to which to write the skeleton image file. Returns ------- None """ imp = IJ.openImage(impath_in) IJ.run(imp, "Skeletonize (2D/3D)", "") IJ.run(imp, "Analyze Skeleton (2D/3D)", "prune=none prune") IJ.saveAs(imp, "Tiff", impath_out) imp.close() if __name__ == '__main__': print sys.argv ij_binary_skeletonize(sys.argv[1], sys.argv[2])
# ... existing code ... """ imp = IJ.openImage(impath_in) IJ.run(imp, "Skeletonize (2D/3D)", "") IJ.run(imp, "Analyze Skeleton (2D/3D)", "prune=none prune") IJ.saveAs(imp, "Tiff", impath_out) imp.close() # ... rest of the code ...
33eb1ea53c3f999a1134dd180bc4b1d8e38d6a80
setup.py
setup.py
from setuptools import setup, find_packages setup( name="ghostwriter", version="0.0.1", packages=find_packages(), include_package_data=True, install_requires=[ 'flask', "six", "enum34", 'flask_login', 'flask_sqlalchemy' ], test_suite='ghostwriter.test', )
from setuptools import setup, find_packages setup( name="ghostwriter", version="0.0.2", author="Arthur M", description="a simple article/blog management tool of which *you* show how to show" packages=find_packages(), include_package_data=True, install_requires=[ 'flask', "six", "enum34", 'flask_login', 'flask_sqlalchemy' ], test_suite='ghostwriter.test', )
Add more information to the package
Add more information to the package
Python
mit
arthurmco/ghostwriter,arthurmco/ghostwriter
python
## Code Before: from setuptools import setup, find_packages setup( name="ghostwriter", version="0.0.1", packages=find_packages(), include_package_data=True, install_requires=[ 'flask', "six", "enum34", 'flask_login', 'flask_sqlalchemy' ], test_suite='ghostwriter.test', ) ## Instruction: Add more information to the package ## Code After: from setuptools import setup, find_packages setup( name="ghostwriter", version="0.0.2", author="Arthur M", description="a simple article/blog management tool of which *you* show how to show" packages=find_packages(), include_package_data=True, install_requires=[ 'flask', "six", "enum34", 'flask_login', 'flask_sqlalchemy' ], test_suite='ghostwriter.test', )
// ... existing code ... setup( name="ghostwriter", version="0.0.2", author="Arthur M", description="a simple article/blog management tool of which *you* show how to show" packages=find_packages(), include_package_data=True, install_requires=[ // ... rest of the code ...
1b9c4935b2edf6601c2d75d8a2d318266de2d456
circuits/tools/__init__.py
circuits/tools/__init__.py
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def graph(x): s = StringIO() d = 0 i = 0 done = False stack = [] visited = set() children = list(x.components) while not done: if x not in visited: if d: s.write("%s%s\n" % (" " * d, "|")) s.write("%s%s%s\n" % (" " * d, "|-", x)) else: s.write(" .%s\n" % x) if x.components: d += 1 visited.add(x) if i < len(children): x = children[i] i += 1 if x.components: stack.append((i, children)) children = list(x.components) i = 0 else: if stack: i, children = stack.pop() d -= 1 else: done = True return s.getvalue()
try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def graph(x): s = StringIO() d = 0 i = 0 done = False stack = [] visited = set() children = list(x.components) while not done: if x not in visited: if d: s.write("%s%s\n" % (" " * d, "|")) s.write("%s%s%s\n" % (" " * d, "|-", x)) else: s.write(" .%s\n" % x) if x.components: d += 1 visited.add(x) if i < len(children): x = children[i] i += 1 if x.components: stack.append((i, d, children)) children = list(x.components) i = 0 else: if stack: i, d, children = stack.pop() else: done = True return s.getvalue()
Store the depth (d) on the stack and restore when backtracking
tools: Store the depth (d) on the stack and restore when backtracking
Python
mit
treemo/circuits,treemo/circuits,eriol/circuits,treemo/circuits,eriol/circuits,nizox/circuits,eriol/circuits
python
## Code Before: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def graph(x): s = StringIO() d = 0 i = 0 done = False stack = [] visited = set() children = list(x.components) while not done: if x not in visited: if d: s.write("%s%s\n" % (" " * d, "|")) s.write("%s%s%s\n" % (" " * d, "|-", x)) else: s.write(" .%s\n" % x) if x.components: d += 1 visited.add(x) if i < len(children): x = children[i] i += 1 if x.components: stack.append((i, children)) children = list(x.components) i = 0 else: if stack: i, children = stack.pop() d -= 1 else: done = True return s.getvalue() ## Instruction: tools: Store the depth (d) on the stack and restore when backtracking ## Code After: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO def graph(x): s = StringIO() d = 0 i = 0 done = False stack = [] visited = set() children = list(x.components) while not done: if x not in visited: if d: s.write("%s%s\n" % (" " * d, "|")) s.write("%s%s%s\n" % (" " * d, "|-", x)) else: s.write(" .%s\n" % x) if x.components: d += 1 visited.add(x) if i < len(children): x = children[i] i += 1 if x.components: stack.append((i, d, children)) children = list(x.components) i = 0 else: if stack: i, d, children = stack.pop() else: done = True return s.getvalue()
# ... existing code ... x = children[i] i += 1 if x.components: stack.append((i, d, children)) children = list(x.components) i = 0 else: if stack: i, d, children = stack.pop() else: done = True # ... rest of the code ...
cff7bb0fda7e126ce65701231cab0e67a5a2794c
endpoints.py
endpoints.py
import requests class AlgoliaEndpoint(object): """Class used to call the Algolia API and parse the response.""" URL = "http://hn.algolia.com/api/v1/search_by_date" @staticmethod def get(tag, since, until=None, page=0): """Send a GET request to the endpoint. Since Algolia only returns JSON, parse it into a dict. Params: tag: Can be "story" or "comment". since: timestamp representing how old the news should be. Optional params: until: timestamp representing how new the news should be. page: The number of the page to get. Returns: A python dict representing the response. Raises: requests.exceptions.RequestException. """ numericFilters = ["created_at_i<%d" % since] if until is not None: numericFilters += ["created_at_i>%d" % until] params = { "numericFilters": ",".join(numericFilters), "tags": tag, "page": page } url = AlgoliaEndpoint.URL url += "?" + "&".join(["%s=%s" for k,v in params.items()]) response = requests.get(url) return response.json()
import requests class AlgoliaEndpoint(object): """Class used to call the Algolia API and parse the response.""" URL = "http://hn.algolia.com/api/v1/search_by_date" @staticmethod def get(tag, since, until=None, page=0): """Send a GET request to the endpoint. Since Algolia only returns JSON, parse it into a dict. See http://hn.algolia.com/api for more details. Params: tag: Can be "story" or "comment". since: timestamp representing how old the news should be. Optional params: until: timestamp representing how new the news should be. page: The number of the page to get. Returns: A python dict representing the response. Raises: requests.exceptions.RequestException. """ numericFilters = ["created_at_i<%d" % since] if until is not None: numericFilters += ["created_at_i>%d" % until] params = { "numericFilters": ",".join(numericFilters), "tags": tag, "page": page } url = AlgoliaEndpoint.URL url += "?" + "&".join(["%s=%s" for k,v in params.items()]) response = requests.get(url) return response.json()
Add Algolia API website in docstring.
Add Algolia API website in docstring.
Python
bsd-2-clause
NiGhTTraX/hackernews-scraper
python
## Code Before: import requests class AlgoliaEndpoint(object): """Class used to call the Algolia API and parse the response.""" URL = "http://hn.algolia.com/api/v1/search_by_date" @staticmethod def get(tag, since, until=None, page=0): """Send a GET request to the endpoint. Since Algolia only returns JSON, parse it into a dict. Params: tag: Can be "story" or "comment". since: timestamp representing how old the news should be. Optional params: until: timestamp representing how new the news should be. page: The number of the page to get. Returns: A python dict representing the response. Raises: requests.exceptions.RequestException. """ numericFilters = ["created_at_i<%d" % since] if until is not None: numericFilters += ["created_at_i>%d" % until] params = { "numericFilters": ",".join(numericFilters), "tags": tag, "page": page } url = AlgoliaEndpoint.URL url += "?" + "&".join(["%s=%s" for k,v in params.items()]) response = requests.get(url) return response.json() ## Instruction: Add Algolia API website in docstring. ## Code After: import requests class AlgoliaEndpoint(object): """Class used to call the Algolia API and parse the response.""" URL = "http://hn.algolia.com/api/v1/search_by_date" @staticmethod def get(tag, since, until=None, page=0): """Send a GET request to the endpoint. Since Algolia only returns JSON, parse it into a dict. See http://hn.algolia.com/api for more details. Params: tag: Can be "story" or "comment". since: timestamp representing how old the news should be. Optional params: until: timestamp representing how new the news should be. page: The number of the page to get. Returns: A python dict representing the response. Raises: requests.exceptions.RequestException. """ numericFilters = ["created_at_i<%d" % since] if until is not None: numericFilters += ["created_at_i>%d" % until] params = { "numericFilters": ",".join(numericFilters), "tags": tag, "page": page } url = AlgoliaEndpoint.URL url += "?" + "&".join(["%s=%s" for k,v in params.items()]) response = requests.get(url) return response.json()
... """Send a GET request to the endpoint. Since Algolia only returns JSON, parse it into a dict. See http://hn.algolia.com/api for more details. Params: tag: Can be "story" or "comment". ...
29877ed22477fc2a7d20fc0a2510b5ea0c81eb97
shout-to-me-sdk/src/main/java/me/shoutto/sdk/internal/http/DefaultUrlProvider.java
shout-to-me-sdk/src/main/java/me/shoutto/sdk/internal/http/DefaultUrlProvider.java
package me.shoutto.sdk.internal.http; import me.shoutto.sdk.StmBaseEntity; /** * Implementation of URL provider for Shout to Me API service endpoints */ public class DefaultUrlProvider implements StmUrlProvider { private String baseApiUrl; public DefaultUrlProvider(String baseApiUrl) { this.baseApiUrl = baseApiUrl; } @Override public String getUrl(StmBaseEntity entity, HttpMethod httpMethod) { String url = String.format("%s%s", baseApiUrl, entity.getBaseEndpoint()); if (httpMethod.equals(HttpMethod.DELETE) || httpMethod.equals(HttpMethod.PUT) || httpMethod.equals(HttpMethod.GET)) { url = url.concat(String.format("/%s", entity.getId())); } return url; } }
package me.shoutto.sdk.internal.http; import me.shoutto.sdk.StmBaseEntity; /** * Implementation of URL provider for Shout to Me API service endpoints */ public class DefaultUrlProvider implements StmUrlProvider { private String baseApiUrl; public DefaultUrlProvider(String baseApiUrl) { this.baseApiUrl = baseApiUrl; } @Override public String getUrl(StmBaseEntity entity, HttpMethod httpMethod) { String url = String.format("%s%s", baseApiUrl, entity.getBaseEndpoint()); if (httpMethod.equals(HttpMethod.DELETE) || httpMethod.equals(HttpMethod.PUT) || httpMethod.equals(HttpMethod.GET)) { if (entity.getId() != null) { url = url.concat(String.format("/%s", entity.getId())); } } return url; } }
Add some protection to default url provider
Add some protection to default url provider
Java
mit
ShoutToMe/stm-sdk-android
java
## Code Before: package me.shoutto.sdk.internal.http; import me.shoutto.sdk.StmBaseEntity; /** * Implementation of URL provider for Shout to Me API service endpoints */ public class DefaultUrlProvider implements StmUrlProvider { private String baseApiUrl; public DefaultUrlProvider(String baseApiUrl) { this.baseApiUrl = baseApiUrl; } @Override public String getUrl(StmBaseEntity entity, HttpMethod httpMethod) { String url = String.format("%s%s", baseApiUrl, entity.getBaseEndpoint()); if (httpMethod.equals(HttpMethod.DELETE) || httpMethod.equals(HttpMethod.PUT) || httpMethod.equals(HttpMethod.GET)) { url = url.concat(String.format("/%s", entity.getId())); } return url; } } ## Instruction: Add some protection to default url provider ## Code After: package me.shoutto.sdk.internal.http; import me.shoutto.sdk.StmBaseEntity; /** * Implementation of URL provider for Shout to Me API service endpoints */ public class DefaultUrlProvider implements StmUrlProvider { private String baseApiUrl; public DefaultUrlProvider(String baseApiUrl) { this.baseApiUrl = baseApiUrl; } @Override public String getUrl(StmBaseEntity entity, HttpMethod httpMethod) { String url = String.format("%s%s", baseApiUrl, entity.getBaseEndpoint()); if (httpMethod.equals(HttpMethod.DELETE) || httpMethod.equals(HttpMethod.PUT) || httpMethod.equals(HttpMethod.GET)) { if (entity.getId() != null) { url = url.concat(String.format("/%s", entity.getId())); } } return url; } }
// ... existing code ... String url = String.format("%s%s", baseApiUrl, entity.getBaseEndpoint()); if (httpMethod.equals(HttpMethod.DELETE) || httpMethod.equals(HttpMethod.PUT) || httpMethod.equals(HttpMethod.GET)) { if (entity.getId() != null) { url = url.concat(String.format("/%s", entity.getId())); } } return url; } // ... rest of the code ...
9334d20adb15f3a6be393c57c797311e31fcd8fc
ConectorDriverComando.py
ConectorDriverComando.py
from serial import SerialException import importlib import threading import logging class ConectorError(Exception): pass class ConectorDriverComando: driver = None def __init__(self, comando, driver, *args, **kwargs): logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver) self._comando = comando self.driver_name = driver # instanciar el driver dinamicamente segun el driver pasado como parametro libraryName = "Drivers." + driver + "Driver" driverModule = importlib.import_module(libraryName) driverClass = getattr(driverModule, driver + "Driver") self.driver = driverClass(**kwargs) def sendCommand(self, *args): logging.getLogger().info("Enviando comando %s" % args) return self.driver.sendCommand(*args) def close(self): # Si el driver es Receipt, se cierra desde la misma clase del driver, sino, tira error de Bad File Descriptor por querer cerrarlo dos veces. if self.driver_name == "ReceiptDirectJet": if self.driver.connected is False: return None self.driver.close() self.driver = None
from serial import SerialException import importlib import threading import logging class ConectorError(Exception): pass class ConectorDriverComando: driver = None def __init__(self, comando, driver, *args, **kwargs): # logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver) logging.getLogger().info("inicializando ConectorDriverComando driver de '${0}'".format(driver)) self._comando = comando self.driver_name = driver # instanciar el driver dinamicamente segun el driver pasado como parametro libraryName = "Drivers." + driver + "Driver" driverModule = importlib.import_module(libraryName) driverClass = getattr(driverModule, driver + "Driver") self.driver = driverClass(**kwargs) def sendCommand(self, *args): # logging.getLogger().info("Enviando comando %s" % args) logging.getLogger().info("Enviando comando '${0}'".format(args)) return self.driver.sendCommand(*args) def close(self): # Si el driver es Receipt, se cierra desde la misma clase del driver, sino, tira error de Bad File Descriptor por querer cerrarlo dos veces. if self.driver_name == "ReceiptDirectJet": if self.driver.connected is False: return None self.driver.close() self.driver = None
FIX Format String Error in Conector Driver Comando
FIX Format String Error in Conector Driver Comando
Python
mit
ristorantino/fiscalberry,ristorantino/fiscalberry,ristorantino/fiscalberry,ristorantino/fiscalberry
python
## Code Before: from serial import SerialException import importlib import threading import logging class ConectorError(Exception): pass class ConectorDriverComando: driver = None def __init__(self, comando, driver, *args, **kwargs): logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver) self._comando = comando self.driver_name = driver # instanciar el driver dinamicamente segun el driver pasado como parametro libraryName = "Drivers." + driver + "Driver" driverModule = importlib.import_module(libraryName) driverClass = getattr(driverModule, driver + "Driver") self.driver = driverClass(**kwargs) def sendCommand(self, *args): logging.getLogger().info("Enviando comando %s" % args) return self.driver.sendCommand(*args) def close(self): # Si el driver es Receipt, se cierra desde la misma clase del driver, sino, tira error de Bad File Descriptor por querer cerrarlo dos veces. if self.driver_name == "ReceiptDirectJet": if self.driver.connected is False: return None self.driver.close() self.driver = None ## Instruction: FIX Format String Error in Conector Driver Comando ## Code After: from serial import SerialException import importlib import threading import logging class ConectorError(Exception): pass class ConectorDriverComando: driver = None def __init__(self, comando, driver, *args, **kwargs): # logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver) logging.getLogger().info("inicializando ConectorDriverComando driver de '${0}'".format(driver)) self._comando = comando self.driver_name = driver # instanciar el driver dinamicamente segun el driver pasado como parametro libraryName = "Drivers." + driver + "Driver" driverModule = importlib.import_module(libraryName) driverClass = getattr(driverModule, driver + "Driver") self.driver = driverClass(**kwargs) def sendCommand(self, *args): # logging.getLogger().info("Enviando comando %s" % args) logging.getLogger().info("Enviando comando '${0}'".format(args)) return self.driver.sendCommand(*args) def close(self): # Si el driver es Receipt, se cierra desde la misma clase del driver, sino, tira error de Bad File Descriptor por querer cerrarlo dos veces. if self.driver_name == "ReceiptDirectJet": if self.driver.connected is False: return None self.driver.close() self.driver = None
# ... existing code ... driver = None def __init__(self, comando, driver, *args, **kwargs): # logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver) logging.getLogger().info("inicializando ConectorDriverComando driver de '${0}'".format(driver)) self._comando = comando self.driver_name = driver # ... modified code ... self.driver = driverClass(**kwargs) def sendCommand(self, *args): # logging.getLogger().info("Enviando comando %s" % args) logging.getLogger().info("Enviando comando '${0}'".format(args)) return self.driver.sendCommand(*args) def close(self): # ... rest of the code ...
be23c953f8f27a8d178022d3ecb44f461100bbc5
tests/__init__.py
tests/__init__.py
"""Tests for running TopoFlow components in CMI.""" import os def locate_topoflow(cache_dir): for x in os.listdir(cache_dir): if x.startswith('topoflow'): return x root_dir = '/home/csdms/wmt/topoflow.0' cache_dir = os.path.join(root_dir, 'cache') topoflow_dir = locate_topoflow(cache_dir) example_dir = os.path.join(cache_dir, topoflow_dir, 'topoflow', 'examples', 'Treynor_Iowa')
"""Tests for running TopoFlow components in CMI.""" import os def locate_topoflow(cache_dir): for x in os.listdir(cache_dir): if x.startswith('topoflow'): return x root_dir = '/home/csdms/wmt/topoflow.0' cache_dir = os.path.join(root_dir, 'cache') topoflow_dir = locate_topoflow(cache_dir) example_dir = os.path.join(cache_dir, topoflow_dir, 'topoflow', 'examples', 'Treynor_Iowa') # Used by tests for D8 and Erode components. data_dir = os.path.join(os.path.abspath('..'), 'data') test_dir = os.path.dirname(__file__)
Add path to data directory
Add path to data directory
Python
mit
mdpiper/topoflow-cmi-testing
python
## Code Before: """Tests for running TopoFlow components in CMI.""" import os def locate_topoflow(cache_dir): for x in os.listdir(cache_dir): if x.startswith('topoflow'): return x root_dir = '/home/csdms/wmt/topoflow.0' cache_dir = os.path.join(root_dir, 'cache') topoflow_dir = locate_topoflow(cache_dir) example_dir = os.path.join(cache_dir, topoflow_dir, 'topoflow', 'examples', 'Treynor_Iowa') ## Instruction: Add path to data directory ## Code After: """Tests for running TopoFlow components in CMI.""" import os def locate_topoflow(cache_dir): for x in os.listdir(cache_dir): if x.startswith('topoflow'): return x root_dir = '/home/csdms/wmt/topoflow.0' cache_dir = os.path.join(root_dir, 'cache') topoflow_dir = locate_topoflow(cache_dir) example_dir = os.path.join(cache_dir, topoflow_dir, 'topoflow', 'examples', 'Treynor_Iowa') # Used by tests for D8 and Erode components. data_dir = os.path.join(os.path.abspath('..'), 'data') test_dir = os.path.dirname(__file__)
... topoflow_dir = locate_topoflow(cache_dir) example_dir = os.path.join(cache_dir, topoflow_dir, 'topoflow', 'examples', 'Treynor_Iowa') # Used by tests for D8 and Erode components. data_dir = os.path.join(os.path.abspath('..'), 'data') test_dir = os.path.dirname(__file__) ...
a273342b6e89709fc838dfd6abcee0a525272cea
management/admin.py
management/admin.py
from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from .models import (Location, Permanence, Equipment, Lending, Position, MembershipType, Membership, PublicFile, PublicImage, ProtectedFile, ProtectedImage, AdminFile, AdminImage) class AdminFileInline(GenericTabularInline): model = AdminFile class AdminImageInline(GenericTabularInline): model = AdminImage class ProtectedFileInline(GenericTabularInline): model = ProtectedFile class ProtectedImageInline(GenericTabularInline): model = ProtectedImage class PublicFileInline(GenericTabularInline): model = PublicFile class PublicImageInline(GenericTabularInline): model = PublicImage class MembershipInline(admin.StackedInline): model = Membership extra = 0 @admin.register(MembershipType) class MembershipTypeAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') @admin.register(Position) class PositionAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') admin.site.register(Location) admin.site.register(Permanence) admin.site.register(Equipment) admin.site.register(Lending) admin.site.register(PublicFile) admin.site.register(PublicImage)
from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from .models import (Location, Permanence, Equipment, Lending, Position, MembershipType, Membership, PublicFile, PublicImage, ProtectedFile, ProtectedImage, AdminFile, AdminImage) class AdminFileInline(GenericTabularInline): model = AdminFile class AdminImageInline(GenericTabularInline): model = AdminImage class ProtectedFileInline(GenericTabularInline): model = ProtectedFile class ProtectedImageInline(GenericTabularInline): model = ProtectedImage class PublicFileInline(GenericTabularInline): model = PublicFile class PublicImageInline(GenericTabularInline): model = PublicImage class MembershipInline(admin.StackedInline): model = Membership extra = 0 @admin.register(MembershipType) class MembershipTypeAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') @admin.register(Position) class PositionAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') admin.site.register(Location) admin.site.register(Permanence) admin.site.register(Equipment) admin.site.register(Lending) admin.site.register(PublicFile) admin.site.register(PublicImage) admin.site.register(ProtectedFile) admin.site.register(ProtectedImage) admin.site.register(AdminFile) admin.site.register(AdminImage)
Add ProtectedFile, ProtectedImage, AdminFile and AdminImage.
Add ProtectedFile, ProtectedImage, AdminFile and AdminImage.
Python
mit
QSchulz/sportassociation,QSchulz/sportassociation,QSchulz/sportassociation
python
## Code Before: from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from .models import (Location, Permanence, Equipment, Lending, Position, MembershipType, Membership, PublicFile, PublicImage, ProtectedFile, ProtectedImage, AdminFile, AdminImage) class AdminFileInline(GenericTabularInline): model = AdminFile class AdminImageInline(GenericTabularInline): model = AdminImage class ProtectedFileInline(GenericTabularInline): model = ProtectedFile class ProtectedImageInline(GenericTabularInline): model = ProtectedImage class PublicFileInline(GenericTabularInline): model = PublicFile class PublicImageInline(GenericTabularInline): model = PublicImage class MembershipInline(admin.StackedInline): model = Membership extra = 0 @admin.register(MembershipType) class MembershipTypeAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') @admin.register(Position) class PositionAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') admin.site.register(Location) admin.site.register(Permanence) admin.site.register(Equipment) admin.site.register(Lending) admin.site.register(PublicFile) admin.site.register(PublicImage) ## Instruction: Add ProtectedFile, ProtectedImage, AdminFile and AdminImage. ## Code After: from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from .models import (Location, Permanence, Equipment, Lending, Position, MembershipType, Membership, PublicFile, PublicImage, ProtectedFile, ProtectedImage, AdminFile, AdminImage) class AdminFileInline(GenericTabularInline): model = AdminFile class AdminImageInline(GenericTabularInline): model = AdminImage class ProtectedFileInline(GenericTabularInline): model = ProtectedFile class ProtectedImageInline(GenericTabularInline): model = ProtectedImage class PublicFileInline(GenericTabularInline): model = PublicFile class PublicImageInline(GenericTabularInline): model = PublicImage class MembershipInline(admin.StackedInline): model = Membership extra = 0 @admin.register(MembershipType) class MembershipTypeAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') @admin.register(Position) class PositionAdmin(admin.ModelAdmin): class Media: js = ('tinymce/tinymce.min.js', 'js/tinymce_4_config.js') admin.site.register(Location) admin.site.register(Permanence) admin.site.register(Equipment) admin.site.register(Lending) admin.site.register(PublicFile) admin.site.register(PublicImage) admin.site.register(ProtectedFile) admin.site.register(ProtectedImage) admin.site.register(AdminFile) admin.site.register(AdminImage)
// ... existing code ... admin.site.register(Lending) admin.site.register(PublicFile) admin.site.register(PublicImage) admin.site.register(ProtectedFile) admin.site.register(ProtectedImage) admin.site.register(AdminFile) admin.site.register(AdminImage) // ... rest of the code ...
ab57bcc9f4219af63e99d82a844986213ade4c01
script/commit_message.py
script/commit_message.py
import re import sys import subprocess examples = """+ 61c8ca9 fix: navbar not responsive on mobile + 479c48b test: prepared test cases for user authentication + a992020 chore: moved to semantic versioning + b818120 fix: button click even handler firing twice + c6e9a97 fix: login page css + dfdc715 feat(auth): added social login using twitter """ def main(): cmd = "git log --pretty=format:'%s' master..HEAD" commits = subprocess.check_output(cmd, shell=True) commits = commits.decode("utf-8").split('\n') for commit in commits: pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa m = re.match(pattern, commit) if m is None: print("\nError with git message '{}' style".format(commit)) print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa print("\n" + examples) sys.exit(1) print("Commit messages valid") if __name__ == "__main__": main()
import re import sys import subprocess examples = """+ 61c8ca9 fix: navbar not responsive on mobile + 479c48b test: prepared test cases for user authentication + a992020 chore: moved to semantic versioning + b818120 fix: button click even handler firing twice + c6e9a97 fix: login page css + dfdc715 feat(auth): added social login using twitter """ def main(): cmd_tag = "git describe --abbrev=0" tag = subprocess.check_output(cmd_tag, shell=True).decode("utf-8").split('\n')[0] cmd = "git log --pretty=format:'%s' {}..master".format(tag) commits = subprocess.check_output(cmd, shell=True) commits = commits.decode("utf-8").split('\n') for commit in commits: pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa m = re.match(pattern, commit) if m is None: print("\nError with git message '{}' style".format(commit)) print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa print("\n" + examples) sys.exit(1) print("Commit messages valid") if __name__ == "__main__": main()
Fix script up to search branches
Fix script up to search branches
Python
mit
pact-foundation/pact-python,pact-foundation/pact-python
python
## Code Before: import re import sys import subprocess examples = """+ 61c8ca9 fix: navbar not responsive on mobile + 479c48b test: prepared test cases for user authentication + a992020 chore: moved to semantic versioning + b818120 fix: button click even handler firing twice + c6e9a97 fix: login page css + dfdc715 feat(auth): added social login using twitter """ def main(): cmd = "git log --pretty=format:'%s' master..HEAD" commits = subprocess.check_output(cmd, shell=True) commits = commits.decode("utf-8").split('\n') for commit in commits: pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa m = re.match(pattern, commit) if m is None: print("\nError with git message '{}' style".format(commit)) print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa print("\n" + examples) sys.exit(1) print("Commit messages valid") if __name__ == "__main__": main() ## Instruction: Fix script up to search branches ## Code After: import re import sys import subprocess examples = """+ 61c8ca9 fix: navbar not responsive on mobile + 479c48b test: prepared test cases for user authentication + a992020 chore: moved to semantic versioning + b818120 fix: button click even handler firing twice + c6e9a97 fix: login page css + dfdc715 feat(auth): added social login using twitter """ def main(): cmd_tag = "git describe --abbrev=0" tag = subprocess.check_output(cmd_tag, shell=True).decode("utf-8").split('\n')[0] cmd = "git log --pretty=format:'%s' {}..master".format(tag) commits = subprocess.check_output(cmd, shell=True) commits = commits.decode("utf-8").split('\n') for commit in commits: pattern = r'((build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)(\([\w\-]+\))?:\s.*)|((Merge)(\([\w\-]+\))?\s.*)' # noqa m = re.match(pattern, commit) if m is None: print("\nError with git message '{}' style".format(commit)) print("\nPlease change commit message to the conventional format and try to commit again. Examples:") # noqa print("\n" + examples) sys.exit(1) print("Commit messages valid") if __name__ == "__main__": main()
... def main(): cmd_tag = "git describe --abbrev=0" tag = subprocess.check_output(cmd_tag, shell=True).decode("utf-8").split('\n')[0] cmd = "git log --pretty=format:'%s' {}..master".format(tag) commits = subprocess.check_output(cmd, shell=True) commits = commits.decode("utf-8").split('\n') for commit in commits: ...
04a738253bbd0018784ce6ad81480b38a61b006f
etc/bin/xcode_bots/testflight/before_integration.py
etc/bin/xcode_bots/testflight/before_integration.py
PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script"
PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script"
Use the correct Info.plist in the new version of FeedbackDemo
Use the correct Info.plist in the new version of FeedbackDemo
Python
bsd-3-clause
Jawbone/apptentive-ios,ALHariPrasad/apptentive-ios,apptentive/apptentive-ios,hibu/apptentive-ios,sahara108/apptentive-ios,Jawbone/apptentive-ios,hibu/apptentive-ios,apptentive/apptentive-ios,sahara108/apptentive-ios,apptentive/apptentive-ios,hibu/apptentive-ios,ALHariPrasad/apptentive-ios
python
## Code Before: PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script" ## Instruction: Use the correct Info.plist in the new version of FeedbackDemo ## Code After: PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script"
# ... existing code ... PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH # Set unique Build Number prior to TestFlight upload cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist # Set internal Apptentive API Key and App ID for TestFlight builds cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value 980430089 --key ATTestFlightAppIDKey echo "Finished running Before Integration script" # ... rest of the code ...
a189c2976e5bb219bdf2f95d9c0bc85fae0e3404
platform/platform-api/src/com/intellij/ide/dnd/DnDManager.java
platform/platform-api/src/com/intellij/ide/dnd/DnDManager.java
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.dnd; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Key; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; public abstract class DnDManager { public static DnDManager getInstance() { return ApplicationManager.getApplication().getService(DnDManager.class); } public abstract void registerSource(@NotNull DnDSource source, @NotNull JComponent component); public abstract void registerSource(@NotNull AdvancedDnDSource source); public abstract void unregisterSource(@NotNull DnDSource source, @NotNull JComponent component); public abstract void unregisterSource(@NotNull AdvancedDnDSource source); public abstract void registerTarget(DnDTarget target, JComponent component); public abstract void unregisterTarget(DnDTarget target, JComponent component); @Nullable public abstract Component getLastDropHandler(); /** * This key is intended to switch on a smooth scrolling during drag-n-drop operations. * Note, that the target component must not use default auto-scrolling. * * @see java.awt.dnd.Autoscroll * @see JComponent#setAutoscrolls * @see JComponent#putClientProperty */ public static final Key<Boolean> AUTO_SCROLL = Key.create("AUTO_SCROLL"); }
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.dnd; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Key; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; public abstract class DnDManager { public static DnDManager getInstance() { return ApplicationManager.getApplication().getService(DnDManager.class); } public abstract void registerSource(@NotNull DnDSource source, @NotNull JComponent component); public abstract void registerSource(@NotNull AdvancedDnDSource source); public abstract void unregisterSource(@NotNull DnDSource source, @NotNull JComponent component); public abstract void unregisterSource(@NotNull AdvancedDnDSource source); public abstract void registerTarget(DnDTarget target, JComponent component); public abstract void unregisterTarget(DnDTarget target, JComponent component); @Nullable public abstract Component getLastDropHandler(); /** * This key is intended to switch on a smooth scrolling during drag-n-drop operations. * Note, that the target component must not use default auto-scrolling. * * @see java.awt.dnd.Autoscroll * @see JComponent#setAutoscrolls * @see JComponent#putClientProperty */ @ApiStatus.Experimental public static final Key<Boolean> AUTO_SCROLL = Key.create("AUTO_SCROLL"); }
Mark API as experimental, because of javax.swing.TransferHandler.DropHandler.autoscroll
Mark API as experimental, because of javax.swing.TransferHandler.DropHandler.autoscroll GitOrigin-RevId: c8522f07307517203906b9c867fd4fca6713b708
Java
apache-2.0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
java
## Code Before: // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.dnd; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Key; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; public abstract class DnDManager { public static DnDManager getInstance() { return ApplicationManager.getApplication().getService(DnDManager.class); } public abstract void registerSource(@NotNull DnDSource source, @NotNull JComponent component); public abstract void registerSource(@NotNull AdvancedDnDSource source); public abstract void unregisterSource(@NotNull DnDSource source, @NotNull JComponent component); public abstract void unregisterSource(@NotNull AdvancedDnDSource source); public abstract void registerTarget(DnDTarget target, JComponent component); public abstract void unregisterTarget(DnDTarget target, JComponent component); @Nullable public abstract Component getLastDropHandler(); /** * This key is intended to switch on a smooth scrolling during drag-n-drop operations. * Note, that the target component must not use default auto-scrolling. * * @see java.awt.dnd.Autoscroll * @see JComponent#setAutoscrolls * @see JComponent#putClientProperty */ public static final Key<Boolean> AUTO_SCROLL = Key.create("AUTO_SCROLL"); } ## Instruction: Mark API as experimental, because of javax.swing.TransferHandler.DropHandler.autoscroll GitOrigin-RevId: c8522f07307517203906b9c867fd4fca6713b708 ## Code After: // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.dnd; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Key; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; public abstract class DnDManager { public static DnDManager getInstance() { return ApplicationManager.getApplication().getService(DnDManager.class); } public abstract void registerSource(@NotNull DnDSource source, @NotNull JComponent component); public abstract void registerSource(@NotNull AdvancedDnDSource source); public abstract void unregisterSource(@NotNull DnDSource source, @NotNull JComponent component); public abstract void unregisterSource(@NotNull AdvancedDnDSource source); public abstract void registerTarget(DnDTarget target, JComponent component); public abstract void unregisterTarget(DnDTarget target, JComponent component); @Nullable public abstract Component getLastDropHandler(); /** * This key is intended to switch on a smooth scrolling during drag-n-drop operations. * Note, that the target component must not use default auto-scrolling. * * @see java.awt.dnd.Autoscroll * @see JComponent#setAutoscrolls * @see JComponent#putClientProperty */ @ApiStatus.Experimental public static final Key<Boolean> AUTO_SCROLL = Key.create("AUTO_SCROLL"); }
// ... existing code ... import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Key; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; // ... modified code ... * @see JComponent#setAutoscrolls * @see JComponent#putClientProperty */ @ApiStatus.Experimental public static final Key<Boolean> AUTO_SCROLL = Key.create("AUTO_SCROLL"); } // ... rest of the code ...
ea6732b8b282efbbec5863bfcf3414b82030c46e
test/com/karateca/ddescriber/model/TestFindResultTest.java
test/com/karateca/ddescriber/model/TestFindResultTest.java
package com.karateca.ddescriber.model; import com.intellij.find.FindResult; import com.karateca.ddescriber.BaseTestCase; import junit.framework.Assert; import java.util.List; /** * @author Andres Dominguez. */ public class TestFindResultTest extends BaseTestCase { private TestFindResult testFindResult; @Override public void setUp() throws Exception { super.setUp(); prepareScenarioWithTestFile("jasmineTestCaretTop.js"); jasmineFinder.findAll(); List<FindResult> findResults = jasmineFinder.getFindResults(); testFindResult = new TestFindResult(document, findResults.get(0)); } public void testToString() throws Exception { Assert.assertEquals("top describe", testFindResult.toString()); } }
package com.karateca.ddescriber.model; import com.intellij.find.FindResult; import com.karateca.ddescriber.BaseTestCase; import junit.framework.Assert; import java.util.List; /** * @author Andres Dominguez. */ public class TestFindResultTest extends BaseTestCase { private TestFindResult testFindResult; @Override public void setUp() throws Exception { super.setUp(); prepareScenarioWithTestFile("jasmine1/jasmineTestCaretTop.js"); jasmineFinder.findAll(); List<FindResult> findResults = jasmineFinder.getFindResults(); testFindResult = new TestFindResult(document, findResults.get(0)); } public void testToString() throws Exception { assertEquals("top describe", testFindResult.toString()); } }
Add scenarios for jasmine 1, 2
Add scenarios for jasmine 1, 2
Java
mit
andresdominguez/ddescriber,andresdominguez/ddescriber
java
## Code Before: package com.karateca.ddescriber.model; import com.intellij.find.FindResult; import com.karateca.ddescriber.BaseTestCase; import junit.framework.Assert; import java.util.List; /** * @author Andres Dominguez. */ public class TestFindResultTest extends BaseTestCase { private TestFindResult testFindResult; @Override public void setUp() throws Exception { super.setUp(); prepareScenarioWithTestFile("jasmineTestCaretTop.js"); jasmineFinder.findAll(); List<FindResult> findResults = jasmineFinder.getFindResults(); testFindResult = new TestFindResult(document, findResults.get(0)); } public void testToString() throws Exception { Assert.assertEquals("top describe", testFindResult.toString()); } } ## Instruction: Add scenarios for jasmine 1, 2 ## Code After: package com.karateca.ddescriber.model; import com.intellij.find.FindResult; import com.karateca.ddescriber.BaseTestCase; import junit.framework.Assert; import java.util.List; /** * @author Andres Dominguez. */ public class TestFindResultTest extends BaseTestCase { private TestFindResult testFindResult; @Override public void setUp() throws Exception { super.setUp(); prepareScenarioWithTestFile("jasmine1/jasmineTestCaretTop.js"); jasmineFinder.findAll(); List<FindResult> findResults = jasmineFinder.getFindResults(); testFindResult = new TestFindResult(document, findResults.get(0)); } public void testToString() throws Exception { assertEquals("top describe", testFindResult.toString()); } }
... @Override public void setUp() throws Exception { super.setUp(); prepareScenarioWithTestFile("jasmine1/jasmineTestCaretTop.js"); jasmineFinder.findAll(); List<FindResult> findResults = jasmineFinder.getFindResults(); ... } public void testToString() throws Exception { assertEquals("top describe", testFindResult.toString()); } } ...
f3cdd03f1e02f7fd0614d4421b831794c01de66d
tests/web_api/case_with_reform/reforms.py
tests/web_api/case_with_reform/reforms.py
from openfisca_core.model_api import Variable, Reform, MONTH from openfisca_country_template.entities import Person class goes_to_school(Variable): value_type = bool default_value = True entity = Person label = "The person goes to school (only relevant for children)" definition_period = MONTH class add_variable_reform(Reform): def apply(self): self.add_variable(goes_to_school)
from openfisca_core.model_api import Variable, Reform, MONTH from openfisca_country_template.entities import Person def test_dynamic_variable(): class NewDynamicClass(Variable): value_type = bool default_value = True entity = Person label = "The person goes to school (only relevant for children)" definition_period = MONTH NewDynamicClass.__name__ = "goes_to_school" return NewDynamicClass class add_variable_reform(Reform): def apply(self): self.add_variable(test_dynamic_variable())
Update test reform to make it fail without a fix
Update test reform to make it fail without a fix
Python
agpl-3.0
openfisca/openfisca-core,openfisca/openfisca-core
python
## Code Before: from openfisca_core.model_api import Variable, Reform, MONTH from openfisca_country_template.entities import Person class goes_to_school(Variable): value_type = bool default_value = True entity = Person label = "The person goes to school (only relevant for children)" definition_period = MONTH class add_variable_reform(Reform): def apply(self): self.add_variable(goes_to_school) ## Instruction: Update test reform to make it fail without a fix ## Code After: from openfisca_core.model_api import Variable, Reform, MONTH from openfisca_country_template.entities import Person def test_dynamic_variable(): class NewDynamicClass(Variable): value_type = bool default_value = True entity = Person label = "The person goes to school (only relevant for children)" definition_period = MONTH NewDynamicClass.__name__ = "goes_to_school" return NewDynamicClass class add_variable_reform(Reform): def apply(self): self.add_variable(test_dynamic_variable())
# ... existing code ... from openfisca_country_template.entities import Person def test_dynamic_variable(): class NewDynamicClass(Variable): value_type = bool default_value = True entity = Person label = "The person goes to school (only relevant for children)" definition_period = MONTH NewDynamicClass.__name__ = "goes_to_school" return NewDynamicClass class add_variable_reform(Reform): def apply(self): self.add_variable(test_dynamic_variable()) # ... rest of the code ...
0a9e3fb387c61f2c7cb32502f5c50eaa5b950169
tests/test_process.py
tests/test_process.py
from __future__ import print_function, unicode_literals import pytest from wamopacker.process import run_command, ProcessException import os import uuid def test_run_command(): cwd = os.getcwd() output_cmd = run_command('ls -1A', working_dir = cwd) output_py = os.listdir(cwd) assert sorted(output_cmd) == sorted(output_py) def test_run_command_error(): data = uuid.uuid4().hex with pytest.raises(ProcessException) as e: run_command('cat {}'.format(data)) assert e.value.log_stdout == '' assert e.value.log_stderr == 'cat: {}: No such file or directory\n'.format(data) assert e.value.exit_code != 0
from __future__ import print_function, unicode_literals import pytest from wamopacker.process import run_command, ProcessException import os import uuid def test_run_command(): cwd = os.getcwd() output_cmd = run_command('ls -1A', working_dir = cwd) output_py = os.listdir(cwd) assert sorted(output_cmd) == sorted(output_py) def test_run_command_error(): data = uuid.uuid4().hex with pytest.raises(ProcessException) as e: run_command('cat {}'.format(data)) assert e.value.log_stdout == '' assert e.value.log_stderr.startswith('cat: {}'.format(data)) assert e.value.exit_code != 0
Fix intermittent travis build error.
Fix intermittent travis build error.
Python
mit
wamonite/packermate
python
## Code Before: from __future__ import print_function, unicode_literals import pytest from wamopacker.process import run_command, ProcessException import os import uuid def test_run_command(): cwd = os.getcwd() output_cmd = run_command('ls -1A', working_dir = cwd) output_py = os.listdir(cwd) assert sorted(output_cmd) == sorted(output_py) def test_run_command_error(): data = uuid.uuid4().hex with pytest.raises(ProcessException) as e: run_command('cat {}'.format(data)) assert e.value.log_stdout == '' assert e.value.log_stderr == 'cat: {}: No such file or directory\n'.format(data) assert e.value.exit_code != 0 ## Instruction: Fix intermittent travis build error. ## Code After: from __future__ import print_function, unicode_literals import pytest from wamopacker.process import run_command, ProcessException import os import uuid def test_run_command(): cwd = os.getcwd() output_cmd = run_command('ls -1A', working_dir = cwd) output_py = os.listdir(cwd) assert sorted(output_cmd) == sorted(output_py) def test_run_command_error(): data = uuid.uuid4().hex with pytest.raises(ProcessException) as e: run_command('cat {}'.format(data)) assert e.value.log_stdout == '' assert e.value.log_stderr.startswith('cat: {}'.format(data)) assert e.value.exit_code != 0
... run_command('cat {}'.format(data)) assert e.value.log_stdout == '' assert e.value.log_stderr.startswith('cat: {}'.format(data)) assert e.value.exit_code != 0 ...
97c8ae2e5624cdd8576a9acc9b70a9cb7cb47927
tests/strings_test.c
tests/strings_test.c
static void test_asprintf(void) { char *result = 0; (void)asprintf(&result, "test 1"); cb_assert(strcmp(result, "test 1") == 0); free(result); (void)asprintf(&result, "test %d", 2); cb_assert(strcmp(result, "test 2") == 0); free(result); (void)asprintf(&result, "%c%c%c%c %d", 't', 'e', 's', 't', 3); cb_assert(strcmp(result, "test 3") == 0); free(result); } int main(void) { test_asprintf(); return 0; }
static void test_asprintf(void) { char *result = 0; cb_assert(asprintf(&result, "test 1") > 0); cb_assert(strcmp(result, "test 1") == 0); free(result); cb_assert(asprintf(&result, "test %d", 2) > 0); cb_assert(strcmp(result, "test 2") == 0); free(result); cb_assert(asprintf(&result, "%c%c%c%c %d", 't', 'e', 's', 't', 3) > 0); cb_assert(strcmp(result, "test 3") == 0); free(result); } int main(void) { test_asprintf(); return 0; }
Check for return value for asprintf
Check for return value for asprintf Change-Id: Ib163468aac1a5e52cef28c59b55be2287dc4ba43 Reviewed-on: http://review.couchbase.org/43023 Reviewed-by: Trond Norbye <[email protected]> Tested-by: Trond Norbye <[email protected]>
C
apache-2.0
vmx/platform,vmx/platform
c
## Code Before: static void test_asprintf(void) { char *result = 0; (void)asprintf(&result, "test 1"); cb_assert(strcmp(result, "test 1") == 0); free(result); (void)asprintf(&result, "test %d", 2); cb_assert(strcmp(result, "test 2") == 0); free(result); (void)asprintf(&result, "%c%c%c%c %d", 't', 'e', 's', 't', 3); cb_assert(strcmp(result, "test 3") == 0); free(result); } int main(void) { test_asprintf(); return 0; } ## Instruction: Check for return value for asprintf Change-Id: Ib163468aac1a5e52cef28c59b55be2287dc4ba43 Reviewed-on: http://review.couchbase.org/43023 Reviewed-by: Trond Norbye <[email protected]> Tested-by: Trond Norbye <[email protected]> ## Code After: static void test_asprintf(void) { char *result = 0; cb_assert(asprintf(&result, "test 1") > 0); cb_assert(strcmp(result, "test 1") == 0); free(result); cb_assert(asprintf(&result, "test %d", 2) > 0); cb_assert(strcmp(result, "test 2") == 0); free(result); cb_assert(asprintf(&result, "%c%c%c%c %d", 't', 'e', 's', 't', 3) > 0); cb_assert(strcmp(result, "test 3") == 0); free(result); } int main(void) { test_asprintf(); return 0; }
... static void test_asprintf(void) { char *result = 0; cb_assert(asprintf(&result, "test 1") > 0); cb_assert(strcmp(result, "test 1") == 0); free(result); cb_assert(asprintf(&result, "test %d", 2) > 0); cb_assert(strcmp(result, "test 2") == 0); free(result); cb_assert(asprintf(&result, "%c%c%c%c %d", 't', 'e', 's', 't', 3) > 0); cb_assert(strcmp(result, "test 3") == 0); free(result); } ...
053d4599dbb70664cb9f4e9c5b620b39733c254d
nova_powervm/conf/__init__.py
nova_powervm/conf/__init__.py
import nova.conf from nova_powervm.conf import powervm CONF = nova.conf.CONF # Pull in the imports that nova-powervm uses so they are validated CONF.import_opt('host', 'nova.netconf') CONF.import_opt('my_ip', 'nova.netconf') CONF.import_opt('vif_plugging_is_fatal', 'nova.virt.driver') CONF.import_opt('vif_plugging_timeout', 'nova.virt.driver') powervm.register_opts(CONF)
import nova.conf from nova_powervm.conf import powervm CONF = nova.conf.CONF powervm.register_opts(CONF)
Support new conf refactor from Nova
Support new conf refactor from Nova The core nova project is consolidating their conf options. This impacted the PowerVM conf options as a few that we were explicitly importing were moved. This change set fixes the issue and allows PowerVM to work properly. The change actually removes the imports, but they are still imported properly because the PowerVM driver imports the 'nova.conf' package (which will background load the parameters). Change-Id: I93c46e74a09cac332b903adeddbd20e859b4b7f5 Closes-Bug: 1578318
Python
apache-2.0
openstack/nova-powervm,openstack/nova-powervm,stackforge/nova-powervm,stackforge/nova-powervm
python
## Code Before: import nova.conf from nova_powervm.conf import powervm CONF = nova.conf.CONF # Pull in the imports that nova-powervm uses so they are validated CONF.import_opt('host', 'nova.netconf') CONF.import_opt('my_ip', 'nova.netconf') CONF.import_opt('vif_plugging_is_fatal', 'nova.virt.driver') CONF.import_opt('vif_plugging_timeout', 'nova.virt.driver') powervm.register_opts(CONF) ## Instruction: Support new conf refactor from Nova The core nova project is consolidating their conf options. This impacted the PowerVM conf options as a few that we were explicitly importing were moved. This change set fixes the issue and allows PowerVM to work properly. The change actually removes the imports, but they are still imported properly because the PowerVM driver imports the 'nova.conf' package (which will background load the parameters). Change-Id: I93c46e74a09cac332b903adeddbd20e859b4b7f5 Closes-Bug: 1578318 ## Code After: import nova.conf from nova_powervm.conf import powervm CONF = nova.conf.CONF powervm.register_opts(CONF)
... CONF = nova.conf.CONF powervm.register_opts(CONF) ...
57318652ba9aacc0456334a1d6466734f35ab84d
e2etest/e2etest.py
e2etest/e2etest.py
"""Run the end to end tests of the project.""" __author__ = "Martha Brennich" __license__ = "MIT" __copyright__ = "2020" __date__ = "11/07/2020" import sys import unittest import e2etest_freesas, e2etest_guinier_apps, e2etest_bift def suite(): """Creates suite for e2e tests""" test_suite = unittest.TestSuite() test_suite.addTest(e2etest_freesas.suite()) test_suite.addTest(e2etest_guinier_apps.suite()) test_suite.addTest(e2etest_bift.suite()) return test_suite if __name__ == "__main__": runner = unittest.TextTestRunner() result = runner.run(suite()) if result.wasSuccessful(): EXIT_STATUS = 0 else: EXIT_STATUS = 1 sys.exit(EXIT_STATUS)
"""Run the end to end tests of the project.""" __author__ = "Martha Brennich" __license__ = "MIT" __copyright__ = "2020" __date__ = "11/07/2020" import sys import unittest import e2etest_freesas, e2etest_guinier_apps, e2etest_bift, e2etest_cormap def suite(): """Creates suite for e2e tests""" test_suite = unittest.TestSuite() test_suite.addTest(e2etest_freesas.suite()) test_suite.addTest(e2etest_guinier_apps.suite()) test_suite.addTest(e2etest_bift.suite()) test_suite.addTest(e2etest_cormap.suite()) return test_suite if __name__ == "__main__": runner = unittest.TextTestRunner() result = runner.run(suite()) if result.wasSuccessful(): EXIT_STATUS = 0 else: EXIT_STATUS = 1 sys.exit(EXIT_STATUS)
Add cormapy test suite to e2e test suite
Add cormapy test suite to e2e test suite
Python
mit
kif/freesas,kif/freesas,kif/freesas
python
## Code Before: """Run the end to end tests of the project.""" __author__ = "Martha Brennich" __license__ = "MIT" __copyright__ = "2020" __date__ = "11/07/2020" import sys import unittest import e2etest_freesas, e2etest_guinier_apps, e2etest_bift def suite(): """Creates suite for e2e tests""" test_suite = unittest.TestSuite() test_suite.addTest(e2etest_freesas.suite()) test_suite.addTest(e2etest_guinier_apps.suite()) test_suite.addTest(e2etest_bift.suite()) return test_suite if __name__ == "__main__": runner = unittest.TextTestRunner() result = runner.run(suite()) if result.wasSuccessful(): EXIT_STATUS = 0 else: EXIT_STATUS = 1 sys.exit(EXIT_STATUS) ## Instruction: Add cormapy test suite to e2e test suite ## Code After: """Run the end to end tests of the project.""" __author__ = "Martha Brennich" __license__ = "MIT" __copyright__ = "2020" __date__ = "11/07/2020" import sys import unittest import e2etest_freesas, e2etest_guinier_apps, e2etest_bift, e2etest_cormap def suite(): """Creates suite for e2e tests""" test_suite = unittest.TestSuite() test_suite.addTest(e2etest_freesas.suite()) test_suite.addTest(e2etest_guinier_apps.suite()) test_suite.addTest(e2etest_bift.suite()) test_suite.addTest(e2etest_cormap.suite()) return test_suite if __name__ == "__main__": runner = unittest.TextTestRunner() result = runner.run(suite()) if result.wasSuccessful(): EXIT_STATUS = 0 else: EXIT_STATUS = 1 sys.exit(EXIT_STATUS)
// ... existing code ... import sys import unittest import e2etest_freesas, e2etest_guinier_apps, e2etest_bift, e2etest_cormap def suite(): // ... modified code ... test_suite.addTest(e2etest_freesas.suite()) test_suite.addTest(e2etest_guinier_apps.suite()) test_suite.addTest(e2etest_bift.suite()) test_suite.addTest(e2etest_cormap.suite()) return test_suite // ... rest of the code ...
1317d645092d94c95bcaf7a0341ac18208f9df0d
patient/admin.py
patient/admin.py
from django.contrib import admin from django.contrib.auth.models import Group from .models import Patient from django import forms class CustomPatientForm(forms.ModelForm): class Meta: model = Patient def __init__(self, *args, **kwargs): super(CustomPatientForm, self).__init__(*args, **kwargs) self.fields['hub'].queryset = Group.objects.get(name="hubs").user_set.all() self.fields['user'].queryset = Group.objects.get(name="patients").user_set.all() class PatientAdmin(admin.ModelAdmin): form = CustomPatientForm admin.site.register(Patient, PatientAdmin)
from django.contrib import admin from django.contrib.auth.models import Group from .models import Patient from django import forms class CustomPatientForm(forms.ModelForm): class Meta: model = Patient exclude = [] def __init__(self, *args, **kwargs): super(CustomPatientForm, self).__init__(*args, **kwargs) self.fields['hub'].queryset = Group.objects.get(name="hubs").user_set.all() self.fields['user'].queryset = Group.objects.get(name="patients").user_set.all() class PatientAdmin(admin.ModelAdmin): form = CustomPatientForm admin.site.register(Patient, PatientAdmin)
Fix deprecated warning in CustomPatientForm
Fix deprecated warning in CustomPatientForm
Python
mit
sigurdsa/angelika-api
python
## Code Before: from django.contrib import admin from django.contrib.auth.models import Group from .models import Patient from django import forms class CustomPatientForm(forms.ModelForm): class Meta: model = Patient def __init__(self, *args, **kwargs): super(CustomPatientForm, self).__init__(*args, **kwargs) self.fields['hub'].queryset = Group.objects.get(name="hubs").user_set.all() self.fields['user'].queryset = Group.objects.get(name="patients").user_set.all() class PatientAdmin(admin.ModelAdmin): form = CustomPatientForm admin.site.register(Patient, PatientAdmin) ## Instruction: Fix deprecated warning in CustomPatientForm ## Code After: from django.contrib import admin from django.contrib.auth.models import Group from .models import Patient from django import forms class CustomPatientForm(forms.ModelForm): class Meta: model = Patient exclude = [] def __init__(self, *args, **kwargs): super(CustomPatientForm, self).__init__(*args, **kwargs) self.fields['hub'].queryset = Group.objects.get(name="hubs").user_set.all() self.fields['user'].queryset = Group.objects.get(name="patients").user_set.all() class PatientAdmin(admin.ModelAdmin): form = CustomPatientForm admin.site.register(Patient, PatientAdmin)
... class CustomPatientForm(forms.ModelForm): class Meta: model = Patient exclude = [] def __init__(self, *args, **kwargs): super(CustomPatientForm, self).__init__(*args, **kwargs) ...
73bb30324b9cf5c2458761c5566d317bb754e986
src/main/kotlin/org/paradise/ipaq/controllers/ipaqController.kt
src/main/kotlin/org/paradise/ipaq/controllers/ipaqController.kt
package org.paradise.ipaq.controllers import org.paradise.ipaq.domain.ExperianAddress import org.paradise.ipaq.domain.ExperianSearchResult import org.paradise.ipaq.services.ExperianService import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController /** * Created by terrence on 17/7/17. */ @RestController class ipaqController(val experianService: ExperianService) { @RequestMapping(value = "/Search", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) fun search(@RequestParam(value = "query") query: String? = null, @RequestParam(value = "country") country: String? = null, @RequestParam(value = "take", defaultValue = "10") take: Int): ResponseEntity<ExperianSearchResult> { return experianService.search(query, country, take) } @RequestMapping(value = "/format", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) fun format(@RequestParam(value = "country") country: String? = null, @RequestParam(value = "id") id: String? = null): ResponseEntity<ExperianAddress> { return experianService.format(country, id) } }
package org.paradise.ipaq.controllers import org.paradise.ipaq.domain.ExperianAddress import org.paradise.ipaq.domain.ExperianSearchResult import org.paradise.ipaq.services.ExperianService import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController /** * Created by terrence on 17/7/17. */ @RestController class ipaqController(val experianService: ExperianService) { @RequestMapping(value = "/Search", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) fun search(@RequestParam(value = "query") query: String, @RequestParam(value = "country") country: String, @RequestParam(value = "take", defaultValue = "10") take: Int): ResponseEntity<ExperianSearchResult> = experianService.search(query, country, take) @RequestMapping(value = "/format", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) fun format(@RequestParam(value = "country") country: String, @RequestParam(value = "id") id: String): ResponseEntity<ExperianAddress> = experianService.format(country, id) }
Refactor controller more Kotlin style like
Refactor controller more Kotlin style like
Kotlin
apache-2.0
TerrenceMiao/IPAQ
kotlin
## Code Before: package org.paradise.ipaq.controllers import org.paradise.ipaq.domain.ExperianAddress import org.paradise.ipaq.domain.ExperianSearchResult import org.paradise.ipaq.services.ExperianService import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController /** * Created by terrence on 17/7/17. */ @RestController class ipaqController(val experianService: ExperianService) { @RequestMapping(value = "/Search", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) fun search(@RequestParam(value = "query") query: String? = null, @RequestParam(value = "country") country: String? = null, @RequestParam(value = "take", defaultValue = "10") take: Int): ResponseEntity<ExperianSearchResult> { return experianService.search(query, country, take) } @RequestMapping(value = "/format", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) fun format(@RequestParam(value = "country") country: String? = null, @RequestParam(value = "id") id: String? = null): ResponseEntity<ExperianAddress> { return experianService.format(country, id) } } ## Instruction: Refactor controller more Kotlin style like ## Code After: package org.paradise.ipaq.controllers import org.paradise.ipaq.domain.ExperianAddress import org.paradise.ipaq.domain.ExperianSearchResult import org.paradise.ipaq.services.ExperianService import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController /** * Created by terrence on 17/7/17. */ @RestController class ipaqController(val experianService: ExperianService) { @RequestMapping(value = "/Search", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) fun search(@RequestParam(value = "query") query: String, @RequestParam(value = "country") country: String, @RequestParam(value = "take", defaultValue = "10") take: Int): ResponseEntity<ExperianSearchResult> = experianService.search(query, country, take) @RequestMapping(value = "/format", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) fun format(@RequestParam(value = "country") country: String, @RequestParam(value = "id") id: String): ResponseEntity<ExperianAddress> = experianService.format(country, id) }
// ... existing code ... class ipaqController(val experianService: ExperianService) { @RequestMapping(value = "/Search", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) fun search(@RequestParam(value = "query") query: String, @RequestParam(value = "country") country: String, @RequestParam(value = "take", defaultValue = "10") take: Int): ResponseEntity<ExperianSearchResult> = experianService.search(query, country, take) @RequestMapping(value = "/format", method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_VALUE)) fun format(@RequestParam(value = "country") country: String, @RequestParam(value = "id") id: String): ResponseEntity<ExperianAddress> = experianService.format(country, id) } // ... rest of the code ...
8262d48c2d08c85fe111602e8455ea94ccfd1304
src/main/java/org/cyclops/integrateddynamics/block/BlockMenrilSaplingConfig.java
src/main/java/org/cyclops/integrateddynamics/block/BlockMenrilSaplingConfig.java
package org.cyclops.integrateddynamics.block; import net.minecraft.block.Block; import net.minecraft.block.SaplingBlock; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import org.cyclops.cyclopscore.config.extendedconfig.BlockConfig; import org.cyclops.integrateddynamics.IntegratedDynamics; import org.cyclops.integrateddynamics.world.gen.TreeMenril; /** * Config for the Menril Sapling. * @author rubensworks * */ public class BlockMenrilSaplingConfig extends BlockConfig { public BlockMenrilSaplingConfig() { super( IntegratedDynamics._instance, "menril_sapling", eConfig -> new SaplingBlock(new TreeMenril(), Block.Properties.create(Material.PLANTS) .doesNotBlockMovement() .tickRandomly() .hardnessAndResistance(0) .sound(SoundType.PLANT)), getDefaultItemConstructor(IntegratedDynamics._instance) ); } }
package org.cyclops.integrateddynamics.block; import net.minecraft.block.Block; import net.minecraft.block.SaplingBlock; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.RenderTypeLookup; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.cyclops.cyclopscore.config.extendedconfig.BlockConfig; import org.cyclops.integrateddynamics.IntegratedDynamics; import org.cyclops.integrateddynamics.world.gen.TreeMenril; /** * Config for the Menril Sapling. * @author rubensworks * */ public class BlockMenrilSaplingConfig extends BlockConfig { public BlockMenrilSaplingConfig() { super( IntegratedDynamics._instance, "menril_sapling", eConfig -> new SaplingBlock(new TreeMenril(), Block.Properties.create(Material.PLANTS) .doesNotBlockMovement() .tickRandomly() .hardnessAndResistance(0) .sound(SoundType.PLANT)), getDefaultItemConstructor(IntegratedDynamics._instance) ); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onClientSetup); } public void onClientSetup(FMLClientSetupEvent event) { RenderTypeLookup.setRenderLayer(getInstance(), RenderType.getCutout()); } }
Fix menril sapling having incorrect render layer
Fix menril sapling having incorrect render layer
Java
mit
CyclopsMC/IntegratedDynamics
java
## Code Before: package org.cyclops.integrateddynamics.block; import net.minecraft.block.Block; import net.minecraft.block.SaplingBlock; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import org.cyclops.cyclopscore.config.extendedconfig.BlockConfig; import org.cyclops.integrateddynamics.IntegratedDynamics; import org.cyclops.integrateddynamics.world.gen.TreeMenril; /** * Config for the Menril Sapling. * @author rubensworks * */ public class BlockMenrilSaplingConfig extends BlockConfig { public BlockMenrilSaplingConfig() { super( IntegratedDynamics._instance, "menril_sapling", eConfig -> new SaplingBlock(new TreeMenril(), Block.Properties.create(Material.PLANTS) .doesNotBlockMovement() .tickRandomly() .hardnessAndResistance(0) .sound(SoundType.PLANT)), getDefaultItemConstructor(IntegratedDynamics._instance) ); } } ## Instruction: Fix menril sapling having incorrect render layer ## Code After: package org.cyclops.integrateddynamics.block; import net.minecraft.block.Block; import net.minecraft.block.SaplingBlock; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.RenderTypeLookup; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.cyclops.cyclopscore.config.extendedconfig.BlockConfig; import org.cyclops.integrateddynamics.IntegratedDynamics; import org.cyclops.integrateddynamics.world.gen.TreeMenril; /** * Config for the Menril Sapling. * @author rubensworks * */ public class BlockMenrilSaplingConfig extends BlockConfig { public BlockMenrilSaplingConfig() { super( IntegratedDynamics._instance, "menril_sapling", eConfig -> new SaplingBlock(new TreeMenril(), Block.Properties.create(Material.PLANTS) .doesNotBlockMovement() .tickRandomly() .hardnessAndResistance(0) .sound(SoundType.PLANT)), getDefaultItemConstructor(IntegratedDynamics._instance) ); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onClientSetup); } public void onClientSetup(FMLClientSetupEvent event) { RenderTypeLookup.setRenderLayer(getInstance(), RenderType.getCutout()); } }
// ... existing code ... import net.minecraft.block.SaplingBlock; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.RenderTypeLookup; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import org.cyclops.cyclopscore.config.extendedconfig.BlockConfig; import org.cyclops.integrateddynamics.IntegratedDynamics; import org.cyclops.integrateddynamics.world.gen.TreeMenril; // ... modified code ... .sound(SoundType.PLANT)), getDefaultItemConstructor(IntegratedDynamics._instance) ); FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onClientSetup); } public void onClientSetup(FMLClientSetupEvent event) { RenderTypeLookup.setRenderLayer(getInstance(), RenderType.getCutout()); } } // ... rest of the code ...
424980a48e451d1b99397843001bd75fa58e474e
tests/test_fullqualname.py
tests/test_fullqualname.py
"""Tests for fullqualname.""" import nose import sys from fullqualname import fullqualname def test_builtin_function(): # Test built-in function object. obj = len # Type is 'builtin_function_or_method'. assert type(obj).__name__ == 'builtin_function_or_method' # Object is a function. assert 'built-in function' in repr(obj) if sys.version_info >= (3, ): expected = 'builtins.len' else: expected = '__builtin__.len' nose.tools.assert_equals(fullqualname(obj), expected)
"""Tests for fullqualname.""" import inspect import nose import sys from fullqualname import fullqualname def test_builtin_function(): # Test built-in function object. obj = len # Type is 'builtin_function_or_method'. assert type(obj).__name__ == 'builtin_function_or_method' # Object is a function. assert 'built-in function' in repr(obj) if sys.version_info >= (3, ): expected = 'builtins.len' else: expected = '__builtin__.len' nose.tools.assert_equals(fullqualname(obj), expected) def test_builtin_method(): # Test built-in method object. obj = [1, 2, 3].append # Object type is 'builtin_function_or_method'. assert type(obj).__name__ == 'builtin_function_or_method' # Object is a method. assert 'built-in method' in repr(obj) # Object __self__ attribute is not a class. assert not inspect.isclass(obj.__self__) if sys.version_info >= (3, ): expected = 'builtins.list.append' else: expected = '__builtin__.list.append' nose.tools.assert_equals(fullqualname(obj), expected)
Add built-in method object test
Add built-in method object test
Python
bsd-3-clause
etgalloway/fullqualname
python
## Code Before: """Tests for fullqualname.""" import nose import sys from fullqualname import fullqualname def test_builtin_function(): # Test built-in function object. obj = len # Type is 'builtin_function_or_method'. assert type(obj).__name__ == 'builtin_function_or_method' # Object is a function. assert 'built-in function' in repr(obj) if sys.version_info >= (3, ): expected = 'builtins.len' else: expected = '__builtin__.len' nose.tools.assert_equals(fullqualname(obj), expected) ## Instruction: Add built-in method object test ## Code After: """Tests for fullqualname.""" import inspect import nose import sys from fullqualname import fullqualname def test_builtin_function(): # Test built-in function object. obj = len # Type is 'builtin_function_or_method'. assert type(obj).__name__ == 'builtin_function_or_method' # Object is a function. assert 'built-in function' in repr(obj) if sys.version_info >= (3, ): expected = 'builtins.len' else: expected = '__builtin__.len' nose.tools.assert_equals(fullqualname(obj), expected) def test_builtin_method(): # Test built-in method object. obj = [1, 2, 3].append # Object type is 'builtin_function_or_method'. assert type(obj).__name__ == 'builtin_function_or_method' # Object is a method. assert 'built-in method' in repr(obj) # Object __self__ attribute is not a class. assert not inspect.isclass(obj.__self__) if sys.version_info >= (3, ): expected = 'builtins.list.append' else: expected = '__builtin__.list.append' nose.tools.assert_equals(fullqualname(obj), expected)
# ... existing code ... """Tests for fullqualname.""" import inspect import nose import sys # ... modified code ... expected = '__builtin__.len' nose.tools.assert_equals(fullqualname(obj), expected) def test_builtin_method(): # Test built-in method object. obj = [1, 2, 3].append # Object type is 'builtin_function_or_method'. assert type(obj).__name__ == 'builtin_function_or_method' # Object is a method. assert 'built-in method' in repr(obj) # Object __self__ attribute is not a class. assert not inspect.isclass(obj.__self__) if sys.version_info >= (3, ): expected = 'builtins.list.append' else: expected = '__builtin__.list.append' nose.tools.assert_equals(fullqualname(obj), expected) # ... rest of the code ...
7143e2706dbf78a064b49369a4b17636ef0bf6dd
setup.py
setup.py
from setuptools import find_packages, setup from setuptools.command.install import install import os BASEPATH='.eDisGo' class InstallSetup(install): def run(self): self.create_edisgo_path() install.run(self) @staticmethod def create_edisgo_path(): edisgo_path = os.path.join(os.path.expanduser('~'), BASEPATH) data_path = os.path.join(edisgo_path, 'data') if not os.path.isdir(edisgo_path): os.mkdir(edisgo_path) if not os.path.isdir(data_path): os.mkdir(data_path) setup( name='eDisGo', version='0.0.1', packages=find_packages(), url='https://github.com/openego/eDisGo', license='GNU Affero General Public License v3.0', author='gplssm, nesnoj', author_email='', description='A python package for distribution grid analysis and optimization', install_requires = [ 'dingo==0.1.0-pre+git.477bf495', 'networkx >=1.11', 'shapely >= 1.5.12, <= 1.5.12', 'pandas >=0.19.2, <=0.20.1' ], cmdclass={ 'install': InstallSetup}, dependency_links=['https://github.com/openego/dingo/archive/'\ '477bf49534f93aca90ba3c5231fe726972343939.zip'\ '#egg=dingo-0.1.0-pre+git.477bf495'] )
from setuptools import find_packages, setup from setuptools.command.install import install import os BASEPATH='.eDisGo' class InstallSetup(install): def run(self): self.create_edisgo_path() install.run(self) @staticmethod def create_edisgo_path(): edisgo_path = os.path.join(os.path.expanduser('~'), BASEPATH) data_path = os.path.join(edisgo_path, 'data') if not os.path.isdir(edisgo_path): os.mkdir(edisgo_path) if not os.path.isdir(data_path): os.mkdir(data_path) setup( name='eDisGo', version='0.0.1', packages=find_packages(), url='https://github.com/openego/eDisGo', license='GNU Affero General Public License v3.0', author='gplssm, nesnoj', author_email='', description='A python package for distribution grid analysis and optimization', install_requires = [ 'ding0==0.1.2', 'networkx >=1.11', 'shapely >= 1.5.12, <= 1.5.12', 'pandas >=0.19.2, <=0.20.1' ], cmdclass={ 'install': InstallSetup} )
Install with dingo version 0.1.2
Install with dingo version 0.1.2
Python
agpl-3.0
openego/eDisGo,openego/eDisGo
python
## Code Before: from setuptools import find_packages, setup from setuptools.command.install import install import os BASEPATH='.eDisGo' class InstallSetup(install): def run(self): self.create_edisgo_path() install.run(self) @staticmethod def create_edisgo_path(): edisgo_path = os.path.join(os.path.expanduser('~'), BASEPATH) data_path = os.path.join(edisgo_path, 'data') if not os.path.isdir(edisgo_path): os.mkdir(edisgo_path) if not os.path.isdir(data_path): os.mkdir(data_path) setup( name='eDisGo', version='0.0.1', packages=find_packages(), url='https://github.com/openego/eDisGo', license='GNU Affero General Public License v3.0', author='gplssm, nesnoj', author_email='', description='A python package for distribution grid analysis and optimization', install_requires = [ 'dingo==0.1.0-pre+git.477bf495', 'networkx >=1.11', 'shapely >= 1.5.12, <= 1.5.12', 'pandas >=0.19.2, <=0.20.1' ], cmdclass={ 'install': InstallSetup}, dependency_links=['https://github.com/openego/dingo/archive/'\ '477bf49534f93aca90ba3c5231fe726972343939.zip'\ '#egg=dingo-0.1.0-pre+git.477bf495'] ) ## Instruction: Install with dingo version 0.1.2 ## Code After: from setuptools import find_packages, setup from setuptools.command.install import install import os BASEPATH='.eDisGo' class InstallSetup(install): def run(self): self.create_edisgo_path() install.run(self) @staticmethod def create_edisgo_path(): edisgo_path = os.path.join(os.path.expanduser('~'), BASEPATH) data_path = os.path.join(edisgo_path, 'data') if not os.path.isdir(edisgo_path): os.mkdir(edisgo_path) if not os.path.isdir(data_path): os.mkdir(data_path) setup( name='eDisGo', version='0.0.1', packages=find_packages(), url='https://github.com/openego/eDisGo', license='GNU Affero General Public License v3.0', author='gplssm, nesnoj', author_email='', description='A python package for distribution grid analysis and optimization', install_requires = [ 'ding0==0.1.2', 'networkx >=1.11', 'shapely >= 1.5.12, <= 1.5.12', 'pandas >=0.19.2, <=0.20.1' ], cmdclass={ 'install': InstallSetup} )
# ... existing code ... author_email='', description='A python package for distribution grid analysis and optimization', install_requires = [ 'ding0==0.1.2', 'networkx >=1.11', 'shapely >= 1.5.12, <= 1.5.12', 'pandas >=0.19.2, <=0.20.1' ], cmdclass={ 'install': InstallSetup} ) # ... rest of the code ...
afac07ce173af3e7db4a6ba6dab4786903e217b7
ocradmin/ocr/tools/plugins/cuneiform_wrapper.py
ocradmin/ocr/tools/plugins/cuneiform_wrapper.py
from generic_wrapper import * def main_class(): return CuneiformWrapper class CuneiformWrapper(GenericWrapper): """ Override certain methods of the OcropusWrapper to use Cuneiform for recognition of individual lines. """ name = "cuneiform" capabilities = ("line", "page") binary = get_binary("cuneiform") def get_command(self, outfile, image): """ Cuneiform command line. Simplified for now. """ return [self.binary, "-o", outfile, image]
import tempfile import subprocess as sp from ocradmin.ocr.tools import check_aborted, set_progress from ocradmin.ocr.utils import HocrParser from generic_wrapper import * def main_class(): return CuneiformWrapper class CuneiformWrapper(GenericWrapper): """ Override certain methods of the OcropusWrapper to use Cuneiform for recognition of individual lines. """ name = "cuneiform" capabilities = ("line", "page") binary = get_binary("cuneiform") def get_command(self, outfile, image): """ Cuneiform command line. Simplified for now. """ return [self.binary, "-o", outfile, image] def convert(self, filepath, *args, **kwargs): """ Convert a full page. """ json = None with tempfile.NamedTemporaryFile(delete=False) as tmp: tmp.close() args = [self.binary, "-f", "hocr", "-o", tmp.name, filepath] self.logger.info(args) proc = sp.Popen(args, stderr=sp.PIPE) err = proc.stderr.read() if proc.wait() != 0: return "!!! %s CONVERSION ERROR %d: %s !!!" % ( os.path.basename(self.binary).upper(), proc.returncode, err) json = HocrParser().parsefile(tmp.name) self.logger.info("%s" % json) os.unlink(tmp.name) set_progress(self.logger, kwargs["progress_func"], 100, 100) return json
Allow Cuneiform to do full page conversions. Downsides: 1) it crashes on quite a lot of pages 2) there's no progress output
Allow Cuneiform to do full page conversions. Downsides: 1) it crashes on quite a lot of pages 2) there's no progress output
Python
apache-2.0
vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium
python
## Code Before: from generic_wrapper import * def main_class(): return CuneiformWrapper class CuneiformWrapper(GenericWrapper): """ Override certain methods of the OcropusWrapper to use Cuneiform for recognition of individual lines. """ name = "cuneiform" capabilities = ("line", "page") binary = get_binary("cuneiform") def get_command(self, outfile, image): """ Cuneiform command line. Simplified for now. """ return [self.binary, "-o", outfile, image] ## Instruction: Allow Cuneiform to do full page conversions. Downsides: 1) it crashes on quite a lot of pages 2) there's no progress output ## Code After: import tempfile import subprocess as sp from ocradmin.ocr.tools import check_aborted, set_progress from ocradmin.ocr.utils import HocrParser from generic_wrapper import * def main_class(): return CuneiformWrapper class CuneiformWrapper(GenericWrapper): """ Override certain methods of the OcropusWrapper to use Cuneiform for recognition of individual lines. """ name = "cuneiform" capabilities = ("line", "page") binary = get_binary("cuneiform") def get_command(self, outfile, image): """ Cuneiform command line. Simplified for now. """ return [self.binary, "-o", outfile, image] def convert(self, filepath, *args, **kwargs): """ Convert a full page. """ json = None with tempfile.NamedTemporaryFile(delete=False) as tmp: tmp.close() args = [self.binary, "-f", "hocr", "-o", tmp.name, filepath] self.logger.info(args) proc = sp.Popen(args, stderr=sp.PIPE) err = proc.stderr.read() if proc.wait() != 0: return "!!! %s CONVERSION ERROR %d: %s !!!" % ( os.path.basename(self.binary).upper(), proc.returncode, err) json = HocrParser().parsefile(tmp.name) self.logger.info("%s" % json) os.unlink(tmp.name) set_progress(self.logger, kwargs["progress_func"], 100, 100) return json
// ... existing code ... import tempfile import subprocess as sp from ocradmin.ocr.tools import check_aborted, set_progress from ocradmin.ocr.utils import HocrParser from generic_wrapper import * def main_class(): return CuneiformWrapper // ... modified code ... return [self.binary, "-o", outfile, image] def convert(self, filepath, *args, **kwargs): """ Convert a full page. """ json = None with tempfile.NamedTemporaryFile(delete=False) as tmp: tmp.close() args = [self.binary, "-f", "hocr", "-o", tmp.name, filepath] self.logger.info(args) proc = sp.Popen(args, stderr=sp.PIPE) err = proc.stderr.read() if proc.wait() != 0: return "!!! %s CONVERSION ERROR %d: %s !!!" % ( os.path.basename(self.binary).upper(), proc.returncode, err) json = HocrParser().parsefile(tmp.name) self.logger.info("%s" % json) os.unlink(tmp.name) set_progress(self.logger, kwargs["progress_func"], 100, 100) return json // ... rest of the code ...
d1da755f10d4287d1cfbec3a6d29d9961125bbce
plugins/tff_backend/plugin_consts.py
plugins/tff_backend/plugin_consts.py
NAMESPACE = u'tff_backend' KEY_ALGORITHM = u'ed25519' KEY_NAME = u'threefold' THREEFOLD_APP_ID = u'em-be-threefold-token' FULL_CURRENCY_NAMES = { 'USD': 'dollar', 'EUR': 'euro', 'YEN': 'yen', 'UAE': 'dirham', 'GBP': 'pound', } CURRENCY_RATES = { 'USD': 5.0, 'EUR': 4.2, 'YEN': 543.6, 'UAE': 18.6, 'GBP': 3.83 }
NAMESPACE = u'tff_backend' KEY_ALGORITHM = u'ed25519' KEY_NAME = u'threefold' THREEFOLD_APP_ID = u'em-be-threefold-token' FULL_CURRENCY_NAMES = { 'USD': 'dollar', 'EUR': 'euro', 'YEN': 'yen', 'UAE': 'dirham', 'GBP': 'pound', 'BTC': 'bitcoin', } CURRENCY_RATES = { 'USD': 5.0, 'EUR': 4.2, 'YEN': 543.6, 'UAE': 18.6, 'GBP': 3.83, 'BTC': .0011, }
Add BTC to possible currencies
Add BTC to possible currencies
Python
bsd-3-clause
threefoldfoundation/app_backend,threefoldfoundation/app_backend,threefoldfoundation/app_backend,threefoldfoundation/app_backend
python
## Code Before: NAMESPACE = u'tff_backend' KEY_ALGORITHM = u'ed25519' KEY_NAME = u'threefold' THREEFOLD_APP_ID = u'em-be-threefold-token' FULL_CURRENCY_NAMES = { 'USD': 'dollar', 'EUR': 'euro', 'YEN': 'yen', 'UAE': 'dirham', 'GBP': 'pound', } CURRENCY_RATES = { 'USD': 5.0, 'EUR': 4.2, 'YEN': 543.6, 'UAE': 18.6, 'GBP': 3.83 } ## Instruction: Add BTC to possible currencies ## Code After: NAMESPACE = u'tff_backend' KEY_ALGORITHM = u'ed25519' KEY_NAME = u'threefold' THREEFOLD_APP_ID = u'em-be-threefold-token' FULL_CURRENCY_NAMES = { 'USD': 'dollar', 'EUR': 'euro', 'YEN': 'yen', 'UAE': 'dirham', 'GBP': 'pound', 'BTC': 'bitcoin', } CURRENCY_RATES = { 'USD': 5.0, 'EUR': 4.2, 'YEN': 543.6, 'UAE': 18.6, 'GBP': 3.83, 'BTC': .0011, }
// ... existing code ... 'YEN': 'yen', 'UAE': 'dirham', 'GBP': 'pound', 'BTC': 'bitcoin', } CURRENCY_RATES = { 'USD': 5.0, // ... modified code ... 'EUR': 4.2, 'YEN': 543.6, 'UAE': 18.6, 'GBP': 3.83, 'BTC': .0011, } // ... rest of the code ...
9e745b0e5ac673d04d978887654627b686813d93
cms/apps/pages/tests/urls.py
cms/apps/pages/tests/urls.py
from django.conf.urls import patterns, url def view(): pass urlpatterns = patterns( "", url("^$", view, name="index"), url("^(?P<url_title>[^/]+)/$", view, name="detail"), )
from django.conf.urls import patterns, url urlpatterns = patterns( "", url("^$", lambda: None, name="index"), url("^(?P<url_title>[^/]+)/$", lambda: None, name="detail"), )
Replace page test url views with lambdas.
Replace page test url views with lambdas.
Python
bsd-3-clause
danielsamuels/cms,jamesfoley/cms,dan-gamble/cms,lewiscollard/cms,jamesfoley/cms,jamesfoley/cms,lewiscollard/cms,danielsamuels/cms,lewiscollard/cms,jamesfoley/cms,dan-gamble/cms,danielsamuels/cms,dan-gamble/cms
python
## Code Before: from django.conf.urls import patterns, url def view(): pass urlpatterns = patterns( "", url("^$", view, name="index"), url("^(?P<url_title>[^/]+)/$", view, name="detail"), ) ## Instruction: Replace page test url views with lambdas. ## Code After: from django.conf.urls import patterns, url urlpatterns = patterns( "", url("^$", lambda: None, name="index"), url("^(?P<url_title>[^/]+)/$", lambda: None, name="detail"), )
// ... existing code ... from django.conf.urls import patterns, url urlpatterns = patterns( "", url("^$", lambda: None, name="index"), url("^(?P<url_title>[^/]+)/$", lambda: None, name="detail"), ) // ... rest of the code ...
6ad8c9fc7846f51e2f784d38f9a92017552da996
lanes/models.py
lanes/models.py
from django.db import models from django.contrib.auth.models import User from kitabu.models.subjects import VariableSizeSubject, BaseSubject from kitabu.models.reservations import ReservationMaybeExclusive, ReservationGroup, BaseReservation from kitabu.models import validators from pools.models import Pool class Lane(VariableSizeSubject, BaseSubject): name = models.TextField() cluster = models.ForeignKey(Pool, related_name='subjects') def __unicode__(self): return self.name class LaneReservation(ReservationMaybeExclusive, BaseReservation): subject = models.ForeignKey('Lane', related_name='reservations') group = models.ForeignKey('LaneReservationGroup', related_name='reservations', null=True, blank=True) owner = models.ForeignKey(User, null=True) def __unicode__(self): return "%s from %s to %s (%s places)" % (self.subject.name, self.start, self.end, self.size) class LaneReservationGroup(ReservationGroup): pass class LaneFullTimeValidator(validators.FullTimeValidator): pass class LaneTimeIntervalValidator(validators.TimeIntervalValidator): pass class LaneWithinPeriodValidator(validators.WithinPeriodValidator): pass class LaneNotWithinPeriodValidator(validators.NotWithinPeriodValidator): pass class LaneGivenHoursAndWeekdaysValidator(validators.GivenHoursAndWeekdaysValidator): pass
from django.db import models from django.contrib.auth.models import User from kitabu.models.subjects import VariableSizeSubject, BaseSubject from kitabu.models.reservations import ReservationMaybeExclusive, ReservationGroup, BaseReservation from kitabu.models import validators from pools.models import Pool class Lane(VariableSizeSubject, BaseSubject): name = models.TextField() cluster = models.ForeignKey(Pool, related_name='subjects') def __unicode__(self): return self.name class LaneReservation(ReservationMaybeExclusive, BaseReservation): subject = models.ForeignKey('Lane', related_name='reservations') group = models.ForeignKey('LaneReservationGroup', related_name='reservations', null=True, blank=True) owner = models.ForeignKey(User, null=True) def __unicode__(self): return "%s from %s to %s (%s places)" % (self.subject.name, self.start, self.end, self.size) class LaneReservationGroup(ReservationGroup): pass class LaneFullTimeValidator(validators.FullTimeValidator): pass class LaneTimeIntervalValidator(validators.TimeIntervalValidator): pass class LaneWithinPeriodValidator(validators.WithinPeriodValidator): pass class Period(validators.Period): validator = models.ForeignKey(LaneWithinPeriodValidator, related_name='periods') class LaneNotWithinPeriodValidator(validators.NotWithinPeriodValidator): pass class LaneGivenHoursAndWeekdaysValidator(validators.GivenHoursAndWeekdaysValidator): pass class LaneMaxReservationsPerUserValidator(validators.MaxReservationsPerUserValidator): pass
Add new validators to SPA
Add new validators to SPA
Python
mit
mbad/kitabu,mbad/kitabu,mbad/kitabu
python
## Code Before: from django.db import models from django.contrib.auth.models import User from kitabu.models.subjects import VariableSizeSubject, BaseSubject from kitabu.models.reservations import ReservationMaybeExclusive, ReservationGroup, BaseReservation from kitabu.models import validators from pools.models import Pool class Lane(VariableSizeSubject, BaseSubject): name = models.TextField() cluster = models.ForeignKey(Pool, related_name='subjects') def __unicode__(self): return self.name class LaneReservation(ReservationMaybeExclusive, BaseReservation): subject = models.ForeignKey('Lane', related_name='reservations') group = models.ForeignKey('LaneReservationGroup', related_name='reservations', null=True, blank=True) owner = models.ForeignKey(User, null=True) def __unicode__(self): return "%s from %s to %s (%s places)" % (self.subject.name, self.start, self.end, self.size) class LaneReservationGroup(ReservationGroup): pass class LaneFullTimeValidator(validators.FullTimeValidator): pass class LaneTimeIntervalValidator(validators.TimeIntervalValidator): pass class LaneWithinPeriodValidator(validators.WithinPeriodValidator): pass class LaneNotWithinPeriodValidator(validators.NotWithinPeriodValidator): pass class LaneGivenHoursAndWeekdaysValidator(validators.GivenHoursAndWeekdaysValidator): pass ## Instruction: Add new validators to SPA ## Code After: from django.db import models from django.contrib.auth.models import User from kitabu.models.subjects import VariableSizeSubject, BaseSubject from kitabu.models.reservations import ReservationMaybeExclusive, ReservationGroup, BaseReservation from kitabu.models import validators from pools.models import Pool class Lane(VariableSizeSubject, BaseSubject): name = models.TextField() cluster = models.ForeignKey(Pool, related_name='subjects') def __unicode__(self): return self.name class LaneReservation(ReservationMaybeExclusive, BaseReservation): subject = models.ForeignKey('Lane', related_name='reservations') group = models.ForeignKey('LaneReservationGroup', related_name='reservations', null=True, blank=True) owner = models.ForeignKey(User, null=True) def __unicode__(self): return "%s from %s to %s (%s places)" % (self.subject.name, self.start, self.end, self.size) class LaneReservationGroup(ReservationGroup): pass class LaneFullTimeValidator(validators.FullTimeValidator): pass class LaneTimeIntervalValidator(validators.TimeIntervalValidator): pass class LaneWithinPeriodValidator(validators.WithinPeriodValidator): pass class Period(validators.Period): validator = models.ForeignKey(LaneWithinPeriodValidator, related_name='periods') class LaneNotWithinPeriodValidator(validators.NotWithinPeriodValidator): pass class LaneGivenHoursAndWeekdaysValidator(validators.GivenHoursAndWeekdaysValidator): pass class LaneMaxReservationsPerUserValidator(validators.MaxReservationsPerUserValidator): pass
// ... existing code ... pass class Period(validators.Period): validator = models.ForeignKey(LaneWithinPeriodValidator, related_name='periods') class LaneNotWithinPeriodValidator(validators.NotWithinPeriodValidator): pass // ... modified code ... class LaneGivenHoursAndWeekdaysValidator(validators.GivenHoursAndWeekdaysValidator): pass class LaneMaxReservationsPerUserValidator(validators.MaxReservationsPerUserValidator): pass // ... rest of the code ...
de514f15cd1bc2ae0bad203d51feafe9b92a9258
tests/environment_variables/env_var_test.c
tests/environment_variables/env_var_test.c
/* * Copyright 2010 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char **argv, char **env) { int count = 0; char **ptr; for (ptr = environ; *ptr != NULL; ptr++) { count++; } printf("%i environment variables\n", count); for (ptr = environ; *ptr != NULL; ptr++) { printf("%s\n", *ptr); } assert(env == environ); return 0; }
/* * Copyright 2010 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <assert.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> /* * In the glibc dynamic linking case, CommandSelLdrTestNacl * passes LD_LIBRARY_PATH in the environment for tests. * Ignore this variable for purposes of this test. */ static bool skip_env_var(const char *envstring) { #ifdef __GLIBC__ static const char kLdLibraryPath[] = "LD_LIBRARY_PATH="; if (!strncmp(envstring, kLdLibraryPath, sizeof(kLdLibraryPath) - 1)) return true; #endif return false; } int main(int argc, char **argv, char **env) { int count = 0; char **ptr; for (ptr = environ; *ptr != NULL; ptr++) { if (!skip_env_var(*ptr)) count++; } printf("%i environment variables\n", count); for (ptr = environ; *ptr != NULL; ptr++) { if (!skip_env_var(*ptr)) puts(*ptr); } assert(env == environ); return 0; }
Make environment_variables test ignore LD_LIBRARY_PATH for glibc
Make environment_variables test ignore LD_LIBRARY_PATH for glibc This test pumps specific values through sel_ldr with -E and then tests that the entire environment seen by the untrusted program is exactly that list, using a golden file. CommandSelLdrTestNacl uses -E to pass LD_LIBRARY_PATH to the nexe for new (ARM) glibc. So that variable's presence in environ is not a bug. BUG= https://code.google.com/p/nativeclient/issues/detail?id=3068 TEST= trybots + scons platform=arm --nacl_glibc run_env_var_test_irt [email protected], [email protected] Review URL: https://codereview.chromium.org/1116963005
C
bsd-3-clause
sbc100/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client
c
## Code Before: /* * Copyright 2010 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main(int argc, char **argv, char **env) { int count = 0; char **ptr; for (ptr = environ; *ptr != NULL; ptr++) { count++; } printf("%i environment variables\n", count); for (ptr = environ; *ptr != NULL; ptr++) { printf("%s\n", *ptr); } assert(env == environ); return 0; } ## Instruction: Make environment_variables test ignore LD_LIBRARY_PATH for glibc This test pumps specific values through sel_ldr with -E and then tests that the entire environment seen by the untrusted program is exactly that list, using a golden file. CommandSelLdrTestNacl uses -E to pass LD_LIBRARY_PATH to the nexe for new (ARM) glibc. So that variable's presence in environ is not a bug. BUG= https://code.google.com/p/nativeclient/issues/detail?id=3068 TEST= trybots + scons platform=arm --nacl_glibc run_env_var_test_irt [email protected], [email protected] Review URL: https://codereview.chromium.org/1116963005 ## Code After: /* * Copyright 2010 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <assert.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> /* * In the glibc dynamic linking case, CommandSelLdrTestNacl * passes LD_LIBRARY_PATH in the environment for tests. * Ignore this variable for purposes of this test. */ static bool skip_env_var(const char *envstring) { #ifdef __GLIBC__ static const char kLdLibraryPath[] = "LD_LIBRARY_PATH="; if (!strncmp(envstring, kLdLibraryPath, sizeof(kLdLibraryPath) - 1)) return true; #endif return false; } int main(int argc, char **argv, char **env) { int count = 0; char **ptr; for (ptr = environ; *ptr != NULL; ptr++) { if (!skip_env_var(*ptr)) count++; } printf("%i environment variables\n", count); for (ptr = environ; *ptr != NULL; ptr++) { if (!skip_env_var(*ptr)) puts(*ptr); } assert(env == environ); return 0; }
# ... existing code ... */ #include <assert.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> /* * In the glibc dynamic linking case, CommandSelLdrTestNacl * passes LD_LIBRARY_PATH in the environment for tests. * Ignore this variable for purposes of this test. */ static bool skip_env_var(const char *envstring) { #ifdef __GLIBC__ static const char kLdLibraryPath[] = "LD_LIBRARY_PATH="; if (!strncmp(envstring, kLdLibraryPath, sizeof(kLdLibraryPath) - 1)) return true; #endif return false; } int main(int argc, char **argv, char **env) { int count = 0; # ... modified code ... char **ptr; for (ptr = environ; *ptr != NULL; ptr++) { if (!skip_env_var(*ptr)) count++; } printf("%i environment variables\n", count); for (ptr = environ; *ptr != NULL; ptr++) { if (!skip_env_var(*ptr)) puts(*ptr); } assert(env == environ); # ... rest of the code ...
1c909afb1ba410349b2c3a1255e0664ef48847ab
src/main/java/dk/nversion/copybook/converters/IntegerToBoolean.java
src/main/java/dk/nversion/copybook/converters/IntegerToBoolean.java
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Licensed under the MIT license (LICENSE.txt) */ package dk.nversion.copybook.converters; import dk.nversion.copybook.exceptions.TypeConverterException; public class IntegerToBoolean extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!(Boolean.class.equals(type) || Boolean.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from int or Integer"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { return (int)super.to(bytes, offset, length, decimals, removePadding) != 0; } @Override public byte[] from(Object value, int length, int decimals, boolean addPadding) { return super.from((boolean)value ? 1 : 0, length, decimals, addPadding); } }
/* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Licensed under the MIT license (LICENSE.txt) */ package dk.nversion.copybook.converters; import dk.nversion.copybook.exceptions.TypeConverterException; public class IntegerToBoolean extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!(Boolean.class.equals(type) || Boolean.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from int or Integer"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { return (int)super.to(bytes, offset, length, decimals, removePadding) != 0; } @Override public byte[] from(Object value, int length, int decimals, boolean addPadding) { return super.from(value != null ? ((boolean)value ? 1 : 0) : null, length, decimals, addPadding); } }
Handle that we could use the object version of Boolean and it could be null
Handle that we could use the object version of Boolean and it could be null
Java
mit
tlbdk/copybook4java,tlbdk/copybook4java,NordeaOSS/copybook4java,tlbdk/copybook4java,NordeaOSS/copybook4java,NordeaOSS/copybook4java
java
## Code Before: /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Licensed under the MIT license (LICENSE.txt) */ package dk.nversion.copybook.converters; import dk.nversion.copybook.exceptions.TypeConverterException; public class IntegerToBoolean extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!(Boolean.class.equals(type) || Boolean.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from int or Integer"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { return (int)super.to(bytes, offset, length, decimals, removePadding) != 0; } @Override public byte[] from(Object value, int length, int decimals, boolean addPadding) { return super.from((boolean)value ? 1 : 0, length, decimals, addPadding); } } ## Instruction: Handle that we could use the object version of Boolean and it could be null ## Code After: /* * Copyright (c) 2015. Troels Liebe Bentsen <[email protected]> * Licensed under the MIT license (LICENSE.txt) */ package dk.nversion.copybook.converters; import dk.nversion.copybook.exceptions.TypeConverterException; public class IntegerToBoolean extends IntegerToInteger { @Override public void validate(Class<?> type, int size, int decimals) { if(!(Boolean.class.equals(type) || Boolean.TYPE.equals(type))) { throw new TypeConverterException("Only supports converting to and from int or Integer"); } } @Override public Object to(byte[] bytes, int offset, int length, int decimals, boolean removePadding) { return (int)super.to(bytes, offset, length, decimals, removePadding) != 0; } @Override public byte[] from(Object value, int length, int decimals, boolean addPadding) { return super.from(value != null ? ((boolean)value ? 1 : 0) : null, length, decimals, addPadding); } }
// ... existing code ... @Override public byte[] from(Object value, int length, int decimals, boolean addPadding) { return super.from(value != null ? ((boolean)value ? 1 : 0) : null, length, decimals, addPadding); } } // ... rest of the code ...
a12e3f0de9e8c10c279d795744f87b7e716bd34c
markitup_filebrowser/fields.py
markitup_filebrowser/fields.py
from markitup.fields import MarkupField import widgets class MarkupFilebrowserFiled(MarkupField): def formfield(self, **kwargs): defaults = {'widget': widgets.MarkitUpFilebrowserWiget} defaults.update(kwargs) return super(MarkupFilebrowserFiled, self).formfield(**defaults) from django.contrib.admin.options import FORMFIELD_FOR_DBFIELD_DEFAULTS FORMFIELD_FOR_DBFIELD_DEFAULTS[MarkupFilebrowserFiled] = {'widget': widgets.AdminMarkitUpFilebrowserWiget}
from markitup.fields import MarkupField import widgets class MarkupFilebrowserFiled(MarkupField): def formfield(self, **kwargs): defaults = {'widget': widgets.MarkitUpFilebrowserWiget} defaults.update(kwargs) return super(MarkupFilebrowserFiled, self).formfield(**defaults) from django.contrib.admin.options import FORMFIELD_FOR_DBFIELD_DEFAULTS FORMFIELD_FOR_DBFIELD_DEFAULTS[MarkupFilebrowserFiled] = {'widget': widgets.AdminMarkitUpFilebrowserWiget} # allow South to handle MarkupField smoothly try: from south.modelsinspector import add_introspection_rules # For a normal MarkupField, the add_rendered_field attribute is # always True, which means no_rendered_field arg will always be # True in a frozen MarkupField, which is what we want. add_introspection_rules(rules=[((MarkupFilebrowserFiled,), [], {'no_rendered_field': ('add_rendered_field', {})})], patterns=['markitup_filebrowser\.fields\.']) except ImportError: pass
Allow south to handle MarkupFilebrowserFiled
Allow south to handle MarkupFilebrowserFiled
Python
bsd-3-clause
Iv/django-markiup-filebrowser,Iv/django-markiup-filebrowser
python
## Code Before: from markitup.fields import MarkupField import widgets class MarkupFilebrowserFiled(MarkupField): def formfield(self, **kwargs): defaults = {'widget': widgets.MarkitUpFilebrowserWiget} defaults.update(kwargs) return super(MarkupFilebrowserFiled, self).formfield(**defaults) from django.contrib.admin.options import FORMFIELD_FOR_DBFIELD_DEFAULTS FORMFIELD_FOR_DBFIELD_DEFAULTS[MarkupFilebrowserFiled] = {'widget': widgets.AdminMarkitUpFilebrowserWiget} ## Instruction: Allow south to handle MarkupFilebrowserFiled ## Code After: from markitup.fields import MarkupField import widgets class MarkupFilebrowserFiled(MarkupField): def formfield(self, **kwargs): defaults = {'widget': widgets.MarkitUpFilebrowserWiget} defaults.update(kwargs) return super(MarkupFilebrowserFiled, self).formfield(**defaults) from django.contrib.admin.options import FORMFIELD_FOR_DBFIELD_DEFAULTS FORMFIELD_FOR_DBFIELD_DEFAULTS[MarkupFilebrowserFiled] = {'widget': widgets.AdminMarkitUpFilebrowserWiget} # allow South to handle MarkupField smoothly try: from south.modelsinspector import add_introspection_rules # For a normal MarkupField, the add_rendered_field attribute is # always True, which means no_rendered_field arg will always be # True in a frozen MarkupField, which is what we want. add_introspection_rules(rules=[((MarkupFilebrowserFiled,), [], {'no_rendered_field': ('add_rendered_field', {})})], patterns=['markitup_filebrowser\.fields\.']) except ImportError: pass
... from django.contrib.admin.options import FORMFIELD_FOR_DBFIELD_DEFAULTS FORMFIELD_FOR_DBFIELD_DEFAULTS[MarkupFilebrowserFiled] = {'widget': widgets.AdminMarkitUpFilebrowserWiget} # allow South to handle MarkupField smoothly try: from south.modelsinspector import add_introspection_rules # For a normal MarkupField, the add_rendered_field attribute is # always True, which means no_rendered_field arg will always be # True in a frozen MarkupField, which is what we want. add_introspection_rules(rules=[((MarkupFilebrowserFiled,), [], {'no_rendered_field': ('add_rendered_field', {})})], patterns=['markitup_filebrowser\.fields\.']) except ImportError: pass ...
ae1a2b73d0c571c49726528f9b8730c9e02ce35f
tests/integration/test_webui.py
tests/integration/test_webui.py
import requests import pytest class TestWebUI(object): def get_page(self, page): return requests.get('http://nginx' + page) pages = [ { 'page': '/', 'matching_text': 'Diamond', }, { 'page': '/scoreboard', }, { 'page': '/login', 'matching_text': 'Please sign in', }, { 'page': '/about', 'matching_text': 'Use the following credentials to login', }, { 'page': '/overview', }, { 'page': '/api/overview/data' } ] @pytest.mark.parametrize("page_data", pages) def test_page(self, page_data): resp = self.get_page(page_data['page']) assert resp.status_code == 200 if 'matching_text' in page_data: assert page_data['matching_text'] in resp.text
import requests import pytest class TestWebUI(object): def get_page(self, page): return requests.get('https://nginx/{0}'.format(page), verify=False) pages = [ { 'page': '', 'matching_text': 'Diamond', }, { 'page': 'scoreboard', }, { 'page': 'login', 'matching_text': 'Please sign in', }, { 'page': 'about', 'matching_text': 'Use the following credentials to login', }, { 'page': 'overview', }, { 'page': 'api/overview/data' } ] @pytest.mark.parametrize("page_data", pages) def test_page(self, page_data): resp = self.get_page(page_data['page']) assert resp.status_code == 200 if 'matching_text' in page_data: assert page_data['matching_text'] in resp.text
Fix webui integration tests to use https
Fix webui integration tests to use https
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
python
## Code Before: import requests import pytest class TestWebUI(object): def get_page(self, page): return requests.get('http://nginx' + page) pages = [ { 'page': '/', 'matching_text': 'Diamond', }, { 'page': '/scoreboard', }, { 'page': '/login', 'matching_text': 'Please sign in', }, { 'page': '/about', 'matching_text': 'Use the following credentials to login', }, { 'page': '/overview', }, { 'page': '/api/overview/data' } ] @pytest.mark.parametrize("page_data", pages) def test_page(self, page_data): resp = self.get_page(page_data['page']) assert resp.status_code == 200 if 'matching_text' in page_data: assert page_data['matching_text'] in resp.text ## Instruction: Fix webui integration tests to use https ## Code After: import requests import pytest class TestWebUI(object): def get_page(self, page): return requests.get('https://nginx/{0}'.format(page), verify=False) pages = [ { 'page': '', 'matching_text': 'Diamond', }, { 'page': 'scoreboard', }, { 'page': 'login', 'matching_text': 'Please sign in', }, { 'page': 'about', 'matching_text': 'Use the following credentials to login', }, { 'page': 'overview', }, { 'page': 'api/overview/data' } ] @pytest.mark.parametrize("page_data", pages) def test_page(self, page_data): resp = self.get_page(page_data['page']) assert resp.status_code == 200 if 'matching_text' in page_data: assert page_data['matching_text'] in resp.text
... class TestWebUI(object): def get_page(self, page): return requests.get('https://nginx/{0}'.format(page), verify=False) pages = [ { 'page': '', 'matching_text': 'Diamond', }, { 'page': 'scoreboard', }, { 'page': 'login', 'matching_text': 'Please sign in', }, { 'page': 'about', 'matching_text': 'Use the following credentials to login', }, { 'page': 'overview', }, { 'page': 'api/overview/data' } ] ...
93c914a0537ee0665e5139e8a8a8bc9508a25dd7
test/strings/format2.py
test/strings/format2.py
"normal {{ normal }} normal {fo.__add__!s}" " : source.python, string.quoted.double.python normal : source.python, string.quoted.double.python {{ : constant.character.format.python, source.python, string.quoted.double.python normal : source.python, string.quoted.double.python }} : constant.character.format.python, source.python, string.quoted.double.python normal : source.python, string.quoted.double.python {fo.__add__ : constant.character.format.python, source.python, string.quoted.double.python !s : constant.character.format.python, source.python, storage.type.format.python, string.quoted.double.python } : constant.character.format.python, source.python, string.quoted.double.python " : source.python, string.quoted.double.python
"normal {{ normal }} normal {fo.__add__!s}".format(fo=1) " : source.python, string.quoted.double.python normal : source.python, string.quoted.double.python {{ : constant.character.format.python, source.python, string.quoted.double.python normal : source.python, string.quoted.double.python }} : constant.character.format.python, source.python, string.quoted.double.python normal : source.python, string.quoted.double.python {fo.__add__ : constant.character.format.python, source.python, string.quoted.double.python !s : constant.character.format.python, source.python, storage.type.format.python, string.quoted.double.python } : constant.character.format.python, source.python, string.quoted.double.python " : source.python, string.quoted.double.python . : source.python format : meta.function-call.python, source.python ( : meta.function-call.arguments.python, meta.function-call.python, punctuation.definition.arguments.begin.python, source.python fo : meta.function-call.arguments.python, meta.function-call.python, source.python, variable.parameter.function-call.pyhton = : keyword.operator.assignment.python, meta.function-call.arguments.python, meta.function-call.python, source.python 1 : constant.numeric.dec.python, meta.function-call.arguments.python, meta.function-call.python, source.python ) : meta.function-call.python, punctuation.definition.arguments.end.python, source.python
Add a test for .format() method
Add a test for .format() method
Python
mit
MagicStack/MagicPython,MagicStack/MagicPython,MagicStack/MagicPython
python
## Code Before: "normal {{ normal }} normal {fo.__add__!s}" " : source.python, string.quoted.double.python normal : source.python, string.quoted.double.python {{ : constant.character.format.python, source.python, string.quoted.double.python normal : source.python, string.quoted.double.python }} : constant.character.format.python, source.python, string.quoted.double.python normal : source.python, string.quoted.double.python {fo.__add__ : constant.character.format.python, source.python, string.quoted.double.python !s : constant.character.format.python, source.python, storage.type.format.python, string.quoted.double.python } : constant.character.format.python, source.python, string.quoted.double.python " : source.python, string.quoted.double.python ## Instruction: Add a test for .format() method ## Code After: "normal {{ normal }} normal {fo.__add__!s}".format(fo=1) " : source.python, string.quoted.double.python normal : source.python, string.quoted.double.python {{ : constant.character.format.python, source.python, string.quoted.double.python normal : source.python, string.quoted.double.python }} : constant.character.format.python, source.python, string.quoted.double.python normal : source.python, string.quoted.double.python {fo.__add__ : constant.character.format.python, source.python, string.quoted.double.python !s : constant.character.format.python, source.python, storage.type.format.python, string.quoted.double.python } : constant.character.format.python, source.python, string.quoted.double.python " : source.python, string.quoted.double.python . : source.python format : meta.function-call.python, source.python ( : meta.function-call.arguments.python, meta.function-call.python, punctuation.definition.arguments.begin.python, source.python fo : meta.function-call.arguments.python, meta.function-call.python, source.python, variable.parameter.function-call.pyhton = : keyword.operator.assignment.python, meta.function-call.arguments.python, meta.function-call.python, source.python 1 : constant.numeric.dec.python, meta.function-call.arguments.python, meta.function-call.python, source.python ) : meta.function-call.python, punctuation.definition.arguments.end.python, source.python
// ... existing code ... "normal {{ normal }} normal {fo.__add__!s}".format(fo=1) " : source.python, string.quoted.double.python // ... modified code ... !s : constant.character.format.python, source.python, storage.type.format.python, string.quoted.double.python } : constant.character.format.python, source.python, string.quoted.double.python " : source.python, string.quoted.double.python . : source.python format : meta.function-call.python, source.python ( : meta.function-call.arguments.python, meta.function-call.python, punctuation.definition.arguments.begin.python, source.python fo : meta.function-call.arguments.python, meta.function-call.python, source.python, variable.parameter.function-call.pyhton = : keyword.operator.assignment.python, meta.function-call.arguments.python, meta.function-call.python, source.python 1 : constant.numeric.dec.python, meta.function-call.arguments.python, meta.function-call.python, source.python ) : meta.function-call.python, punctuation.definition.arguments.end.python, source.python // ... rest of the code ...
aee8d2911c3f19a9b748f21ae82592d823e0c57e
update.py
update.py
import os, subprocess os.chdir(os.path.dirname(os.path.abspath(__file__))) subprocess.call([ 'python', os.path.join('..', 'venus', 'planet.py'), 'planet.ini' ]) subprocess.call([ 'python', 'aws', 's3', 'sync', '--region', 'us-east-1', 'public/', 's3://tempura.8-p.info/' ])
import os, subprocess os.chdir(os.path.dirname(os.path.abspath(__file__))) subprocess.call([ 'python', os.path.join('..', 'venus', 'planet.py'), 'planet.ini' ]) subprocess.call([ 'python', 'aws', 's3', 'sync', '--region', 'us-east-1', '--acl', 'public-read', 'public/', 's3://tempura.8-p.info/' ])
Set ACL explicitly to make files readable
Set ACL explicitly to make files readable
Python
mit
kzys/planet-tempura
python
## Code Before: import os, subprocess os.chdir(os.path.dirname(os.path.abspath(__file__))) subprocess.call([ 'python', os.path.join('..', 'venus', 'planet.py'), 'planet.ini' ]) subprocess.call([ 'python', 'aws', 's3', 'sync', '--region', 'us-east-1', 'public/', 's3://tempura.8-p.info/' ]) ## Instruction: Set ACL explicitly to make files readable ## Code After: import os, subprocess os.chdir(os.path.dirname(os.path.abspath(__file__))) subprocess.call([ 'python', os.path.join('..', 'venus', 'planet.py'), 'planet.ini' ]) subprocess.call([ 'python', 'aws', 's3', 'sync', '--region', 'us-east-1', '--acl', 'public-read', 'public/', 's3://tempura.8-p.info/' ])
// ... existing code ... subprocess.call([ 'python', 'aws', 's3', 'sync', '--region', 'us-east-1', '--acl', 'public-read', 'public/', 's3://tempura.8-p.info/' ]) // ... rest of the code ...
e2ee2dab59a8367c3a94f0d7ed74d29e5236b16c
include/stdlib.h
include/stdlib.h
/* * Copyright (C) 2014, Galois, Inc. * This sotware is distributed under a standard, three-clause BSD license. * Please see the file LICENSE, distributed with this software, for specific * terms and conditions. */ #ifndef MINLIBC_STDLIB_H #define MINLIBC_STDLIB_H #define NULL 0 #define EXIT_SUCCESS 0 #define EXIT_FAILURE 1 typedef unsigned long int size_t; double atof(const char *nptr); int atoi(const char *nptr); long int strtol(const char *nptr, char **endptr, int base); char *getenv(const char *name); void abort(void); void exit(int status); void *malloc(size_t size); void *realloc(void *ptr, size_t size); void *calloc(size_t nmemb, size_t size); void free(void *ptr); int mkstemp(char *template); void *bsearch(const void *, const void *, size_t, size_t, int (*)(const void *, const void *)); int putenv(char *str); int unsetenv(const char *name); #endif
/* * Copyright (C) 2014, Galois, Inc. * This sotware is distributed under a standard, three-clause BSD license. * Please see the file LICENSE, distributed with this software, for specific * terms and conditions. */ #ifndef MINLIBC_STDLIB_H #define MINLIBC_STDLIB_H #define NULL 0 #define EXIT_SUCCESS 0 #define EXIT_FAILURE 1 typedef unsigned long int size_t; double atof(const char *nptr); int atoi(const char *nptr); long int strtol(const char *nptr, char **endptr, int base); char *getenv(const char *name); void abort(void); void exit(int status); void *malloc(size_t size); void *realloc(void *ptr, size_t size); void *calloc(size_t nmemb, size_t size); void free(void *ptr); int mkstemp(char *template); void *bsearch(const void *, const void *, size_t, size_t, int (*)(const void *, const void *)); int putenv(char *str); int unsetenv(const char *name); int abs(int j); #endif
Add a prototype for abs().
Add a prototype for abs().
C
bsd-3-clause
GaloisInc/minlibc,GaloisInc/minlibc
c
## Code Before: /* * Copyright (C) 2014, Galois, Inc. * This sotware is distributed under a standard, three-clause BSD license. * Please see the file LICENSE, distributed with this software, for specific * terms and conditions. */ #ifndef MINLIBC_STDLIB_H #define MINLIBC_STDLIB_H #define NULL 0 #define EXIT_SUCCESS 0 #define EXIT_FAILURE 1 typedef unsigned long int size_t; double atof(const char *nptr); int atoi(const char *nptr); long int strtol(const char *nptr, char **endptr, int base); char *getenv(const char *name); void abort(void); void exit(int status); void *malloc(size_t size); void *realloc(void *ptr, size_t size); void *calloc(size_t nmemb, size_t size); void free(void *ptr); int mkstemp(char *template); void *bsearch(const void *, const void *, size_t, size_t, int (*)(const void *, const void *)); int putenv(char *str); int unsetenv(const char *name); #endif ## Instruction: Add a prototype for abs(). ## Code After: /* * Copyright (C) 2014, Galois, Inc. * This sotware is distributed under a standard, three-clause BSD license. * Please see the file LICENSE, distributed with this software, for specific * terms and conditions. */ #ifndef MINLIBC_STDLIB_H #define MINLIBC_STDLIB_H #define NULL 0 #define EXIT_SUCCESS 0 #define EXIT_FAILURE 1 typedef unsigned long int size_t; double atof(const char *nptr); int atoi(const char *nptr); long int strtol(const char *nptr, char **endptr, int base); char *getenv(const char *name); void abort(void); void exit(int status); void *malloc(size_t size); void *realloc(void *ptr, size_t size); void *calloc(size_t nmemb, size_t size); void free(void *ptr); int mkstemp(char *template); void *bsearch(const void *, const void *, size_t, size_t, int (*)(const void *, const void *)); int putenv(char *str); int unsetenv(const char *name); int abs(int j); #endif
... int putenv(char *str); int unsetenv(const char *name); int abs(int j); #endif ...
e92784a36053e6708a3eb2772f4c5cd4e16cde4a
app/base/templatetags/git.py
app/base/templatetags/git.py
import subprocess from django.template import Library register = Library() try: head = subprocess.Popen("git rev-parse --short HEAD", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) VERSION = head.stdout.readline().strip() except: VERSION = u'unknown' @register.simple_tag() def git_version(): return VERSION
import subprocess from django.template import Library register = Library() GIT_VERSION = None @register.simple_tag() def git_version(): global GIT_VERSION if GIT_VERSION: return GIT_VERSION try: head = subprocess.Popen("git rev-parse --short HEAD", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) GIT_VERSION = head.stdout.readline().strip() except: GIT_VERSION = 'unknown' return GIT_VERSION
Make GIT_VERSION on footer more robust
[REFACTOR] Make GIT_VERSION on footer more robust
Python
mit
internship2016/sovolo,internship2016/sovolo,internship2016/sovolo
python
## Code Before: import subprocess from django.template import Library register = Library() try: head = subprocess.Popen("git rev-parse --short HEAD", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) VERSION = head.stdout.readline().strip() except: VERSION = u'unknown' @register.simple_tag() def git_version(): return VERSION ## Instruction: [REFACTOR] Make GIT_VERSION on footer more robust ## Code After: import subprocess from django.template import Library register = Library() GIT_VERSION = None @register.simple_tag() def git_version(): global GIT_VERSION if GIT_VERSION: return GIT_VERSION try: head = subprocess.Popen("git rev-parse --short HEAD", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) GIT_VERSION = head.stdout.readline().strip() except: GIT_VERSION = 'unknown' return GIT_VERSION
# ... existing code ... register = Library() GIT_VERSION = None @register.simple_tag() def git_version(): global GIT_VERSION if GIT_VERSION: return GIT_VERSION try: head = subprocess.Popen("git rev-parse --short HEAD", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) GIT_VERSION = head.stdout.readline().strip() except: GIT_VERSION = 'unknown' return GIT_VERSION # ... rest of the code ...
7a276551f8349db28f32c36a68ab96c46c90517c
storage/src/vespa/storage/common/bucket_utils.h
storage/src/vespa/storage/common/bucket_utils.h
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <vespa/document/bucket/bucketid.h> #include <vespa/persistence/spi/bucket_limits.h> #include <cassert> namespace storage { /** * Returns the super bucket key of the given bucket id key based on the minimum used bits allowed. */ uint64_t get_super_bucket_key(const document::BucketId& bucket_id) { assert(bucket_id.getUsedBits() >= spi::BucketLimits::MinUsedBits); // Since bucket keys have count-bits at the LSB positions, we want to look at the MSBs instead. return (bucket_id.toKey() >> (64 - spi::BucketLimits::MinUsedBits)); } }
// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <vespa/document/bucket/bucketid.h> #include <vespa/persistence/spi/bucket_limits.h> #include <cassert> namespace storage { /** * Returns the super bucket key of the given bucket id key based on the minimum used bits allowed. */ inline uint64_t get_super_bucket_key(const document::BucketId& bucket_id) noexcept { assert(bucket_id.getUsedBits() >= spi::BucketLimits::MinUsedBits); // Since bucket keys have count-bits at the LSB positions, we want to look at the MSBs instead. return (bucket_id.toKey() >> (64 - spi::BucketLimits::MinUsedBits)); } }
Make function inline and noexcept.
Make function inline and noexcept.
C
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
c
## Code Before: // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <vespa/document/bucket/bucketid.h> #include <vespa/persistence/spi/bucket_limits.h> #include <cassert> namespace storage { /** * Returns the super bucket key of the given bucket id key based on the minimum used bits allowed. */ uint64_t get_super_bucket_key(const document::BucketId& bucket_id) { assert(bucket_id.getUsedBits() >= spi::BucketLimits::MinUsedBits); // Since bucket keys have count-bits at the LSB positions, we want to look at the MSBs instead. return (bucket_id.toKey() >> (64 - spi::BucketLimits::MinUsedBits)); } } ## Instruction: Make function inline and noexcept. ## Code After: // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <vespa/document/bucket/bucketid.h> #include <vespa/persistence/spi/bucket_limits.h> #include <cassert> namespace storage { /** * Returns the super bucket key of the given bucket id key based on the minimum used bits allowed. */ inline uint64_t get_super_bucket_key(const document::BucketId& bucket_id) noexcept { assert(bucket_id.getUsedBits() >= spi::BucketLimits::MinUsedBits); // Since bucket keys have count-bits at the LSB positions, we want to look at the MSBs instead. return (bucket_id.toKey() >> (64 - spi::BucketLimits::MinUsedBits)); } }
# ... existing code ... /** * Returns the super bucket key of the given bucket id key based on the minimum used bits allowed. */ inline uint64_t get_super_bucket_key(const document::BucketId& bucket_id) noexcept { assert(bucket_id.getUsedBits() >= spi::BucketLimits::MinUsedBits); // Since bucket keys have count-bits at the LSB positions, we want to look at the MSBs instead. return (bucket_id.toKey() >> (64 - spi::BucketLimits::MinUsedBits)); # ... rest of the code ...
c17f827aedb944eec4ea5e55172db6f190acebb7
src/main/java/tdl/examples/AddNumbers.java
src/main/java/tdl/examples/AddNumbers.java
package tdl.examples; import tdl.client.Client; /** * Created by julianghionoiu on 11/06/2015. */ public class AddNumbers { public static void main(String[] args) throws Exception { Client client = new Client("localhost", 21616, "test"); client.goLiveWith(params -> { Integer x = Integer.parseInt(params[0]); Integer y = Integer.parseInt(params[1]); return x + y; }); } }
package tdl.examples; import tdl.client.Client; import tdl.client.abstractions.UserImplementation; /** * Created by julianghionoiu on 11/06/2015. */ public class AddNumbers { public static void main(String[] args) throws Exception { Client client = new Client("localhost", 21616, "test"); client.goLiveWith(new UserImplementation() { @Override public Object process(String... params) { Integer x = Integer.parseInt(params[0]); Integer y = Integer.parseInt(params[1]); return x + y; } }); } }
Replace lambda in example with anonymous class to fix cobertura
Replace lambda in example with anonymous class to fix cobertura
Java
apache-2.0
julianghionoiu/tdl-client-java,julianghionoiu/tdl-client-java
java
## Code Before: package tdl.examples; import tdl.client.Client; /** * Created by julianghionoiu on 11/06/2015. */ public class AddNumbers { public static void main(String[] args) throws Exception { Client client = new Client("localhost", 21616, "test"); client.goLiveWith(params -> { Integer x = Integer.parseInt(params[0]); Integer y = Integer.parseInt(params[1]); return x + y; }); } } ## Instruction: Replace lambda in example with anonymous class to fix cobertura ## Code After: package tdl.examples; import tdl.client.Client; import tdl.client.abstractions.UserImplementation; /** * Created by julianghionoiu on 11/06/2015. */ public class AddNumbers { public static void main(String[] args) throws Exception { Client client = new Client("localhost", 21616, "test"); client.goLiveWith(new UserImplementation() { @Override public Object process(String... params) { Integer x = Integer.parseInt(params[0]); Integer y = Integer.parseInt(params[1]); return x + y; } }); } }
// ... existing code ... package tdl.examples; import tdl.client.Client; import tdl.client.abstractions.UserImplementation; /** * Created by julianghionoiu on 11/06/2015. // ... modified code ... public static void main(String[] args) throws Exception { Client client = new Client("localhost", 21616, "test"); client.goLiveWith(new UserImplementation() { @Override public Object process(String... params) { Integer x = Integer.parseInt(params[0]); Integer y = Integer.parseInt(params[1]); return x + y; } }); } } // ... rest of the code ...
918b001cb6d9743d3d2ee1b2bab8f14c90e1adf7
src/ice/rom_finder.py
src/ice/rom_finder.py
from console import Console from rom import ROM from functools import reduce class ROMFinder(object): def __init__(self, filesystem): self.filesystem = filesystem def roms_for_console(self, console): """ @param console - A console object @returns A list of ROM objects representing all of the valid ROMs for a given console. Valid ROMs are defined as ROMs for which `console`'s `is_valid_rom` method returns True. Returns an empty list if `console` is not enabled """ if not console.is_enabled(): return [] paths = self.filesystem.files_in_directory(console.roms_directory()) valid_rom_paths = filter(console.is_valid_rom, paths) return map(lambda path: ROM(path, console), valid_rom_paths) def roms_for_consoles(self, consoles): """ @param consoles - An iterable list of consoles @returns A list of all of the ROMs for all of the consoles in `consoles` Equivalent to calling `roms_for_console` on every element of `consoles` and combining the results """ assert hasattr( consoles, '__iter__'), "Expecting an iterable list of consoles" def rom_collector(roms, console): roms.extend(self.roms_for_console(console)) return roms return reduce(rom_collector, consoles, [])
from console import Console from rom import ROM from functools import reduce class ROMFinder(object): def __init__(self, filesystem): self.filesystem = filesystem def roms_for_console(self, console): """ @param console - A console object @returns A list of ROM objects representing all of the valid ROMs for a given console. Valid ROMs are defined as ROMs for which `console`'s `is_valid_rom` method returns True. Returns an empty list if `console` is not enabled """ if not console.is_enabled(): return [] paths = self.filesystem.files_in_directory(console.roms_directory()) valid_rom_paths = filter(console.is_valid_rom, paths) return map(lambda path: ROM(path, console), valid_rom_paths) def roms_for_consoles(self, consoles): """ @param consoles - An iterable list of consoles @returns A list of all of the ROMs for all of the consoles in `consoles` Equivalent to calling `roms_for_console` on every element of `consoles` and combining the results """ return reduce(lambda roms, console: roms + self.roms_for_console(console), consoles, [])
Replace 'list.extend' call with '+' operator
[Cleanup] Replace 'list.extend' call with '+' operator I knew there had to be an easier way for merging lists other than `extend`. Turns out the plus operator does exactly what I need.
Python
mit
rdoyle1978/Ice,scottrice/Ice
python
## Code Before: from console import Console from rom import ROM from functools import reduce class ROMFinder(object): def __init__(self, filesystem): self.filesystem = filesystem def roms_for_console(self, console): """ @param console - A console object @returns A list of ROM objects representing all of the valid ROMs for a given console. Valid ROMs are defined as ROMs for which `console`'s `is_valid_rom` method returns True. Returns an empty list if `console` is not enabled """ if not console.is_enabled(): return [] paths = self.filesystem.files_in_directory(console.roms_directory()) valid_rom_paths = filter(console.is_valid_rom, paths) return map(lambda path: ROM(path, console), valid_rom_paths) def roms_for_consoles(self, consoles): """ @param consoles - An iterable list of consoles @returns A list of all of the ROMs for all of the consoles in `consoles` Equivalent to calling `roms_for_console` on every element of `consoles` and combining the results """ assert hasattr( consoles, '__iter__'), "Expecting an iterable list of consoles" def rom_collector(roms, console): roms.extend(self.roms_for_console(console)) return roms return reduce(rom_collector, consoles, []) ## Instruction: [Cleanup] Replace 'list.extend' call with '+' operator I knew there had to be an easier way for merging lists other than `extend`. Turns out the plus operator does exactly what I need. ## Code After: from console import Console from rom import ROM from functools import reduce class ROMFinder(object): def __init__(self, filesystem): self.filesystem = filesystem def roms_for_console(self, console): """ @param console - A console object @returns A list of ROM objects representing all of the valid ROMs for a given console. Valid ROMs are defined as ROMs for which `console`'s `is_valid_rom` method returns True. Returns an empty list if `console` is not enabled """ if not console.is_enabled(): return [] paths = self.filesystem.files_in_directory(console.roms_directory()) valid_rom_paths = filter(console.is_valid_rom, paths) return map(lambda path: ROM(path, console), valid_rom_paths) def roms_for_consoles(self, consoles): """ @param consoles - An iterable list of consoles @returns A list of all of the ROMs for all of the consoles in `consoles` Equivalent to calling `roms_for_console` on every element of `consoles` and combining the results """ return reduce(lambda roms, console: roms + self.roms_for_console(console), consoles, [])
# ... existing code ... Equivalent to calling `roms_for_console` on every element of `consoles` and combining the results """ return reduce(lambda roms, console: roms + self.roms_for_console(console), consoles, []) # ... rest of the code ...
86a23691ed0e1c2e57be9de4bdd8dbb4200efd86
core-examples/src/main/java/io/vertx/example/core/eventbus/pointtopoint/Sender.java
core-examples/src/main/java/io/vertx/example/core/eventbus/pointtopoint/Sender.java
package io.vertx.example.core.eventbus.pointtopoint; import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.EventBus; import io.vertx.example.util.Runner; /* * @author <a href="http://tfox.org">Tim Fox</a> */ public class Sender extends AbstractVerticle { // Convenience method so you can run it in your IDE public static void main(String[] args) { Runner.runClusteredExample(Sender.class); } @Override public void start() throws Exception { EventBus eb = vertx.eventBus(); // Send a message every second vertx.setPeriodic(1000, v -> { eb.send("ping-address", "ping!", reply -> { System.out.println("Received reply " + reply.result().body()); }); }); } }
package io.vertx.example.core.eventbus.pointtopoint; import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.EventBus; import io.vertx.example.util.Runner; /* * @author <a href="http://tfox.org">Tim Fox</a> */ public class Sender extends AbstractVerticle { // Convenience method so you can run it in your IDE public static void main(String[] args) { Runner.runClusteredExample(Sender.class); } @Override public void start() throws Exception { EventBus eb = vertx.eventBus(); // Send a message every second vertx.setPeriodic(1000, v -> { eb.send("ping-address", "ping!", reply -> { if (reply.succeeded()) { System.out.println("Received reply " + reply.result().body()); } else { System.out.println("No reply"); } }); }); } }
Improve reply handler in pointtopoint examples
Improve reply handler in pointtopoint examples
Java
apache-2.0
vert-x3/vertx-examples,vert-x3/vertx-examples,vert-x3/vertx-examples,vert-x3/vertx-examples,vert-x3/vertx-examples
java
## Code Before: package io.vertx.example.core.eventbus.pointtopoint; import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.EventBus; import io.vertx.example.util.Runner; /* * @author <a href="http://tfox.org">Tim Fox</a> */ public class Sender extends AbstractVerticle { // Convenience method so you can run it in your IDE public static void main(String[] args) { Runner.runClusteredExample(Sender.class); } @Override public void start() throws Exception { EventBus eb = vertx.eventBus(); // Send a message every second vertx.setPeriodic(1000, v -> { eb.send("ping-address", "ping!", reply -> { System.out.println("Received reply " + reply.result().body()); }); }); } } ## Instruction: Improve reply handler in pointtopoint examples ## Code After: package io.vertx.example.core.eventbus.pointtopoint; import io.vertx.core.AbstractVerticle; import io.vertx.core.eventbus.EventBus; import io.vertx.example.util.Runner; /* * @author <a href="http://tfox.org">Tim Fox</a> */ public class Sender extends AbstractVerticle { // Convenience method so you can run it in your IDE public static void main(String[] args) { Runner.runClusteredExample(Sender.class); } @Override public void start() throws Exception { EventBus eb = vertx.eventBus(); // Send a message every second vertx.setPeriodic(1000, v -> { eb.send("ping-address", "ping!", reply -> { if (reply.succeeded()) { System.out.println("Received reply " + reply.result().body()); } else { System.out.println("No reply"); } }); }); } }
// ... existing code ... vertx.setPeriodic(1000, v -> { eb.send("ping-address", "ping!", reply -> { if (reply.succeeded()) { System.out.println("Received reply " + reply.result().body()); } else { System.out.println("No reply"); } }); }); // ... rest of the code ...
db4b8b2abbb1726a3d2db3496b82e0ad6c0572e9
gateway_mac.py
gateway_mac.py
import socket, struct import scapy.all as scapy def get_default_gateway_linux(): """Read the default gateway directly from /proc.""" with open("/proc/net/route") as fh: for line in fh: fields = line.strip().split() if fields[1] != '00000000' or not int(fields[3], 16) & 2: continue return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))) def get_mac(ip): arp_request = scapy.ARP(pdst=ip) broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff") arp_request_broadcast = broadcast/arp_request answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0] clients_list = [] for element in answered_list: client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc} clients_list.append(client_dict) return clients_list if __name__ == '__main__': default_gw = get_default_gateway_linux() print(get_mac(default_gw))
import socket, struct import scapy.all as scapy def get_default_gateway_linux(): """Read the default gateway directly from /proc.""" routes = [] with open("/proc/net/route") as fh: for line in fh: fields = line.strip().split() if fields[1] != '00000000' or not int(fields[3], 16) & 2: continue routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))) print(routes) return routes def get_mac(ip): arp_request = scapy.ARP(pdst=ip) broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff") arp_request_broadcast = broadcast/arp_request answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0] clients_list = [] for element in answered_list: client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc} clients_list.append(client_dict) return clients_list if __name__ == '__main__': default_gw = get_default_gateway_linux() for g in default_gw: print(get_mac(default_gw))
Update to support multiple default gateways
Update to support multiple default gateways
Python
mit
nulledbyte/scripts
python
## Code Before: import socket, struct import scapy.all as scapy def get_default_gateway_linux(): """Read the default gateway directly from /proc.""" with open("/proc/net/route") as fh: for line in fh: fields = line.strip().split() if fields[1] != '00000000' or not int(fields[3], 16) & 2: continue return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))) def get_mac(ip): arp_request = scapy.ARP(pdst=ip) broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff") arp_request_broadcast = broadcast/arp_request answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0] clients_list = [] for element in answered_list: client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc} clients_list.append(client_dict) return clients_list if __name__ == '__main__': default_gw = get_default_gateway_linux() print(get_mac(default_gw)) ## Instruction: Update to support multiple default gateways ## Code After: import socket, struct import scapy.all as scapy def get_default_gateway_linux(): """Read the default gateway directly from /proc.""" routes = [] with open("/proc/net/route") as fh: for line in fh: fields = line.strip().split() if fields[1] != '00000000' or not int(fields[3], 16) & 2: continue routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))) print(routes) return routes def get_mac(ip): arp_request = scapy.ARP(pdst=ip) broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff") arp_request_broadcast = broadcast/arp_request answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0] clients_list = [] for element in answered_list: client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc} clients_list.append(client_dict) return clients_list if __name__ == '__main__': default_gw = get_default_gateway_linux() for g in default_gw: print(get_mac(default_gw))
// ... existing code ... def get_default_gateway_linux(): """Read the default gateway directly from /proc.""" routes = [] with open("/proc/net/route") as fh: for line in fh: fields = line.strip().split() if fields[1] != '00000000' or not int(fields[3], 16) & 2: continue routes.append(socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))) print(routes) return routes def get_mac(ip): arp_request = scapy.ARP(pdst=ip) // ... modified code ... if __name__ == '__main__': default_gw = get_default_gateway_linux() for g in default_gw: print(get_mac(default_gw)) // ... rest of the code ...
f70bbbdadc044a76f7b90b2cac0191353a6a5048
depfinder.py
depfinder.py
import ast def get_imported_libs(code): tree = ast.parse(code) # ast.Import represents lines like 'import foo' and 'import foo, bar' # the extra for name in t.names is needed, because names is a list that # would be ['foo'] for the first and ['foo', 'bar'] for the second imports = [name.name.split('.')[0] for t in tree.body if type(t) == ast.Import for name in t.names] # ast.ImportFrom represents lines like 'from foo import bar' import_froms = [t.module.split('.')[0] for t in tree.body if type(t) == ast.ImportFrom if t.module] return imports + import_froms
import ast import os from collections import deque import sys from stdlib_list import stdlib_list conf = { 'ignore_relative_imports': True, 'ignore_builtin_modules': True, 'pyver': None, } def get_imported_libs(code): tree = ast.parse(code) imports = deque() for t in tree.body: # ast.Import represents lines like 'import foo' and 'import foo, bar' # the extra for name in t.names is needed, because names is a list that # would be ['foo'] for the first and ['foo', 'bar'] for the second if type(t) == ast.Import: imports.extend([name.name.split('.')[0] for name in t.names]) # ast.ImportFrom represents lines like 'from foo import bar' # t.level == 0 is to get rid of 'from .foo import bar' and higher levels # of relative importing if type(t) == ast.ImportFrom: if t.level > 0: if conf['ignore_relative_imports'] or not t.module: continue else: imports.append(t.module.split('.')[0]) return list(imports) def iterate_over_library(path_to_source_code): libs = set() for parent, folders, files in os.walk(path_to_source_code): for file in files: if file.endswith('.py'): print('.', end='') full_file_path = os.path.join(parent, file) with open(full_file_path, 'r') as f: code = f.read() libs.update(set(get_imported_libs(code))) if conf['ignore_builtin_modules']: if not conf['pyver']: pyver = '%s.%s' % (sys.version_info.major, sys.version_info.minor) std_libs = stdlib_list("3.4") # print(std_libs) libs = [lib for lib in libs if lib not in std_libs] return libs
Rework the import finding logic
MNT: Rework the import finding logic
Python
bsd-3-clause
ericdill/depfinder
python
## Code Before: import ast def get_imported_libs(code): tree = ast.parse(code) # ast.Import represents lines like 'import foo' and 'import foo, bar' # the extra for name in t.names is needed, because names is a list that # would be ['foo'] for the first and ['foo', 'bar'] for the second imports = [name.name.split('.')[0] for t in tree.body if type(t) == ast.Import for name in t.names] # ast.ImportFrom represents lines like 'from foo import bar' import_froms = [t.module.split('.')[0] for t in tree.body if type(t) == ast.ImportFrom if t.module] return imports + import_froms ## Instruction: MNT: Rework the import finding logic ## Code After: import ast import os from collections import deque import sys from stdlib_list import stdlib_list conf = { 'ignore_relative_imports': True, 'ignore_builtin_modules': True, 'pyver': None, } def get_imported_libs(code): tree = ast.parse(code) imports = deque() for t in tree.body: # ast.Import represents lines like 'import foo' and 'import foo, bar' # the extra for name in t.names is needed, because names is a list that # would be ['foo'] for the first and ['foo', 'bar'] for the second if type(t) == ast.Import: imports.extend([name.name.split('.')[0] for name in t.names]) # ast.ImportFrom represents lines like 'from foo import bar' # t.level == 0 is to get rid of 'from .foo import bar' and higher levels # of relative importing if type(t) == ast.ImportFrom: if t.level > 0: if conf['ignore_relative_imports'] or not t.module: continue else: imports.append(t.module.split('.')[0]) return list(imports) def iterate_over_library(path_to_source_code): libs = set() for parent, folders, files in os.walk(path_to_source_code): for file in files: if file.endswith('.py'): print('.', end='') full_file_path = os.path.join(parent, file) with open(full_file_path, 'r') as f: code = f.read() libs.update(set(get_imported_libs(code))) if conf['ignore_builtin_modules']: if not conf['pyver']: pyver = '%s.%s' % (sys.version_info.major, sys.version_info.minor) std_libs = stdlib_list("3.4") # print(std_libs) libs = [lib for lib in libs if lib not in std_libs] return libs
// ... existing code ... import ast import os from collections import deque import sys from stdlib_list import stdlib_list conf = { 'ignore_relative_imports': True, 'ignore_builtin_modules': True, 'pyver': None, } def get_imported_libs(code): tree = ast.parse(code) imports = deque() for t in tree.body: # ast.Import represents lines like 'import foo' and 'import foo, bar' # the extra for name in t.names is needed, because names is a list that # would be ['foo'] for the first and ['foo', 'bar'] for the second if type(t) == ast.Import: imports.extend([name.name.split('.')[0] for name in t.names]) # ast.ImportFrom represents lines like 'from foo import bar' # t.level == 0 is to get rid of 'from .foo import bar' and higher levels # of relative importing if type(t) == ast.ImportFrom: if t.level > 0: if conf['ignore_relative_imports'] or not t.module: continue else: imports.append(t.module.split('.')[0]) return list(imports) def iterate_over_library(path_to_source_code): libs = set() for parent, folders, files in os.walk(path_to_source_code): for file in files: if file.endswith('.py'): print('.', end='') full_file_path = os.path.join(parent, file) with open(full_file_path, 'r') as f: code = f.read() libs.update(set(get_imported_libs(code))) if conf['ignore_builtin_modules']: if not conf['pyver']: pyver = '%s.%s' % (sys.version_info.major, sys.version_info.minor) std_libs = stdlib_list("3.4") # print(std_libs) libs = [lib for lib in libs if lib not in std_libs] return libs // ... rest of the code ...
26415375a5cf90623ddb187015ea167e7194cf8e
src/main/java/org/realityforge/ssf/SessionInfo.java
src/main/java/org/realityforge/ssf/SessionInfo.java
package org.realityforge.ssf; import javax.annotation.Nonnull; /** * A basic interface defining a session. */ public interface SessionInfo { /** * @return an opaque ID representing session. */ @Nonnull String getSessionID(); /** * @return the username for session if available. */ @Nonnull String getUsername(); /** * @return the time at which session was created. */ long getCreatedAt(); /** * @return the time at which session was last accessed. */ long getLastAccessedAt(); }
package org.realityforge.ssf; import javax.annotation.Nonnull; /** * A basic interface defining a session. */ public interface SessionInfo { /** * @return an opaque ID representing session. */ @Nonnull String getSessionID(); /** * @return the username for session if available. */ @Nonnull String getUsername(); /** * @return the time at which session was created. */ long getCreatedAt(); /** * @return the time at which session was last accessed. */ long getLastAccessedAt(); /** * Update the access time to now. */ void updateAccessTime(); }
Make updateAccessTime() part of the public interface for sessions
Make updateAccessTime() part of the public interface for sessions
Java
apache-2.0
realityforge/simple-session-filter,realityforge/simple-session-filter
java
## Code Before: package org.realityforge.ssf; import javax.annotation.Nonnull; /** * A basic interface defining a session. */ public interface SessionInfo { /** * @return an opaque ID representing session. */ @Nonnull String getSessionID(); /** * @return the username for session if available. */ @Nonnull String getUsername(); /** * @return the time at which session was created. */ long getCreatedAt(); /** * @return the time at which session was last accessed. */ long getLastAccessedAt(); } ## Instruction: Make updateAccessTime() part of the public interface for sessions ## Code After: package org.realityforge.ssf; import javax.annotation.Nonnull; /** * A basic interface defining a session. */ public interface SessionInfo { /** * @return an opaque ID representing session. */ @Nonnull String getSessionID(); /** * @return the username for session if available. */ @Nonnull String getUsername(); /** * @return the time at which session was created. */ long getCreatedAt(); /** * @return the time at which session was last accessed. */ long getLastAccessedAt(); /** * Update the access time to now. */ void updateAccessTime(); }
# ... existing code ... * @return the time at which session was last accessed. */ long getLastAccessedAt(); /** * Update the access time to now. */ void updateAccessTime(); } # ... rest of the code ...
7e8e8d6b2c033b7242913452ac895b252d815b75
cosmos/models/mobility/src/main/java/es/tid/cosmos/mobility/aggregatedmatrix/simple/MatrixSpreadVectorByPairMapper.java
cosmos/models/mobility/src/main/java/es/tid/cosmos/mobility/aggregatedmatrix/simple/MatrixSpreadVectorByPairMapper.java
package es.tid.cosmos.mobility.aggregatedmatrix.simple; import java.io.IOException; import com.twitter.elephantbird.mapreduce.io.ProtobufWritable; import org.apache.hadoop.mapreduce.Mapper; import es.tid.cosmos.mobility.data.TwoIntUtil; import es.tid.cosmos.mobility.data.generated.MobProtocol.ItinRange; import es.tid.cosmos.mobility.data.generated.MobProtocol.MobData; import es.tid.cosmos.mobility.data.generated.MobProtocol.TwoInt; /** * Input: <TwoInt, ItinTime> * Output: <TwoInt, ItinTime> * * @author dmicol */ public class MatrixSpreadVectorByPairMapper extends Mapper< ProtobufWritable<ItinRange>, ProtobufWritable<MobData>, ProtobufWritable<TwoInt>, ProtobufWritable<MobData>> { @Override protected void map(ProtobufWritable<ItinRange> key, ProtobufWritable<MobData> value, Context context) throws IOException, InterruptedException { key.setConverter(ItinRange.class); final ItinRange itrang = key.get(); ItinRange.Builder outItrang = ItinRange.newBuilder(itrang); outItrang.setNode(itrang.getPoiSrc() * itrang.getPoiTgt()); context.write(TwoIntUtil.createAndWrap(itrang.getPoiSrc(), itrang.getPoiTgt()), value); } }
package es.tid.cosmos.mobility.aggregatedmatrix.simple; import java.io.IOException; import com.twitter.elephantbird.mapreduce.io.ProtobufWritable; import org.apache.hadoop.mapreduce.Mapper; import es.tid.cosmos.mobility.data.TwoIntUtil; import es.tid.cosmos.mobility.data.generated.MobProtocol.ItinRange; import es.tid.cosmos.mobility.data.generated.MobProtocol.MobData; import es.tid.cosmos.mobility.data.generated.MobProtocol.TwoInt; /** * Input: <ItinRange, ClusterVector> * Output: <TwoInt, ClusterVector> * * @author dmicol */ public class MatrixSpreadVectorByPairMapper extends Mapper< ProtobufWritable<ItinRange>, ProtobufWritable<MobData>, ProtobufWritable<TwoInt>, ProtobufWritable<MobData>> { @Override protected void map(ProtobufWritable<ItinRange> key, ProtobufWritable<MobData> value, Context context) throws IOException, InterruptedException { key.setConverter(ItinRange.class); final ItinRange itrang = key.get(); ItinRange.Builder outItrang = ItinRange.newBuilder(itrang); outItrang.setNode(itrang.getPoiSrc() * itrang.getPoiTgt()); context.write(TwoIntUtil.createAndWrap(itrang.getPoiSrc(), itrang.getPoiTgt()), value); } }
Fix wrong input/output drata types.
Fix wrong input/output drata types.
Java
apache-2.0
telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform
java
## Code Before: package es.tid.cosmos.mobility.aggregatedmatrix.simple; import java.io.IOException; import com.twitter.elephantbird.mapreduce.io.ProtobufWritable; import org.apache.hadoop.mapreduce.Mapper; import es.tid.cosmos.mobility.data.TwoIntUtil; import es.tid.cosmos.mobility.data.generated.MobProtocol.ItinRange; import es.tid.cosmos.mobility.data.generated.MobProtocol.MobData; import es.tid.cosmos.mobility.data.generated.MobProtocol.TwoInt; /** * Input: <TwoInt, ItinTime> * Output: <TwoInt, ItinTime> * * @author dmicol */ public class MatrixSpreadVectorByPairMapper extends Mapper< ProtobufWritable<ItinRange>, ProtobufWritable<MobData>, ProtobufWritable<TwoInt>, ProtobufWritable<MobData>> { @Override protected void map(ProtobufWritable<ItinRange> key, ProtobufWritable<MobData> value, Context context) throws IOException, InterruptedException { key.setConverter(ItinRange.class); final ItinRange itrang = key.get(); ItinRange.Builder outItrang = ItinRange.newBuilder(itrang); outItrang.setNode(itrang.getPoiSrc() * itrang.getPoiTgt()); context.write(TwoIntUtil.createAndWrap(itrang.getPoiSrc(), itrang.getPoiTgt()), value); } } ## Instruction: Fix wrong input/output drata types. ## Code After: package es.tid.cosmos.mobility.aggregatedmatrix.simple; import java.io.IOException; import com.twitter.elephantbird.mapreduce.io.ProtobufWritable; import org.apache.hadoop.mapreduce.Mapper; import es.tid.cosmos.mobility.data.TwoIntUtil; import es.tid.cosmos.mobility.data.generated.MobProtocol.ItinRange; import es.tid.cosmos.mobility.data.generated.MobProtocol.MobData; import es.tid.cosmos.mobility.data.generated.MobProtocol.TwoInt; /** * Input: <ItinRange, ClusterVector> * Output: <TwoInt, ClusterVector> * * @author dmicol */ public class MatrixSpreadVectorByPairMapper extends Mapper< ProtobufWritable<ItinRange>, ProtobufWritable<MobData>, ProtobufWritable<TwoInt>, ProtobufWritable<MobData>> { @Override protected void map(ProtobufWritable<ItinRange> key, ProtobufWritable<MobData> value, Context context) throws IOException, InterruptedException { key.setConverter(ItinRange.class); final ItinRange itrang = key.get(); ItinRange.Builder outItrang = ItinRange.newBuilder(itrang); outItrang.setNode(itrang.getPoiSrc() * itrang.getPoiTgt()); context.write(TwoIntUtil.createAndWrap(itrang.getPoiSrc(), itrang.getPoiTgt()), value); } }
// ... existing code ... import es.tid.cosmos.mobility.data.generated.MobProtocol.TwoInt; /** * Input: <ItinRange, ClusterVector> * Output: <TwoInt, ClusterVector> * * @author dmicol */ // ... rest of the code ...
f317f946f9f17cbaf162b12c8770908abba5bbeb
linter.py
linter.py
"""This module exports the Cppcheck plugin class.""" from SublimeLinter.lint import Linter, util class Cppcheck(Linter): """Provides an interface to cppcheck.""" syntax = 'c++' cmd = ('cppcheck', '--template=gcc', '--inline-suppr', '--quiet', '*', '@') regex = r'^.+:(?P<line>\d+):\s+(?P<message>.+)' error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout tempfile_suffix = 'cpp' defaults = { '--std=,+': [], # example ['c99', 'c89'] '--enable=,': 'style', } inline_settings = 'std' inline_overrides = 'enable' comment_re = r'\s*/[/*]'
"""This module exports the Cppcheck plugin class.""" from SublimeLinter.lint import Linter, util class Cppcheck(Linter): """Provides an interface to cppcheck.""" syntax = 'c++' cmd = ('cppcheck', '--template=gcc', '--inline-suppr', '--quiet', '*', '@') regex = r'^.+:(?P<line>\d+):\s+((?P<error>error)|(?P<warning>warning|style|performance|portability|information)):\s+(?P<message>.+)' error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout tempfile_suffix = 'cpp' defaults = { '--std=,+': [], # example ['c99', 'c89'] '--enable=,': 'style', } inline_settings = 'std' inline_overrides = 'enable' comment_re = r'\s*/[/*]'
Change on the regex variable such that it distinguish warnings from errors.
Change on the regex variable such that it distinguish warnings from errors.
Python
mit
SublimeLinter/SublimeLinter-cppcheck,ftoulemon/SublimeLinter-cppcheck
python
## Code Before: """This module exports the Cppcheck plugin class.""" from SublimeLinter.lint import Linter, util class Cppcheck(Linter): """Provides an interface to cppcheck.""" syntax = 'c++' cmd = ('cppcheck', '--template=gcc', '--inline-suppr', '--quiet', '*', '@') regex = r'^.+:(?P<line>\d+):\s+(?P<message>.+)' error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout tempfile_suffix = 'cpp' defaults = { '--std=,+': [], # example ['c99', 'c89'] '--enable=,': 'style', } inline_settings = 'std' inline_overrides = 'enable' comment_re = r'\s*/[/*]' ## Instruction: Change on the regex variable such that it distinguish warnings from errors. ## Code After: """This module exports the Cppcheck plugin class.""" from SublimeLinter.lint import Linter, util class Cppcheck(Linter): """Provides an interface to cppcheck.""" syntax = 'c++' cmd = ('cppcheck', '--template=gcc', '--inline-suppr', '--quiet', '*', '@') regex = r'^.+:(?P<line>\d+):\s+((?P<error>error)|(?P<warning>warning|style|performance|portability|information)):\s+(?P<message>.+)' error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout tempfile_suffix = 'cpp' defaults = { '--std=,+': [], # example ['c99', 'c89'] '--enable=,': 'style', } inline_settings = 'std' inline_overrides = 'enable' comment_re = r'\s*/[/*]'
... syntax = 'c++' cmd = ('cppcheck', '--template=gcc', '--inline-suppr', '--quiet', '*', '@') regex = r'^.+:(?P<line>\d+):\s+((?P<error>error)|(?P<warning>warning|style|performance|portability|information)):\s+(?P<message>.+)' error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout tempfile_suffix = 'cpp' defaults = { ...
83dabc9fc1142e1575843d3a68c6241185543936
fabtastic/db/__init__.py
fabtastic/db/__init__.py
from django.conf import settings from fabtastic.db import util db_engine = util.get_db_setting('ENGINE') if 'postgresql_psycopg2' in db_engine: from fabtastic.db.postgres import * else: raise NotImplementedError("Fabtastic: DB engine '%s' is not supported" % db_engine)
from django.conf import settings from fabtastic.db import util db_engine = util.get_db_setting('ENGINE') if 'postgresql_psycopg2' in db_engine: from fabtastic.db.postgres import * else: print("Fabtastic WARNING: DB engine '%s' is not supported" % db_engine)
Make the warning for SQLite not being supported a print instead of an exception.
Make the warning for SQLite not being supported a print instead of an exception.
Python
bsd-3-clause
duointeractive/django-fabtastic
python
## Code Before: from django.conf import settings from fabtastic.db import util db_engine = util.get_db_setting('ENGINE') if 'postgresql_psycopg2' in db_engine: from fabtastic.db.postgres import * else: raise NotImplementedError("Fabtastic: DB engine '%s' is not supported" % db_engine) ## Instruction: Make the warning for SQLite not being supported a print instead of an exception. ## Code After: from django.conf import settings from fabtastic.db import util db_engine = util.get_db_setting('ENGINE') if 'postgresql_psycopg2' in db_engine: from fabtastic.db.postgres import * else: print("Fabtastic WARNING: DB engine '%s' is not supported" % db_engine)
// ... existing code ... if 'postgresql_psycopg2' in db_engine: from fabtastic.db.postgres import * else: print("Fabtastic WARNING: DB engine '%s' is not supported" % db_engine) // ... rest of the code ...
436342980610f009077bd5d01221f88b75e767c6
junit-jupiter-api/junit-jupiter-api.gradle.kts
junit-jupiter-api/junit-jupiter-api.gradle.kts
description = "JUnit Jupiter API" dependencies { api("org.opentest4j:opentest4j:${Versions.ota4j}") api(project(":junit-platform-commons")) compileOnly("org.jetbrains.kotlin:kotlin-stdlib") } tasks.jar { manifest { attributes( "Automatic-Module-Name" to "org.junit.jupiter.api" ) } }
description = "JUnit Jupiter API" dependencies { api("org.opentest4j:opentest4j:${Versions.ota4j}") api(project(":junit-platform-commons")) compileOnly("org.jetbrains.kotlin:kotlin-stdlib") runtimeOnly(project(":junit-jupiter-engine")) } tasks.jar { manifest { attributes( "Automatic-Module-Name" to "org.junit.jupiter.api" ) } }
Introduce runtime dependency from Jupiter API to its Engine
Introduce runtime dependency from Jupiter API to its Engine Prior to this commit users needed to declare a runtime dependency for the Jupiter Engine despite a compile time dependency to the Jupiter API was already in place: ``` testCompile('org.junit.jupiter:junit-jupiter-api:<version>') testRuntime('org.junit.jupiter:junit-jupiter-engine:<version>') ``` This commit introduces the runtime dependency to `junit-jupiter-engine` per default. This allows users to omit the explicit declaration of the runtime dependency: ``` testCompile('org.junit.jupiter:junit-jupiter-api:<version>') ``` This also works for Maven-based dependency resolution build tools. Addresses issue #1669
Kotlin
epl-1.0
junit-team/junit-lambda,sbrannen/junit-lambda
kotlin
## Code Before: description = "JUnit Jupiter API" dependencies { api("org.opentest4j:opentest4j:${Versions.ota4j}") api(project(":junit-platform-commons")) compileOnly("org.jetbrains.kotlin:kotlin-stdlib") } tasks.jar { manifest { attributes( "Automatic-Module-Name" to "org.junit.jupiter.api" ) } } ## Instruction: Introduce runtime dependency from Jupiter API to its Engine Prior to this commit users needed to declare a runtime dependency for the Jupiter Engine despite a compile time dependency to the Jupiter API was already in place: ``` testCompile('org.junit.jupiter:junit-jupiter-api:<version>') testRuntime('org.junit.jupiter:junit-jupiter-engine:<version>') ``` This commit introduces the runtime dependency to `junit-jupiter-engine` per default. This allows users to omit the explicit declaration of the runtime dependency: ``` testCompile('org.junit.jupiter:junit-jupiter-api:<version>') ``` This also works for Maven-based dependency resolution build tools. Addresses issue #1669 ## Code After: description = "JUnit Jupiter API" dependencies { api("org.opentest4j:opentest4j:${Versions.ota4j}") api(project(":junit-platform-commons")) compileOnly("org.jetbrains.kotlin:kotlin-stdlib") runtimeOnly(project(":junit-jupiter-engine")) } tasks.jar { manifest { attributes( "Automatic-Module-Name" to "org.junit.jupiter.api" ) } }
// ... existing code ... api("org.opentest4j:opentest4j:${Versions.ota4j}") api(project(":junit-platform-commons")) compileOnly("org.jetbrains.kotlin:kotlin-stdlib") runtimeOnly(project(":junit-jupiter-engine")) } tasks.jar { // ... rest of the code ...
237c7004130c08be3ea1a06d0e5ac76b1a153e5a
peer_testing.h
peer_testing.h
fake_read #else #define READ \ read #endif #endif
extern "C" { #endif ssize_t fake_read(int fd, void *buf, size_t count); #ifdef __cplusplus } #endif #define READ \ fake_read #else #define READ \ read #endif #endif
Add "extern C" stuff for clean compile of tests.
Add "extern C" stuff for clean compile of tests.
C
mit
mloy/cjet,mloy/cjet,gatzka/cjet,mloy/cjet,mloy/cjet,mloy/cjet,gatzka/cjet,gatzka/cjet,gatzka/cjet,gatzka/cjet
c
## Code Before: fake_read #else #define READ \ read #endif #endif ## Instruction: Add "extern C" stuff for clean compile of tests. ## Code After: extern "C" { #endif ssize_t fake_read(int fd, void *buf, size_t count); #ifdef __cplusplus } #endif #define READ \ fake_read #else #define READ \ read #endif #endif
# ... existing code ... extern "C" { #endif ssize_t fake_read(int fd, void *buf, size_t count); #ifdef __cplusplus } #endif #define READ \ fake_read #else #define READ \ read #endif # ... rest of the code ...
5ca96beb26dd2ab5285a57f5cade6f01160df368
joequery/blog/posts/code/notes-on-dynamic-programming-part-1/meta.py
joequery/blog/posts/code/notes-on-dynamic-programming-part-1/meta.py
title="Notes on dynamic programming - part 1" description=""" Part 1 of extensive notes discussing the fundamentals of dynamic programming. Examples in these notes include the Fibonacci sequence and Warshall's algorithm. Pseudocode and Python implementations of the algorithms are provided. """ time="2012-12-10 Mon 02:28 AM" # related=[("Some article", "its/url")]
title="Notes on dynamic programming - part 1" description=""" Part 1 of extensive notes discussing the fundamentals of dynamic programming. Examples in these notes include the Fibonacci sequence, the Binomial Formula, and Warshall's algorithm. Python implementations of the algorithms are provided. """ time="2012-12-10 Mon 02:48 AM" # related=[("Some article", "its/url")]
Update description and timestamp for dynamic programming part 1
Update description and timestamp for dynamic programming part 1
Python
mit
joequery/joequery.me,joequery/joequery.me,joequery/joequery.me,joequery/joequery.me
python
## Code Before: title="Notes on dynamic programming - part 1" description=""" Part 1 of extensive notes discussing the fundamentals of dynamic programming. Examples in these notes include the Fibonacci sequence and Warshall's algorithm. Pseudocode and Python implementations of the algorithms are provided. """ time="2012-12-10 Mon 02:28 AM" # related=[("Some article", "its/url")] ## Instruction: Update description and timestamp for dynamic programming part 1 ## Code After: title="Notes on dynamic programming - part 1" description=""" Part 1 of extensive notes discussing the fundamentals of dynamic programming. Examples in these notes include the Fibonacci sequence, the Binomial Formula, and Warshall's algorithm. Python implementations of the algorithms are provided. """ time="2012-12-10 Mon 02:48 AM" # related=[("Some article", "its/url")]
// ... existing code ... title="Notes on dynamic programming - part 1" description=""" Part 1 of extensive notes discussing the fundamentals of dynamic programming. Examples in these notes include the Fibonacci sequence, the Binomial Formula, and Warshall's algorithm. Python implementations of the algorithms are provided. """ time="2012-12-10 Mon 02:48 AM" # related=[("Some article", "its/url")] // ... rest of the code ...
29e6e77b03569d39e484b47efd3b8230f30ee195
eduid_signup/db.py
eduid_signup/db.py
import pymongo from eduid_signup.compat import urlparse DEFAULT_MONGODB_HOST = 'localhost' DEFAULT_MONGODB_PORT = 27017 DEFAULT_MONGODB_NAME = 'eduid' DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST, DEFAULT_MONGODB_PORT, DEFAULT_MONGODB_NAME) class MongoDB(object): """Simple wrapper to get pymongo real objects from the settings uri""" def __init__(self, db_uri=DEFAULT_MONGODB_URI, connection_factory=pymongo.Connection): self.db_uri = urlparse.urlparse(db_uri) self.connection = connection_factory( host=self.db_uri.hostname or DEFAULT_MONGODB_HOST, port=self.db_uri.port or DEFAULT_MONGODB_PORT, tz_aware=True) if self.db_uri.path: self.database_name = self.db_uri.path[1:] else: self.database_name = DEFAULT_MONGODB_NAME def get_connection(self): return self.connection def get_database(self): database = self.connection[self.database_name] if self.db_uri.username and self.db_uri.password: database.authenticate(self.db_uri.username, self.db_uri.password) return database def get_db(request): return request.registry.settings['mongodb'].get_database()
import pymongo DEFAULT_MONGODB_HOST = 'localhost' DEFAULT_MONGODB_PORT = 27017 DEFAULT_MONGODB_NAME = 'eduid' DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST, DEFAULT_MONGODB_PORT, DEFAULT_MONGODB_NAME) class MongoDB(object): """Simple wrapper to get pymongo real objects from the settings uri""" def __init__(self, db_uri=DEFAULT_MONGODB_URI, connection_factory=pymongo.MongoClient): self.db_uri = db_uri self.connection = connection_factory( host=self.db_uri, tz_aware=True) if self.db_uri.path: self.database_name = self.db_uri.path[1:] else: self.database_name = DEFAULT_MONGODB_NAME def get_connection(self): return self.connection def get_database(self): database = self.connection[self.database_name] if self.db_uri.username and self.db_uri.password: database.authenticate(self.db_uri.username, self.db_uri.password) return database def get_db(request): return request.registry.settings['mongodb'].get_database()
Allow Mongo connections to Mongo Replicaset Cluster
Allow Mongo connections to Mongo Replicaset Cluster
Python
bsd-3-clause
SUNET/eduid-signup,SUNET/eduid-signup,SUNET/eduid-signup
python
## Code Before: import pymongo from eduid_signup.compat import urlparse DEFAULT_MONGODB_HOST = 'localhost' DEFAULT_MONGODB_PORT = 27017 DEFAULT_MONGODB_NAME = 'eduid' DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST, DEFAULT_MONGODB_PORT, DEFAULT_MONGODB_NAME) class MongoDB(object): """Simple wrapper to get pymongo real objects from the settings uri""" def __init__(self, db_uri=DEFAULT_MONGODB_URI, connection_factory=pymongo.Connection): self.db_uri = urlparse.urlparse(db_uri) self.connection = connection_factory( host=self.db_uri.hostname or DEFAULT_MONGODB_HOST, port=self.db_uri.port or DEFAULT_MONGODB_PORT, tz_aware=True) if self.db_uri.path: self.database_name = self.db_uri.path[1:] else: self.database_name = DEFAULT_MONGODB_NAME def get_connection(self): return self.connection def get_database(self): database = self.connection[self.database_name] if self.db_uri.username and self.db_uri.password: database.authenticate(self.db_uri.username, self.db_uri.password) return database def get_db(request): return request.registry.settings['mongodb'].get_database() ## Instruction: Allow Mongo connections to Mongo Replicaset Cluster ## Code After: import pymongo DEFAULT_MONGODB_HOST = 'localhost' DEFAULT_MONGODB_PORT = 27017 DEFAULT_MONGODB_NAME = 'eduid' DEFAULT_MONGODB_URI = 'mongodb://%s:%d/%s' % (DEFAULT_MONGODB_HOST, DEFAULT_MONGODB_PORT, DEFAULT_MONGODB_NAME) class MongoDB(object): """Simple wrapper to get pymongo real objects from the settings uri""" def __init__(self, db_uri=DEFAULT_MONGODB_URI, connection_factory=pymongo.MongoClient): self.db_uri = db_uri self.connection = connection_factory( host=self.db_uri, tz_aware=True) if self.db_uri.path: self.database_name = self.db_uri.path[1:] else: self.database_name = DEFAULT_MONGODB_NAME def get_connection(self): return self.connection def get_database(self): database = self.connection[self.database_name] if self.db_uri.username and self.db_uri.password: database.authenticate(self.db_uri.username, self.db_uri.password) return database def get_db(request): return request.registry.settings['mongodb'].get_database()
# ... existing code ... import pymongo DEFAULT_MONGODB_HOST = 'localhost' DEFAULT_MONGODB_PORT = 27017 # ... modified code ... """Simple wrapper to get pymongo real objects from the settings uri""" def __init__(self, db_uri=DEFAULT_MONGODB_URI, connection_factory=pymongo.MongoClient): self.db_uri = db_uri self.connection = connection_factory( host=self.db_uri, tz_aware=True) if self.db_uri.path: # ... rest of the code ...
57560385ef05ba6a2234e43795a037a487f26cfd
djaml/utils.py
djaml/utils.py
import imp from os import listdir from os.path import dirname, splitext from django.template import loaders MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()]) def get_django_template_loaders(): return [(loader.__name__.rsplit('.',1)[1], loader) for loader in get_submodules(loaders) if hasattr(loader, 'load_template_source')] def get_submodules(package): submodules = ("%s.%s" % (package.__name__, module) for module in package_contents(package)) return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]]) for module in submodules] def package_contents(package): package_path = dirname(loaders.__file__) contents = set([splitext(module)[0] for module in listdir(package_path) if module.endswith(MODULE_EXTENSIONS)]) return contents
import imp from os import listdir from os.path import dirname, splitext from django.template import loaders MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()]) def get_django_template_loaders(): return [(loader.__name__.rsplit('.',1)[1], loader) for loader in get_submodules(loaders) if hasattr(loader, 'Loader')] def get_submodules(package): submodules = ("%s.%s" % (package.__name__, module) for module in package_contents(package)) return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]]) for module in submodules] def package_contents(package): package_path = dirname(loaders.__file__) contents = set([splitext(module)[0] for module in listdir(package_path) if module.endswith(MODULE_EXTENSIONS)]) return contents
Fix submodule attribute check for Django 1.4 compatibility
Fix submodule attribute check for Django 1.4 compatibility
Python
mit
chartjes/djaml
python
## Code Before: import imp from os import listdir from os.path import dirname, splitext from django.template import loaders MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()]) def get_django_template_loaders(): return [(loader.__name__.rsplit('.',1)[1], loader) for loader in get_submodules(loaders) if hasattr(loader, 'load_template_source')] def get_submodules(package): submodules = ("%s.%s" % (package.__name__, module) for module in package_contents(package)) return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]]) for module in submodules] def package_contents(package): package_path = dirname(loaders.__file__) contents = set([splitext(module)[0] for module in listdir(package_path) if module.endswith(MODULE_EXTENSIONS)]) return contents ## Instruction: Fix submodule attribute check for Django 1.4 compatibility ## Code After: import imp from os import listdir from os.path import dirname, splitext from django.template import loaders MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()]) def get_django_template_loaders(): return [(loader.__name__.rsplit('.',1)[1], loader) for loader in get_submodules(loaders) if hasattr(loader, 'Loader')] def get_submodules(package): submodules = ("%s.%s" % (package.__name__, module) for module in package_contents(package)) return [__import__(module, {}, {}, [module.rsplit(".", 1)[-1]]) for module in submodules] def package_contents(package): package_path = dirname(loaders.__file__) contents = set([splitext(module)[0] for module in listdir(package_path) if module.endswith(MODULE_EXTENSIONS)]) return contents
... def get_django_template_loaders(): return [(loader.__name__.rsplit('.',1)[1], loader) for loader in get_submodules(loaders) if hasattr(loader, 'Loader')] def get_submodules(package): submodules = ("%s.%s" % (package.__name__, module) ...
bd8fdf1dccc3660be3b8e020a637f94d21dc2b3a
gaphas/tests/test_state.py
gaphas/tests/test_state.py
from builtins import object import unittest from gaphas.state import reversible_pair, observed, _reverse class SList(object): def __init__(self): self.l = list() def add(self, node, before=None): if before: self.l.insert(self.l.index(before), node) else: self.l.append(node) add = observed(add) @observed def remove(self, node): self.l.remove(self.l.index(node)) class StateTestCase(unittest.TestCase): def test_adding_pair(self): """Test adding reversible pair """ reversible_pair(SList.add, SList.remove, \ bind1={'before': lambda self, node: self.l[self.l.index(node)+1] }) self.assertTrue(SList.add.__func__ in _reverse) self.assertTrue(SList.remove.__func__ in _reverse)
from builtins import object import unittest from gaphas.state import reversible_pair, observed, _reverse class SList(object): def __init__(self): self.l = list() def add(self, node, before=None): if before: self.l.insert(self.l.index(before), node) else: self.l.append(node) add = observed(add) @observed def remove(self, node): self.l.remove(self.l.index(node)) class StateTestCase(unittest.TestCase): def test_adding_pair(self): """Test adding reversible pair """ reversible_pair(SList.add, SList.remove, \ bind1={'before': lambda self, node: self.l[self.l.index(node)+1] }) self.assertTrue(SList.add in _reverse) self.assertTrue(SList.remove in _reverse)
Fix function object has no attribute __func__
Fix function object has no attribute __func__ Signed-off-by: Dan Yeaw <[email protected]>
Python
lgpl-2.1
amolenaar/gaphas
python
## Code Before: from builtins import object import unittest from gaphas.state import reversible_pair, observed, _reverse class SList(object): def __init__(self): self.l = list() def add(self, node, before=None): if before: self.l.insert(self.l.index(before), node) else: self.l.append(node) add = observed(add) @observed def remove(self, node): self.l.remove(self.l.index(node)) class StateTestCase(unittest.TestCase): def test_adding_pair(self): """Test adding reversible pair """ reversible_pair(SList.add, SList.remove, \ bind1={'before': lambda self, node: self.l[self.l.index(node)+1] }) self.assertTrue(SList.add.__func__ in _reverse) self.assertTrue(SList.remove.__func__ in _reverse) ## Instruction: Fix function object has no attribute __func__ Signed-off-by: Dan Yeaw <[email protected]> ## Code After: from builtins import object import unittest from gaphas.state import reversible_pair, observed, _reverse class SList(object): def __init__(self): self.l = list() def add(self, node, before=None): if before: self.l.insert(self.l.index(before), node) else: self.l.append(node) add = observed(add) @observed def remove(self, node): self.l.remove(self.l.index(node)) class StateTestCase(unittest.TestCase): def test_adding_pair(self): """Test adding reversible pair """ reversible_pair(SList.add, SList.remove, \ bind1={'before': lambda self, node: self.l[self.l.index(node)+1] }) self.assertTrue(SList.add in _reverse) self.assertTrue(SList.remove in _reverse)
# ... existing code ... reversible_pair(SList.add, SList.remove, \ bind1={'before': lambda self, node: self.l[self.l.index(node)+1] }) self.assertTrue(SList.add in _reverse) self.assertTrue(SList.remove in _reverse) # ... rest of the code ...
4193a49144227f8ff2694d602246d692ee9946bf
oauthenticator/__init__.py
oauthenticator/__init__.py
from .oauth2 import * from .github import * from .bitbucket import * from .generic import * from .google import * from .okpy import * from ._version import __version__, version_info
from .oauth2 import * from .github import * from .bitbucket import * from .google import * from .okpy import * from ._version import __version__, version_info
Delete extra import. Prepare for PR.
Delete extra import. Prepare for PR.
Python
bsd-3-clause
NickolausDS/oauthenticator,enolfc/oauthenticator,yuvipanda/mwoauthenticator,jupyter/oauthenticator,jupyter/oauthenticator,minrk/oauthenticator,yuvipanda/mwoauthenticator,jupyterhub/oauthenticator,maltevogl/oauthenticator
python
## Code Before: from .oauth2 import * from .github import * from .bitbucket import * from .generic import * from .google import * from .okpy import * from ._version import __version__, version_info ## Instruction: Delete extra import. Prepare for PR. ## Code After: from .oauth2 import * from .github import * from .bitbucket import * from .google import * from .okpy import * from ._version import __version__, version_info
# ... existing code ... from .oauth2 import * from .github import * from .bitbucket import * from .google import * from .okpy import * # ... rest of the code ...
84a2f2f019216ec96121159365ef4ca66f5d4e25
corehq/util/couch.py
corehq/util/couch.py
from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if (unwrapped.get('domain', domain) != domain or domain not in unwrapped.get('domains', [domain]) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404()
from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if ((unwrapped.get('domain', None) != domain and domain not in unwrapped.get('domains', [])) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404()
Handle doc without domain or domains
Handle doc without domain or domains
Python
bsd-3-clause
qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
python
## Code Before: from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if (unwrapped.get('domain', domain) != domain or domain not in unwrapped.get('domains', [domain]) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404() ## Instruction: Handle doc without domain or domains ## Code After: from couchdbkit import ResourceNotFound from django.http import Http404 from jsonobject.exceptions import WrappingAttributeError def get_document_or_404(cls, domain, doc_id, additional_doc_types=None): """ Gets a document and enforces its domain and doc type. Raises Http404 if the doc isn't found or domain/doc_type don't match. """ allowed_doc_types = (additional_doc_types or []) + [cls.__name__] try: unwrapped = cls.get_db().get(doc_id) except ResourceNotFound: raise Http404() if ((unwrapped.get('domain', None) != domain and domain not in unwrapped.get('domains', [])) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() try: return cls.wrap(unwrapped) except WrappingAttributeError: raise Http404()
// ... existing code ... except ResourceNotFound: raise Http404() if ((unwrapped.get('domain', None) != domain and domain not in unwrapped.get('domains', [])) or unwrapped['doc_type'] not in allowed_doc_types): raise Http404() // ... rest of the code ...
bdcc7bdc9daace561f3961122b1d74cd69f1958a
src/CommonFrame.java
src/CommonFrame.java
/** * Part of Employ */ import java.awt.*; import javax.swing.*; public abstract class CommonFrame extends JFrame { JPanel panelHeading; JLabel labelHeading; // define common settings for all frame public CommonFrame(String heading) { super("Employ - " + heading); setSize(400, 200); setResizable(false); setLocationRelativeTo(null); setLayout(new FlowLayout()); panelHeading = new JPanel(); labelHeading = new JLabel(heading); add(panelHeading); add(labelHeading); setDefaultCloseOperation(EXIT_ON_CLOSE); } }
/** * Part of Employ */ import javax.swing.*; public abstract class CommonFrame extends JFrame { JPanel panelHeading = new JPanel(); // define common settings for all frame public CommonFrame(String heading) { super("Employ - " + heading); setSize(400, 200); setResizable(false); setLocationRelativeTo(null); setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); JLabel labelHeading = new JLabel(heading); panelHeading.add(labelHeading); add(panelHeading); setDefaultCloseOperation(EXIT_ON_CLOSE); } }
Use BoxLayout for better component arrangement
Use BoxLayout for better component arrangement Refer CommonFrame's content pane as the layout target container with Y axis. Now it's a basic responsive Java design if resizeable.
Java
mit
mhaidarh/employ
java
## Code Before: /** * Part of Employ */ import java.awt.*; import javax.swing.*; public abstract class CommonFrame extends JFrame { JPanel panelHeading; JLabel labelHeading; // define common settings for all frame public CommonFrame(String heading) { super("Employ - " + heading); setSize(400, 200); setResizable(false); setLocationRelativeTo(null); setLayout(new FlowLayout()); panelHeading = new JPanel(); labelHeading = new JLabel(heading); add(panelHeading); add(labelHeading); setDefaultCloseOperation(EXIT_ON_CLOSE); } } ## Instruction: Use BoxLayout for better component arrangement Refer CommonFrame's content pane as the layout target container with Y axis. Now it's a basic responsive Java design if resizeable. ## Code After: /** * Part of Employ */ import javax.swing.*; public abstract class CommonFrame extends JFrame { JPanel panelHeading = new JPanel(); // define common settings for all frame public CommonFrame(String heading) { super("Employ - " + heading); setSize(400, 200); setResizable(false); setLocationRelativeTo(null); setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); JLabel labelHeading = new JLabel(heading); panelHeading.add(labelHeading); add(panelHeading); setDefaultCloseOperation(EXIT_ON_CLOSE); } }
... * Part of Employ */ import javax.swing.*; public abstract class CommonFrame extends JFrame { JPanel panelHeading = new JPanel(); // define common settings for all frame public CommonFrame(String heading) { ... setSize(400, 200); setResizable(false); setLocationRelativeTo(null); setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); JLabel labelHeading = new JLabel(heading); panelHeading.add(labelHeading); add(panelHeading); setDefaultCloseOperation(EXIT_ON_CLOSE); } ...
edc88421bec2798d82faeece2df5229888d97db9
contrib/performance/graph.py
contrib/performance/graph.py
import sys, pickle from matplotlib import pyplot import numpy from compare import select def main(): fig = pyplot.figure() ax = fig.add_subplot(111) data = [] for fname in sys.argv[1:]: stats, samples = select( pickle.load(file(fname)), 'vfreebusy', 1, 'urlopen time') data.append(samples) if data: assert len(samples) == len(data[0]) bars = [] color = iter('rgbcmy').next w = 1.0 / len(data) xs = numpy.arange(len(data[0])) for i, s in enumerate(data): bars.append(ax.bar(xs + i * w, s, width=w, color=color())[0]) ax.set_xlabel('sample #') ax.set_ylabel('seconds') ax.legend(bars, sys.argv[1:]) pyplot.show()
import sys, pickle from matplotlib import pyplot import numpy from compare import select def main(): fig = pyplot.figure() ax = fig.add_subplot(111) data = [] for fname in sys.argv[1:]: fname, bench, param, stat = fname.split(',') stats, samples = select( pickle.load(file(fname)), bench, param, stat) data.append(samples) if data: assert len(samples) == len(data[0]) bars = [] color = iter('rgbcmy').next w = 1.0 / len(data) xs = numpy.arange(len(data[0])) for i, s in enumerate(data): bars.append(ax.bar(xs + i * w, s, width=w, color=color())[0]) ax.set_xlabel('sample #') ax.set_ylabel('seconds') ax.legend(bars, sys.argv[1:]) pyplot.show()
Make the bench/param/stat a commandline parameter
Make the bench/param/stat a commandline parameter git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6150 e27351fd-9f3e-4f54-a53b-843176b1656c
Python
apache-2.0
trevor/calendarserver,trevor/calendarserver,trevor/calendarserver
python
## Code Before: import sys, pickle from matplotlib import pyplot import numpy from compare import select def main(): fig = pyplot.figure() ax = fig.add_subplot(111) data = [] for fname in sys.argv[1:]: stats, samples = select( pickle.load(file(fname)), 'vfreebusy', 1, 'urlopen time') data.append(samples) if data: assert len(samples) == len(data[0]) bars = [] color = iter('rgbcmy').next w = 1.0 / len(data) xs = numpy.arange(len(data[0])) for i, s in enumerate(data): bars.append(ax.bar(xs + i * w, s, width=w, color=color())[0]) ax.set_xlabel('sample #') ax.set_ylabel('seconds') ax.legend(bars, sys.argv[1:]) pyplot.show() ## Instruction: Make the bench/param/stat a commandline parameter git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6150 e27351fd-9f3e-4f54-a53b-843176b1656c ## Code After: import sys, pickle from matplotlib import pyplot import numpy from compare import select def main(): fig = pyplot.figure() ax = fig.add_subplot(111) data = [] for fname in sys.argv[1:]: fname, bench, param, stat = fname.split(',') stats, samples = select( pickle.load(file(fname)), bench, param, stat) data.append(samples) if data: assert len(samples) == len(data[0]) bars = [] color = iter('rgbcmy').next w = 1.0 / len(data) xs = numpy.arange(len(data[0])) for i, s in enumerate(data): bars.append(ax.bar(xs + i * w, s, width=w, color=color())[0]) ax.set_xlabel('sample #') ax.set_ylabel('seconds') ax.legend(bars, sys.argv[1:]) pyplot.show()
# ... existing code ... data = [] for fname in sys.argv[1:]: fname, bench, param, stat = fname.split(',') stats, samples = select( pickle.load(file(fname)), bench, param, stat) data.append(samples) if data: assert len(samples) == len(data[0]) # ... rest of the code ...
679f20fc8747020f08f1e18a47772b18d886d29f
circuit/_twisted.py
circuit/_twisted.py
from circuit.breaker import CircuitBreaker, CircuitBreakerSet try: from twisted.internet import defer except ImportError: pass class TwistedCircuitBreaker(CircuitBreaker): """Circuit breaker that know that L{defer.inlineCallbacks} use exceptions in its internal workings. """ def __exit__(self, exc_type, exc_val, tb): print "EXIT" if exc_type is defer._DefGen_Return: print "GOT IT" exc_type, exc_val, tb = None, None, None return CircuitBreaker.__exit__(self, exc_type, exc_val, tb) class TwistedCircuitBreakerSet(CircuitBreakerSet): """Circuit breaker that supports twisted.""" def __init__(self, reactor, logger, **kwargs): kwargs.update({'factory': TwistedCircuitBreaker}) CircuitBreakerSet.__init__(self, reactor.seconds, logger, **kwargs)
from circuit.breaker import CircuitBreaker, CircuitBreakerSet try: from twisted.internet import defer except ImportError: pass class TwistedCircuitBreaker(CircuitBreaker): """Circuit breaker that know that L{defer.inlineCallbacks} use exceptions in its internal workings. """ def __exit__(self, exc_type, exc_val, tb): if exc_type is defer._DefGen_Return: exc_type, exc_val, tb = None, None, None return CircuitBreaker.__exit__(self, exc_type, exc_val, tb) class TwistedCircuitBreakerSet(CircuitBreakerSet): """Circuit breaker that supports twisted.""" def __init__(self, reactor, logger, **kwargs): kwargs.update({'factory': TwistedCircuitBreaker}) CircuitBreakerSet.__init__(self, reactor.seconds, logger, **kwargs)
Remove print statements from TwistedCircuitBreaker
Remove print statements from TwistedCircuitBreaker
Python
apache-2.0
edgeware/python-circuit
python
## Code Before: from circuit.breaker import CircuitBreaker, CircuitBreakerSet try: from twisted.internet import defer except ImportError: pass class TwistedCircuitBreaker(CircuitBreaker): """Circuit breaker that know that L{defer.inlineCallbacks} use exceptions in its internal workings. """ def __exit__(self, exc_type, exc_val, tb): print "EXIT" if exc_type is defer._DefGen_Return: print "GOT IT" exc_type, exc_val, tb = None, None, None return CircuitBreaker.__exit__(self, exc_type, exc_val, tb) class TwistedCircuitBreakerSet(CircuitBreakerSet): """Circuit breaker that supports twisted.""" def __init__(self, reactor, logger, **kwargs): kwargs.update({'factory': TwistedCircuitBreaker}) CircuitBreakerSet.__init__(self, reactor.seconds, logger, **kwargs) ## Instruction: Remove print statements from TwistedCircuitBreaker ## Code After: from circuit.breaker import CircuitBreaker, CircuitBreakerSet try: from twisted.internet import defer except ImportError: pass class TwistedCircuitBreaker(CircuitBreaker): """Circuit breaker that know that L{defer.inlineCallbacks} use exceptions in its internal workings. """ def __exit__(self, exc_type, exc_val, tb): if exc_type is defer._DefGen_Return: exc_type, exc_val, tb = None, None, None return CircuitBreaker.__exit__(self, exc_type, exc_val, tb) class TwistedCircuitBreakerSet(CircuitBreakerSet): """Circuit breaker that supports twisted.""" def __init__(self, reactor, logger, **kwargs): kwargs.update({'factory': TwistedCircuitBreaker}) CircuitBreakerSet.__init__(self, reactor.seconds, logger, **kwargs)
// ... existing code ... """ def __exit__(self, exc_type, exc_val, tb): if exc_type is defer._DefGen_Return: exc_type, exc_val, tb = None, None, None return CircuitBreaker.__exit__(self, exc_type, exc_val, tb) // ... rest of the code ...
e624f510a79aaa2b7264b55ce0d59c80a0321ee6
clients/mobile-lib/src/main/java/org/openecard/mobile/activation/EacControllerFactory.java
clients/mobile-lib/src/main/java/org/openecard/mobile/activation/EacControllerFactory.java
/**************************************************************************** * Copyright (C) 2019 ecsec GmbH. * All rights reserved. * Contact: ecsec GmbH ([email protected]) * * This file is part of the Open eCard App. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License version 3.0 as published by the Free Software Foundation * and appearing in the file LICENSE.GPL included in the packaging of * this file. Please review the following information to ensure the * GNU General Public License version 3.0 requirements will be met: * http://www.gnu.org/copyleft/gpl.html. * * Other Usage * Alternatively, this file may be used in accordance with the terms * and conditions contained in a signed written agreement between * you and ecsec GmbH. * ***************************************************************************/ package org.openecard.mobile.activation; import java.net.URL; import java.util.Set; import org.openecard.robovm.annotations.FrameworkInterface; /** * * @author Neil Crossley */ @FrameworkInterface public interface EacControllerFactory { ActivationController create(URL url, Set<String> supportedCard, ControllerCallback activation, EacInteraction interaction); void destroy(ActivationController controller); }
/**************************************************************************** * Copyright (C) 2019 ecsec GmbH. * All rights reserved. * Contact: ecsec GmbH ([email protected]) * * This file is part of the Open eCard App. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License version 3.0 as published by the Free Software Foundation * and appearing in the file LICENSE.GPL included in the packaging of * this file. Please review the following information to ensure the * GNU General Public License version 3.0 requirements will be met: * http://www.gnu.org/copyleft/gpl.html. * * Other Usage * Alternatively, this file may be used in accordance with the terms * and conditions contained in a signed written agreement between * you and ecsec GmbH. * ***************************************************************************/ package org.openecard.mobile.activation; import java.util.Set; import org.openecard.robovm.annotations.FrameworkInterface; /** * * @author Neil Crossley */ @FrameworkInterface public interface EacControllerFactory { ActivationController create(String url, Set<String> supportedCard, ControllerCallback activation, EacInteraction interaction); void destroy(ActivationController controller); }
Make URL a string because of iOS build problems.
Make URL a string because of iOS build problems.
Java
apache-2.0
ecsec/open-ecard,ecsec/open-ecard,ecsec/open-ecard
java
## Code Before: /**************************************************************************** * Copyright (C) 2019 ecsec GmbH. * All rights reserved. * Contact: ecsec GmbH ([email protected]) * * This file is part of the Open eCard App. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License version 3.0 as published by the Free Software Foundation * and appearing in the file LICENSE.GPL included in the packaging of * this file. Please review the following information to ensure the * GNU General Public License version 3.0 requirements will be met: * http://www.gnu.org/copyleft/gpl.html. * * Other Usage * Alternatively, this file may be used in accordance with the terms * and conditions contained in a signed written agreement between * you and ecsec GmbH. * ***************************************************************************/ package org.openecard.mobile.activation; import java.net.URL; import java.util.Set; import org.openecard.robovm.annotations.FrameworkInterface; /** * * @author Neil Crossley */ @FrameworkInterface public interface EacControllerFactory { ActivationController create(URL url, Set<String> supportedCard, ControllerCallback activation, EacInteraction interaction); void destroy(ActivationController controller); } ## Instruction: Make URL a string because of iOS build problems. ## Code After: /**************************************************************************** * Copyright (C) 2019 ecsec GmbH. * All rights reserved. * Contact: ecsec GmbH ([email protected]) * * This file is part of the Open eCard App. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License version 3.0 as published by the Free Software Foundation * and appearing in the file LICENSE.GPL included in the packaging of * this file. Please review the following information to ensure the * GNU General Public License version 3.0 requirements will be met: * http://www.gnu.org/copyleft/gpl.html. * * Other Usage * Alternatively, this file may be used in accordance with the terms * and conditions contained in a signed written agreement between * you and ecsec GmbH. * ***************************************************************************/ package org.openecard.mobile.activation; import java.util.Set; import org.openecard.robovm.annotations.FrameworkInterface; /** * * @author Neil Crossley */ @FrameworkInterface public interface EacControllerFactory { ActivationController create(String url, Set<String> supportedCard, ControllerCallback activation, EacInteraction interaction); void destroy(ActivationController controller); }
... package org.openecard.mobile.activation; import java.util.Set; import org.openecard.robovm.annotations.FrameworkInterface; ... @FrameworkInterface public interface EacControllerFactory { ActivationController create(String url, Set<String> supportedCard, ControllerCallback activation, EacInteraction interaction); void destroy(ActivationController controller); } ...
bb575cfdf4a6781c878a12f80987fb3e62fe56d4
chandl/model/posts.py
chandl/model/posts.py
from __future__ import unicode_literals class Posts(list): """ Represents a list of posts in a thread. """ def __init__(self, *args): """ Initialise a new posts list. :param args: The list of posts. """ super(Posts, self).__init__(*args) def filter(self, predicate): """ Take a subset of this list of posts. :param predicate: The predicate to use to choose which posts make the cut. :return: The filtered posts. """ return Posts(filter(predicate, self)) def map(self, transformation): """ Applies a transformation function to each post, returning a list of this function's returned values. :param transformation: The transformation function. :return: The transformed list of posts. """ return map(transformation, self) def foreach(self, function): """ Call a function for each post. :param function: A function taking a post argument. Return values are ignored. """ for post in self: function(post)
from __future__ import unicode_literals class Posts(list): """ Represents a list of posts in a thread. """ def __init__(self, *args): """ Initialise a new posts list. :param args: The list of posts. """ super(Posts, self).__init__(*args) def filter(self, predicate): """ Take a subset of this list of posts. :param predicate: The predicate to use to choose which posts make the cut. :return: The filtered posts. """ return Posts([post for post in self if predicate(post)]) def map(self, transform): """ Applies a transformation function to each post, returning a list of this function's returned values. :param transform: The transformation function. :return: The transformed list of posts. """ return [transform(post) for post in self] def foreach(self, function): """ Call a function for each post. :param function: A function taking a post argument. Return values are ignored. """ for post in self: function(post)
Make post filtering and mapping more pythonic
Make post filtering and mapping more pythonic
Python
mit
gebn/chandl,gebn/chandl
python
## Code Before: from __future__ import unicode_literals class Posts(list): """ Represents a list of posts in a thread. """ def __init__(self, *args): """ Initialise a new posts list. :param args: The list of posts. """ super(Posts, self).__init__(*args) def filter(self, predicate): """ Take a subset of this list of posts. :param predicate: The predicate to use to choose which posts make the cut. :return: The filtered posts. """ return Posts(filter(predicate, self)) def map(self, transformation): """ Applies a transformation function to each post, returning a list of this function's returned values. :param transformation: The transformation function. :return: The transformed list of posts. """ return map(transformation, self) def foreach(self, function): """ Call a function for each post. :param function: A function taking a post argument. Return values are ignored. """ for post in self: function(post) ## Instruction: Make post filtering and mapping more pythonic ## Code After: from __future__ import unicode_literals class Posts(list): """ Represents a list of posts in a thread. """ def __init__(self, *args): """ Initialise a new posts list. :param args: The list of posts. """ super(Posts, self).__init__(*args) def filter(self, predicate): """ Take a subset of this list of posts. :param predicate: The predicate to use to choose which posts make the cut. :return: The filtered posts. """ return Posts([post for post in self if predicate(post)]) def map(self, transform): """ Applies a transformation function to each post, returning a list of this function's returned values. :param transform: The transformation function. :return: The transformed list of posts. """ return [transform(post) for post in self] def foreach(self, function): """ Call a function for each post. :param function: A function taking a post argument. Return values are ignored. """ for post in self: function(post)
// ... existing code ... :return: The filtered posts. """ return Posts([post for post in self if predicate(post)]) def map(self, transform): """ Applies a transformation function to each post, returning a list of this function's returned values. :param transform: The transformation function. :return: The transformed list of posts. """ return [transform(post) for post in self] def foreach(self, function): """ // ... rest of the code ...
ceac9c401f80a279e7291e7ba2a9e06757d4dd1d
buildtools/wrapper/cmake.py
buildtools/wrapper/cmake.py
import os from buildtools.bt_logging import log from buildtools.os_utils import cmd, ENV class CMake(object): def __init__(self): self.flags = {} self.generator = None def setFlag(self, key, val): log.info('CMake: {} = {}'.format(key, val)) self.flags[key] = val def build(self, CMAKE, dir='.', env=None, target=None, moreflags=[]): moreflags += ['--build'] if target is not None: moreflags += ['--target',target] self.run(CMAKE,dir,env,moreflags) def run(self, CMAKE, env=None, dir='.', moreflags=[]): if env is None: env = ENV.env flags = [] if self.generator is not None: flags += ['-G',self.generator] for key, value in self.flags.items(): flags += ['-D{0}={1}'.format(key, value)] flags += moreflags with log.info('Running CMake:'): for key, value in env.items(): log.info('+{0}="{1}"'.format(key, value)) return cmd([CMAKE] + flags + [dir], env=env, critical=True, echo=True) return False
import os from buildtools.bt_logging import log from buildtools.os_utils import cmd, ENV class CMake(object): def __init__(self): self.flags = {} self.generator = None def setFlag(self, key, val): log.info('CMake: {} = {}'.format(key, val)) self.flags[key] = val def build(self, CMAKE, dir='.', env=None, target=None, moreflags=[]): moreflags += ['--build'] if target is not None: moreflags += ['--target', target] self.run(CMAKE, env, dir, moreflags) def run(self, CMAKE, env=None, dir='.', moreflags=[]): if env is None: env = ENV.env flags = [] if self.generator is not None: flags += ['-G', self.generator] for key, value in self.flags.items(): flags += ['-D{0}={1}'.format(key, value)] flags += moreflags with log.info('Running CMake:'): for key, value in env.items(): log.info('+{0}="{1}"'.format(key, value)) return cmd([CMAKE] + flags + [dir], env=env, critical=True, echo=True) return False
Fix mismatched args in CMake.build
Fix mismatched args in CMake.build
Python
mit
N3X15/python-build-tools,N3X15/python-build-tools,N3X15/python-build-tools
python
## Code Before: import os from buildtools.bt_logging import log from buildtools.os_utils import cmd, ENV class CMake(object): def __init__(self): self.flags = {} self.generator = None def setFlag(self, key, val): log.info('CMake: {} = {}'.format(key, val)) self.flags[key] = val def build(self, CMAKE, dir='.', env=None, target=None, moreflags=[]): moreflags += ['--build'] if target is not None: moreflags += ['--target',target] self.run(CMAKE,dir,env,moreflags) def run(self, CMAKE, env=None, dir='.', moreflags=[]): if env is None: env = ENV.env flags = [] if self.generator is not None: flags += ['-G',self.generator] for key, value in self.flags.items(): flags += ['-D{0}={1}'.format(key, value)] flags += moreflags with log.info('Running CMake:'): for key, value in env.items(): log.info('+{0}="{1}"'.format(key, value)) return cmd([CMAKE] + flags + [dir], env=env, critical=True, echo=True) return False ## Instruction: Fix mismatched args in CMake.build ## Code After: import os from buildtools.bt_logging import log from buildtools.os_utils import cmd, ENV class CMake(object): def __init__(self): self.flags = {} self.generator = None def setFlag(self, key, val): log.info('CMake: {} = {}'.format(key, val)) self.flags[key] = val def build(self, CMAKE, dir='.', env=None, target=None, moreflags=[]): moreflags += ['--build'] if target is not None: moreflags += ['--target', target] self.run(CMAKE, env, dir, moreflags) def run(self, CMAKE, env=None, dir='.', moreflags=[]): if env is None: env = ENV.env flags = [] if self.generator is not None: flags += ['-G', self.generator] for key, value in self.flags.items(): flags += ['-D{0}={1}'.format(key, value)] flags += moreflags with log.info('Running CMake:'): for key, value in env.items(): log.info('+{0}="{1}"'.format(key, value)) return cmd([CMAKE] + flags + [dir], env=env, critical=True, echo=True) return False
# ... existing code ... def build(self, CMAKE, dir='.', env=None, target=None, moreflags=[]): moreflags += ['--build'] if target is not None: moreflags += ['--target', target] self.run(CMAKE, env, dir, moreflags) def run(self, CMAKE, env=None, dir='.', moreflags=[]): if env is None: # ... modified code ... flags = [] if self.generator is not None: flags += ['-G', self.generator] for key, value in self.flags.items(): flags += ['-D{0}={1}'.format(key, value)] # ... rest of the code ...
6fa6ef07dd18794b75d63ffa2a5be83e2ec9b674
bit/count_ones.py
bit/count_ones.py
def count_ones(n): """ :type n: int :rtype: int """ counter = 0 while n: counter += n & 1 n >>= 1 return counter
def count_ones(n): """ :type n: int :rtype: int """ if n < 0: return counter = 0 while n: counter += n & 1 n >>= 1 return counter
Check if the input is negative
Check if the input is negative As the comments mention, the code would work only for unsigned integers. If a negative integer is provided as input, then the code runs into an infinite loop. To avoid this, we are checking if the input is negative. If yes, then return control before loop is entered.
Python
mit
amaozhao/algorithms,keon/algorithms
python
## Code Before: def count_ones(n): """ :type n: int :rtype: int """ counter = 0 while n: counter += n & 1 n >>= 1 return counter ## Instruction: Check if the input is negative As the comments mention, the code would work only for unsigned integers. If a negative integer is provided as input, then the code runs into an infinite loop. To avoid this, we are checking if the input is negative. If yes, then return control before loop is entered. ## Code After: def count_ones(n): """ :type n: int :rtype: int """ if n < 0: return counter = 0 while n: counter += n & 1 n >>= 1 return counter
# ... existing code ... :type n: int :rtype: int """ if n < 0: return counter = 0 while n: counter += n & 1 # ... rest of the code ...
b457af625a2a9a77720e426ecd4c02ad05bece0d
ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewHierarchyDumper.java
ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewHierarchyDumper.java
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.uimanager; import javax.annotation.Nullable; import android.view.View; import android.view.ViewGroup; import com.facebook.react.bridge.UiThreadUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class ViewHierarchyDumper { public static @Nullable JSONObject toJSON(@Nullable View view) { UiThreadUtil.assertOnUiThread(); if (view == null) { return null; } JSONObject result = new JSONObject(); try { result.put("class", view.getClass().getSimpleName()); Object tag = view.getTag(); if (tag != null && tag instanceof String) { result.put("id", tag); } if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; if (viewGroup.getChildCount() > 0) { JSONArray children = new JSONArray(); for (int i = 0; i < viewGroup.getChildCount(); i++) { children.put(i, toJSON(viewGroup.getChildAt(i))); } result.put("children", children); } } } catch (JSONException ex) { return null; } return result; } }
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.uimanager; import android.view.View; import android.view.ViewGroup; import com.facebook.react.bridge.UiThreadUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class ViewHierarchyDumper { public static JSONObject toJSON(View view) throws JSONException { UiThreadUtil.assertOnUiThread(); JSONObject result = new JSONObject(); result.put("n", view.getClass().getName()); result.put("i", System.identityHashCode(view)); Object tag = view.getTag(); if (tag != null && tag instanceof String) { result.put("t", tag); } if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; if (viewGroup.getChildCount() > 0) { JSONArray children = new JSONArray(); for (int i = 0; i < viewGroup.getChildCount(); i++) { children.put(i, toJSON(viewGroup.getChildAt(i))); } result.put("c", children); } } return result; } }
Add custom error reporter in Groups
Add custom error reporter in Groups Differential Revision: D3413351 fbshipit-source-id: 580782aac2966a07a3dbce9e9268392739e4803b
Java
bsd-3-clause
christopherdro/react-native,thotegowda/react-native,csatf/react-native,gre/react-native,skatpgusskat/react-native,peterp/react-native,exponentjs/react-native,chnfeeeeeef/react-native,javache/react-native,skatpgusskat/react-native,facebook/react-native,brentvatne/react-native,gilesvangruisen/react-native,wenpkpk/react-native,orenklein/react-native,myntra/react-native,aaron-goshine/react-native,happypancake/react-native,myntra/react-native,forcedotcom/react-native,nathanajah/react-native,skevy/react-native,imDangerous/react-native,DanielMSchmidt/react-native,brentvatne/react-native,ptomasroos/react-native,formatlos/react-native,forcedotcom/react-native,DanielMSchmidt/react-native,aaron-goshine/react-native,Ehesp/react-native,skevy/react-native,callstack-io/react-native,kesha-antonov/react-native,kesha-antonov/react-native,DanielMSchmidt/react-native,CodeLinkIO/react-native,Purii/react-native,exponentjs/react-native,pandiaraj44/react-native,aljs/react-native,jevakallio/react-native,Swaagie/react-native,tsjing/react-native,clozr/react-native,gitim/react-native,jaggs6/react-native,jevakallio/react-native,browniefed/react-native,facebook/react-native,browniefed/react-native,clozr/react-native,mrspeaker/react-native,foghina/react-native,javache/react-native,ptmt/react-native-macos,htc2u/react-native,Swaagie/react-native,nathanajah/react-native,hoangpham95/react-native,rickbeerendonk/react-native,Livyli/react-native,ptmt/react-native-macos,Purii/react-native,doochik/react-native,tgoldenberg/react-native,formatlos/react-native,tsjing/react-native,catalinmiron/react-native,formatlos/react-native,tsjing/react-native,charlesvinette/react-native,csatf/react-native,eduardinni/react-native,jasonnoahchoi/react-native,imDangerous/react-native,eduardinni/react-native,shrutic123/react-native,shrutic/react-native,Maxwell2022/react-native,corbt/react-native,exponentjs/react-native,Maxwell2022/react-native,janicduplessis/react-native,adamjmcgrath/react-native,tszajna0/react-native,aljs/react-native,Guardiannw/react-native,happypancake/react-native,forcedotcom/react-native,DanielMSchmidt/react-native,lprhodes/react-native,salanki/react-native,cpunion/react-native,tarkus/react-native-appletv,jhen0409/react-native,dikaiosune/react-native,cdlewis/react-native,Andreyco/react-native,cdlewis/react-native,jaggs6/react-native,dikaiosune/react-native,jevakallio/react-native,Maxwell2022/react-native,Livyli/react-native,exponent/react-native,esauter5/react-native,Maxwell2022/react-native,negativetwelve/react-native,pandiaraj44/react-native,cosmith/react-native,shrutic/react-native,PlexChat/react-native,forcedotcom/react-native,jhen0409/react-native,htc2u/react-native,hoastoolshop/react-native,kesha-antonov/react-native,shrutic123/react-native,Livyli/react-native,DanielMSchmidt/react-native,dikaiosune/react-native,tsjing/react-native,salanki/react-native,shrutic123/react-native,CodeLinkIO/react-native,Livyli/react-native,nathanajah/react-native,hoangpham95/react-native,charlesvinette/react-native,wenpkpk/react-native,cdlewis/react-native,facebook/react-native,ptomasroos/react-native,brentvatne/react-native,exponentjs/react-native,jasonnoahchoi/react-native,catalinmiron/react-native,gilesvangruisen/react-native,gitim/react-native,chnfeeeeeef/react-native,imjerrybao/react-native,arthuralee/react-native,farazs/react-native,farazs/react-native,jasonnoahchoi/react-native,orenklein/react-native,mironiasty/react-native,DannyvanderJagt/react-native,Guardiannw/react-native,jadbox/react-native,imjerrybao/react-native,forcedotcom/react-native,browniefed/react-native,jevakallio/react-native,janicduplessis/react-native,DannyvanderJagt/react-native,dikaiosune/react-native,orenklein/react-native,javache/react-native,adamjmcgrath/react-native,jevakallio/react-native,csatf/react-native,eduardinni/react-native,gitim/react-native,PlexChat/react-native,peterp/react-native,tadeuzagallo/react-native,tszajna0/react-native,chnfeeeeeef/react-native,eduardinni/react-native,Andreyco/react-native,brentvatne/react-native,adamjmcgrath/react-native,makadaw/react-native,gitim/react-native,aljs/react-native,alin23/react-native,Emilios1995/react-native,Bhullnatik/react-native,exponent/react-native,cdlewis/react-native,PlexChat/react-native,Livyli/react-native,Livyli/react-native,happypancake/react-native,cosmith/react-native,corbt/react-native,makadaw/react-native,chnfeeeeeef/react-native,htc2u/react-native,orenklein/react-native,jhen0409/react-native,csatf/react-native,catalinmiron/react-native,Guardiannw/react-native,facebook/react-native,esauter5/react-native,ndejesus1227/react-native,catalinmiron/react-native,catalinmiron/react-native,ptmt/react-native-macos,tarkus/react-native-appletv,wenpkpk/react-native,jhen0409/react-native,ankitsinghania94/react-native,hammerandchisel/react-native,formatlos/react-native,chnfeeeeeef/react-native,InterfaceInc/react-native,cosmith/react-native,kesha-antonov/react-native,gre/react-native,kesha-antonov/react-native,alin23/react-native,gitim/react-native,pandiaraj44/react-native,adamjmcgrath/react-native,tgoldenberg/react-native,ptomasroos/react-native,cosmith/react-native,clozr/react-native,cpunion/react-native,jhen0409/react-native,corbt/react-native,naoufal/react-native,jhen0409/react-native,alin23/react-native,mironiasty/react-native,peterp/react-native,hoastoolshop/react-native,jevakallio/react-native,jaggs6/react-native,catalinmiron/react-native,shrutic/react-native,kesha-antonov/react-native,naoufal/react-native,charlesvinette/react-native,makadaw/react-native,javache/react-native,tarkus/react-native-appletv,frantic/react-native,alin23/react-native,negativetwelve/react-native,Bhullnatik/react-native,ptmt/react-native-macos,Swaagie/react-native,myntra/react-native,hoastoolshop/react-native,nickhudkins/react-native,Swaagie/react-native,ndejesus1227/react-native,callstack-io/react-native,christopherdro/react-native,hoangpham95/react-native,arthuralee/react-native,tsjing/react-native,mrspeaker/react-native,hoangpham95/react-native,mironiasty/react-native,browniefed/react-native,Andreyco/react-native,clozr/react-native,orenklein/react-native,shrutic123/react-native,cpunion/react-native,Bhullnatik/react-native,tadeuzagallo/react-native,htc2u/react-native,thotegowda/react-native,pandiaraj44/react-native,tarkus/react-native-appletv,Bhullnatik/react-native,satya164/react-native,brentvatne/react-native,jadbox/react-native,cpunion/react-native,Guardiannw/react-native,satya164/react-native,cdlewis/react-native,wenpkpk/react-native,farazs/react-native,imjerrybao/react-native,Purii/react-native,xiayz/react-native,skatpgusskat/react-native,arthuralee/react-native,hammerandchisel/react-native,Livyli/react-native,Bhullnatik/react-native,exponent/react-native,tszajna0/react-native,christopherdro/react-native,htc2u/react-native,tgoldenberg/react-native,ptomasroos/react-native,eduardinni/react-native,ptomasroos/react-native,InterfaceInc/react-native,exponentjs/react-native,hammerandchisel/react-native,foghina/react-native,ankitsinghania94/react-native,happypancake/react-native,foghina/react-native,doochik/react-native,tadeuzagallo/react-native,ndejesus1227/react-native,InterfaceInc/react-native,callstack-io/react-native,Ehesp/react-native,aaron-goshine/react-native,cdlewis/react-native,ndejesus1227/react-native,facebook/react-native,exponent/react-native,pandiaraj44/react-native,shrutic/react-native,adamjmcgrath/react-native,dikaiosune/react-native,facebook/react-native,xiayz/react-native,lprhodes/react-native,DannyvanderJagt/react-native,myntra/react-native,cosmith/react-native,gre/react-native,ptmt/react-native-macos,exponent/react-native,farazs/react-native,tadeuzagallo/react-native,ptmt/react-native-macos,Maxwell2022/react-native,gre/react-native,Ehesp/react-native,jasonnoahchoi/react-native,alin23/react-native,tgoldenberg/react-native,tsjing/react-native,jaggs6/react-native,hammerandchisel/react-native,thotegowda/react-native,cpunion/react-native,arthuralee/react-native,nathanajah/react-native,mrspeaker/react-native,PlexChat/react-native,jevakallio/react-native,mironiasty/react-native,gilesvangruisen/react-native,htc2u/react-native,mrspeaker/react-native,adamjmcgrath/react-native,ndejesus1227/react-native,hoangpham95/react-native,facebook/react-native,mironiasty/react-native,nickhudkins/react-native,satya164/react-native,ankitsinghania94/react-native,myntra/react-native,aaron-goshine/react-native,Andreyco/react-native,gilesvangruisen/react-native,tszajna0/react-native,catalinmiron/react-native,eduardinni/react-native,christopherdro/react-native,rickbeerendonk/react-native,ptmt/react-native-macos,foghina/react-native,wenpkpk/react-native,Bhullnatik/react-native,alin23/react-native,Bhullnatik/react-native,mrspeaker/react-native,exponentjs/react-native,aljs/react-native,skevy/react-native,myntra/react-native,doochik/react-native,skatpgusskat/react-native,DannyvanderJagt/react-native,charlesvinette/react-native,lprhodes/react-native,thotegowda/react-native,exponent/react-native,skatpgusskat/react-native,rickbeerendonk/react-native,esauter5/react-native,chnfeeeeeef/react-native,farazs/react-native,callstack-io/react-native,jaggs6/react-native,Purii/react-native,aljs/react-native,javache/react-native,gitim/react-native,xiayz/react-native,jaggs6/react-native,mironiasty/react-native,nickhudkins/react-native,hoastoolshop/react-native,Ehesp/react-native,forcedotcom/react-native,gre/react-native,DannyvanderJagt/react-native,Guardiannw/react-native,Swaagie/react-native,nathanajah/react-native,xiayz/react-native,javache/react-native,Andreyco/react-native,ankitsinghania94/react-native,corbt/react-native,Purii/react-native,InterfaceInc/react-native,Andreyco/react-native,jadbox/react-native,cosmith/react-native,peterp/react-native,salanki/react-native,callstack-io/react-native,Ehesp/react-native,thotegowda/react-native,salanki/react-native,Swaagie/react-native,negativetwelve/react-native,ptomasroos/react-native,frantic/react-native,imDangerous/react-native,Purii/react-native,makadaw/react-native,Maxwell2022/react-native,tszajna0/react-native,imjerrybao/react-native,farazs/react-native,satya164/react-native,makadaw/react-native,tadeuzagallo/react-native,cpunion/react-native,foghina/react-native,Ehesp/react-native,hoangpham95/react-native,dikaiosune/react-native,esauter5/react-native,rickbeerendonk/react-native,mrspeaker/react-native,frantic/react-native,Maxwell2022/react-native,Purii/react-native,jadbox/react-native,lprhodes/react-native,tszajna0/react-native,CodeLinkIO/react-native,Livyli/react-native,brentvatne/react-native,browniefed/react-native,skevy/react-native,doochik/react-native,eduardinni/react-native,brentvatne/react-native,Guardiannw/react-native,janicduplessis/react-native,tgoldenberg/react-native,Ehesp/react-native,makadaw/react-native,orenklein/react-native,jadbox/react-native,jadbox/react-native,christopherdro/react-native,happypancake/react-native,xiayz/react-native,tsjing/react-native,charlesvinette/react-native,tadeuzagallo/react-native,jasonnoahchoi/react-native,lprhodes/react-native,tszajna0/react-native,myntra/react-native,skatpgusskat/react-native,janicduplessis/react-native,janicduplessis/react-native,tarkus/react-native-appletv,exponentjs/react-native,dikaiosune/react-native,CodeLinkIO/react-native,Emilios1995/react-native,wenpkpk/react-native,frantic/react-native,pandiaraj44/react-native,Emilios1995/react-native,InterfaceInc/react-native,jaggs6/react-native,kesha-antonov/react-native,ndejesus1227/react-native,jhen0409/react-native,frantic/react-native,wenpkpk/react-native,charlesvinette/react-native,doochik/react-native,browniefed/react-native,imDangerous/react-native,charlesvinette/react-native,cosmith/react-native,christopherdro/react-native,aljs/react-native,shrutic123/react-native,naoufal/react-native,DannyvanderJagt/react-native,imDangerous/react-native,hoastoolshop/react-native,javache/react-native,jasonnoahchoi/react-native,mrspeaker/react-native,jevakallio/react-native,ankitsinghania94/react-native,DanielMSchmidt/react-native,skatpgusskat/react-native,shrutic/react-native,arthuralee/react-native,htc2u/react-native,esauter5/react-native,satya164/react-native,skevy/react-native,csatf/react-native,lprhodes/react-native,charlesvinette/react-native,Guardiannw/react-native,tadeuzagallo/react-native,InterfaceInc/react-native,xiayz/react-native,myntra/react-native,formatlos/react-native,negativetwelve/react-native,chnfeeeeeef/react-native,pandiaraj44/react-native,PlexChat/react-native,InterfaceInc/react-native,foghina/react-native,lprhodes/react-native,hammerandchisel/react-native,tarkus/react-native-appletv,naoufal/react-native,naoufal/react-native,imDangerous/react-native,foghina/react-native,gilesvangruisen/react-native,negativetwelve/react-native,corbt/react-native,doochik/react-native,tgoldenberg/react-native,exponent/react-native,nickhudkins/react-native,adamjmcgrath/react-native,xiayz/react-native,esauter5/react-native,callstack-io/react-native,farazs/react-native,csatf/react-native,Emilios1995/react-native,farazs/react-native,thotegowda/react-native,negativetwelve/react-native,clozr/react-native,salanki/react-native,corbt/react-native,DanielMSchmidt/react-native,hoastoolshop/react-native,cosmith/react-native,cpunion/react-native,cpunion/react-native,alin23/react-native,peterp/react-native,jadbox/react-native,tarkus/react-native-appletv,ptomasroos/react-native,janicduplessis/react-native,jasonnoahchoi/react-native,facebook/react-native,Bhullnatik/react-native,Purii/react-native,skevy/react-native,salanki/react-native,ankitsinghania94/react-native,gitim/react-native,skatpgusskat/react-native,clozr/react-native,doochik/react-native,naoufal/react-native,ndejesus1227/react-native,corbt/react-native,forcedotcom/react-native,lprhodes/react-native,peterp/react-native,negativetwelve/react-native,rickbeerendonk/react-native,clozr/react-native,imjerrybao/react-native,cdlewis/react-native,Emilios1995/react-native,forcedotcom/react-native,aaron-goshine/react-native,aaron-goshine/react-native,exponentjs/react-native,christopherdro/react-native,satya164/react-native,peterp/react-native,PlexChat/react-native,cdlewis/react-native,skevy/react-native,Emilios1995/react-native,aaron-goshine/react-native,mrspeaker/react-native,mironiasty/react-native,CodeLinkIO/react-native,gre/react-native,tarkus/react-native-appletv,formatlos/react-native,gilesvangruisen/react-native,callstack-io/react-native,orenklein/react-native,imDangerous/react-native,shrutic123/react-native,callstack-io/react-native,naoufal/react-native,brentvatne/react-native,aljs/react-native,happypancake/react-native,Andreyco/react-native,imjerrybao/react-native,ndejesus1227/react-native,mironiasty/react-native,tgoldenberg/react-native,makadaw/react-native,javache/react-native,shrutic123/react-native,shrutic/react-native,alin23/react-native,jhen0409/react-native,imjerrybao/react-native,Ehesp/react-native,wenpkpk/react-native,aljs/react-native,chnfeeeeeef/react-native,happypancake/react-native,jadbox/react-native,skevy/react-native,nathanajah/react-native,InterfaceInc/react-native,csatf/react-native,gre/react-native,kesha-antonov/react-native,catalinmiron/react-native,peterp/react-native,salanki/react-native,satya164/react-native,nathanajah/react-native,gitim/react-native,rickbeerendonk/react-native,PlexChat/react-native,jaggs6/react-native,doochik/react-native,hammerandchisel/react-native,hammerandchisel/react-native,pandiaraj44/react-native,cdlewis/react-native,naoufal/react-native,rickbeerendonk/react-native,happypancake/react-native,ankitsinghania94/react-native,makadaw/react-native,CodeLinkIO/react-native,imDangerous/react-native,tadeuzagallo/react-native,jevakallio/react-native,thotegowda/react-native,foghina/react-native,ankitsinghania94/react-native,htc2u/react-native,formatlos/react-native,satya164/react-native,xiayz/react-native,shrutic/react-native,christopherdro/react-native,janicduplessis/react-native,browniefed/react-native,janicduplessis/react-native,DannyvanderJagt/react-native,imjerrybao/react-native,adamjmcgrath/react-native,myntra/react-native,brentvatne/react-native,esauter5/react-native,farazs/react-native,gilesvangruisen/react-native,DannyvanderJagt/react-native,tsjing/react-native,ptomasroos/react-native,nickhudkins/react-native,CodeLinkIO/react-native,gre/react-native,kesha-antonov/react-native,negativetwelve/react-native,formatlos/react-native,Andreyco/react-native,ptmt/react-native-macos,exponent/react-native,hoastoolshop/react-native,hoangpham95/react-native,tgoldenberg/react-native,shrutic/react-native,formatlos/react-native,doochik/react-native,hoastoolshop/react-native,thotegowda/react-native,dikaiosune/react-native,makadaw/react-native,esauter5/react-native,Swaagie/react-native,browniefed/react-native,corbt/react-native,javache/react-native,clozr/react-native,jasonnoahchoi/react-native,csatf/react-native,CodeLinkIO/react-native,Swaagie/react-native,nathanajah/react-native,gilesvangruisen/react-native,Guardiannw/react-native,hammerandchisel/react-native,salanki/react-native,tszajna0/react-native,Emilios1995/react-native,DanielMSchmidt/react-native,rickbeerendonk/react-native,nickhudkins/react-native,rickbeerendonk/react-native,hoangpham95/react-native,nickhudkins/react-native,mironiasty/react-native,aaron-goshine/react-native,eduardinni/react-native,shrutic123/react-native,facebook/react-native,nickhudkins/react-native,Maxwell2022/react-native,negativetwelve/react-native,orenklein/react-native,Emilios1995/react-native,PlexChat/react-native
java
## Code Before: /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.uimanager; import javax.annotation.Nullable; import android.view.View; import android.view.ViewGroup; import com.facebook.react.bridge.UiThreadUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class ViewHierarchyDumper { public static @Nullable JSONObject toJSON(@Nullable View view) { UiThreadUtil.assertOnUiThread(); if (view == null) { return null; } JSONObject result = new JSONObject(); try { result.put("class", view.getClass().getSimpleName()); Object tag = view.getTag(); if (tag != null && tag instanceof String) { result.put("id", tag); } if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; if (viewGroup.getChildCount() > 0) { JSONArray children = new JSONArray(); for (int i = 0; i < viewGroup.getChildCount(); i++) { children.put(i, toJSON(viewGroup.getChildAt(i))); } result.put("children", children); } } } catch (JSONException ex) { return null; } return result; } } ## Instruction: Add custom error reporter in Groups Differential Revision: D3413351 fbshipit-source-id: 580782aac2966a07a3dbce9e9268392739e4803b ## Code After: /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.uimanager; import android.view.View; import android.view.ViewGroup; import com.facebook.react.bridge.UiThreadUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class ViewHierarchyDumper { public static JSONObject toJSON(View view) throws JSONException { UiThreadUtil.assertOnUiThread(); JSONObject result = new JSONObject(); result.put("n", view.getClass().getName()); result.put("i", System.identityHashCode(view)); Object tag = view.getTag(); if (tag != null && tag instanceof String) { result.put("t", tag); } if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; if (viewGroup.getChildCount() > 0) { JSONArray children = new JSONArray(); for (int i = 0; i < viewGroup.getChildCount(); i++) { children.put(i, toJSON(viewGroup.getChildAt(i))); } result.put("c", children); } } return result; } }
# ... existing code ... */ package com.facebook.react.uimanager; import android.view.View; import android.view.ViewGroup; # ... modified code ... public class ViewHierarchyDumper { public static JSONObject toJSON(View view) throws JSONException { UiThreadUtil.assertOnUiThread(); JSONObject result = new JSONObject(); result.put("n", view.getClass().getName()); result.put("i", System.identityHashCode(view)); Object tag = view.getTag(); if (tag != null && tag instanceof String) { result.put("t", tag); } if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; if (viewGroup.getChildCount() > 0) { JSONArray children = new JSONArray(); for (int i = 0; i < viewGroup.getChildCount(); i++) { children.put(i, toJSON(viewGroup.getChildAt(i))); } result.put("c", children); } } return result; } } # ... rest of the code ...
8b5d2f3e9f4a0c9034449e5bb310c73d2e8ff98d
src/test/java/org/freecompany/redline/ScannerTest.java
src/test/java/org/freecompany/redline/ScannerTest.java
package org.freecompany.redline; import java.io.File; import org.junit.Test; public class ScannerTest extends TestBase { @Test public void scanNoArchRPMTest() throws Exception { Scanner.main ( new String[]{ getTestResourcesDirectory ( ) + File.separator + "rpm-1-1.0-1.noarch.rpm" } ); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void scanSomeArchTest() throws Exception { Scanner.main ( new String[]{ getTestResourcesDirectory ( ) + File.separator + "rpm-3-1.0-1.somearch.rpm" } ); } }
package org.freecompany.redline; import java.io.File; import org.junit.Test; public class ScannerTest extends TestBase { @Test public void scanNoArchRPMTest() throws Exception { Scanner.main ( new String[]{ getTestResourcesDirectory ( ) + File.separator + "rpm-1-1.0-1.noarch.rpm" } ); } @Test public void scanSomeArchTest() throws Exception { Scanner.main ( new String[]{ getTestResourcesDirectory ( ) + File.separator + "rpm-3-1.0-1.somearch.rpm" } ); } }
Remove AIOOBE assertion on scanSomeArchTest
Remove AIOOBE assertion on scanSomeArchTest has been fixed in Lead.java
Java
mit
craigwblake/redline,craigwblake/redline,joker1/redline,craigwblake/redline,craigwblake/redline,joker1/redline,craigwblake/redline,joker1/redline,joker1/redline
java
## Code Before: package org.freecompany.redline; import java.io.File; import org.junit.Test; public class ScannerTest extends TestBase { @Test public void scanNoArchRPMTest() throws Exception { Scanner.main ( new String[]{ getTestResourcesDirectory ( ) + File.separator + "rpm-1-1.0-1.noarch.rpm" } ); } @Test(expected = ArrayIndexOutOfBoundsException.class) public void scanSomeArchTest() throws Exception { Scanner.main ( new String[]{ getTestResourcesDirectory ( ) + File.separator + "rpm-3-1.0-1.somearch.rpm" } ); } } ## Instruction: Remove AIOOBE assertion on scanSomeArchTest has been fixed in Lead.java ## Code After: package org.freecompany.redline; import java.io.File; import org.junit.Test; public class ScannerTest extends TestBase { @Test public void scanNoArchRPMTest() throws Exception { Scanner.main ( new String[]{ getTestResourcesDirectory ( ) + File.separator + "rpm-1-1.0-1.noarch.rpm" } ); } @Test public void scanSomeArchTest() throws Exception { Scanner.main ( new String[]{ getTestResourcesDirectory ( ) + File.separator + "rpm-3-1.0-1.somearch.rpm" } ); } }
... Scanner.main ( new String[]{ getTestResourcesDirectory ( ) + File.separator + "rpm-1-1.0-1.noarch.rpm" } ); } @Test public void scanSomeArchTest() throws Exception { Scanner.main ( new String[]{ getTestResourcesDirectory ( ) + File.separator + "rpm-3-1.0-1.somearch.rpm" } ); } ...
067c9be6c9e362a9a902f3233e1ae0b2643d405f
src/sequences/io/trend/price/macd/s_chunk.py
src/sequences/io/trend/price/macd/s_chunk.py
''' Sequential Price-Trend Models: MACD with Price-Bar-Chunk (MDC) ''' import numpy import json from techmodels.overlays.trend.price.chunk import sign_chunker from techmodels.indicators.trend.price.macd import MACDIndicator def macd_chunk(data, nfast=10, nslow=35, nema=5, getter=lambda x: x): prices = numpy.array(map(getter, data)) macd_oscillator = MACDIndicator(prices, nfast, nslow, nema) # Skip the first nfast values cropped_indicator = macd_oscillator.indicator()[nfast + 1:] cropped_data = data[nfast + 1:] chunks = sign_chunker(cropped_indicator, cropped_data) return chunks def macd_chunk_json(input): python_list = json.loads(input) chunks = macd_chunk(python_list, getter=lambda x: x[u'close']) return json.dumps(chunks)
''' Sequential Price-Trend Models: MACD with Price-Bar-Chunk (MDC) ''' import numpy import json from techmodels.overlays.trend.price.chunk import sign_chunker from techmodels.indicators.trend.price.macd import MACDIndicator def macd_chunk(data, nfast=10, nslow=35, nema=5, getter=lambda x: x): prices = numpy.array(map(getter, data)) macd_oscillator = MACDIndicator(prices, nfast, nslow, nema) # Skip the first nfast values cropped_indicator = macd_oscillator.indicator()[nfast + 1:] cropped_data = data[nfast + 1:] chunks = sign_chunker(cropped_indicator, cropped_data) return chunks def macd_chunk_json(data, pricetype=u'close'): python_list = json.loads(data) chunks = macd_chunk(python_list, getter=lambda x: x[pricetype]) return json.dumps(chunks)
Handle two arguments while converting to JSON
Feature: Handle two arguments while converting to JSON
Python
mpl-2.0
Skalman/owl_analytics
python
## Code Before: ''' Sequential Price-Trend Models: MACD with Price-Bar-Chunk (MDC) ''' import numpy import json from techmodels.overlays.trend.price.chunk import sign_chunker from techmodels.indicators.trend.price.macd import MACDIndicator def macd_chunk(data, nfast=10, nslow=35, nema=5, getter=lambda x: x): prices = numpy.array(map(getter, data)) macd_oscillator = MACDIndicator(prices, nfast, nslow, nema) # Skip the first nfast values cropped_indicator = macd_oscillator.indicator()[nfast + 1:] cropped_data = data[nfast + 1:] chunks = sign_chunker(cropped_indicator, cropped_data) return chunks def macd_chunk_json(input): python_list = json.loads(input) chunks = macd_chunk(python_list, getter=lambda x: x[u'close']) return json.dumps(chunks) ## Instruction: Feature: Handle two arguments while converting to JSON ## Code After: ''' Sequential Price-Trend Models: MACD with Price-Bar-Chunk (MDC) ''' import numpy import json from techmodels.overlays.trend.price.chunk import sign_chunker from techmodels.indicators.trend.price.macd import MACDIndicator def macd_chunk(data, nfast=10, nslow=35, nema=5, getter=lambda x: x): prices = numpy.array(map(getter, data)) macd_oscillator = MACDIndicator(prices, nfast, nslow, nema) # Skip the first nfast values cropped_indicator = macd_oscillator.indicator()[nfast + 1:] cropped_data = data[nfast + 1:] chunks = sign_chunker(cropped_indicator, cropped_data) return chunks def macd_chunk_json(data, pricetype=u'close'): python_list = json.loads(data) chunks = macd_chunk(python_list, getter=lambda x: x[pricetype]) return json.dumps(chunks)
# ... existing code ... return chunks def macd_chunk_json(data, pricetype=u'close'): python_list = json.loads(data) chunks = macd_chunk(python_list, getter=lambda x: x[pricetype]) return json.dumps(chunks) # ... rest of the code ...
436195aad8c3e7a069066e9e1d4db6dfa9ac34db
devilry/addons/student/devilry_plugin.py
devilry/addons/student/devilry_plugin.py
from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from devilry.addons.dashboard.dashboardplugin_registry import registry, \ DashboardItem import dashboardviews def simpleview(request, *args): return mark_safe(u"""Student dashboard-view(s) is not finished. <a href='%s'>Click here</a> for the main student view.""" % reverse('devilry-student-show-assignments')) registry.register_important(DashboardItem( title = _('Student'), candidate_access = True, view = dashboardviews.list_assignments))
from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from devilry.addons.dashboard.dashboardplugin_registry import registry, \ DashboardItem import dashboardviews registry.register_important(DashboardItem( title = _('Assignments'), candidate_access = True, view = dashboardviews.list_assignments))
Set title to 'Assignment' in student dashboard
Set title to 'Assignment' in student dashboard
Python
bsd-3-clause
devilry/devilry-django,devilry/devilry-django,devilry/devilry-django,vegarang/devilry-django,vegarang/devilry-django,devilry/devilry-django
python
## Code Before: from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from devilry.addons.dashboard.dashboardplugin_registry import registry, \ DashboardItem import dashboardviews def simpleview(request, *args): return mark_safe(u"""Student dashboard-view(s) is not finished. <a href='%s'>Click here</a> for the main student view.""" % reverse('devilry-student-show-assignments')) registry.register_important(DashboardItem( title = _('Student'), candidate_access = True, view = dashboardviews.list_assignments)) ## Instruction: Set title to 'Assignment' in student dashboard ## Code After: from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from devilry.addons.dashboard.dashboardplugin_registry import registry, \ DashboardItem import dashboardviews registry.register_important(DashboardItem( title = _('Assignments'), candidate_access = True, view = dashboardviews.list_assignments))
# ... existing code ... DashboardItem import dashboardviews registry.register_important(DashboardItem( title = _('Assignments'), candidate_access = True, view = dashboardviews.list_assignments)) # ... rest of the code ...
e1f2f32b87f28f948e9f8321df910700f5a5ece2
setup.py
setup.py
from setuptools import setup from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() version = {} with open(path.join(here, 'emv', "__init__.py")) as fp: exec(fp.read(), version) setup(name='emv', version=version['__version__'], description='EMV Smartcard Protocol Library', long_description=long_description, license='MIT', author='Russ Garrett', author_email='[email protected]', url='https://github.com/russss/python-emv', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3' ], keywords='smartcard emv payment', packages=['emv', 'emv.protocol', 'emv.command'], install_requires=['enum', 'argparse', 'pyscard'], entry_points={ 'console_scripts': { 'emvtool=emv.command.client:run' } } )
from setuptools import setup from codecs import open from os import path here = path.abspath(path.dirname(__file__)) readme_rst = path.join(here, 'README.rst') if path.isfile(readme_rst): with open(readme_rst, encoding='utf-8') as f: long_description = f.read() else: long_description = '' version = {} with open(path.join(here, 'emv', "__init__.py")) as fp: exec(fp.read(), version) setup(name='emv', version=version['__version__'], description='EMV Smartcard Protocol Library', long_description=long_description, license='MIT', author='Russ Garrett', author_email='[email protected]', url='https://github.com/russss/python-emv', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3' ], keywords='smartcard emv payment', packages=['emv', 'emv.protocol', 'emv.command'], install_requires=['enum', 'argparse', 'pyscard'], entry_points={ 'console_scripts': { 'emvtool=emv.command.client:run' } } )
Handle pandoc-generated readme file not being present
Handle pandoc-generated readme file not being present
Python
mit
russss/python-emv
python
## Code Before: from setuptools import setup from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() version = {} with open(path.join(here, 'emv', "__init__.py")) as fp: exec(fp.read(), version) setup(name='emv', version=version['__version__'], description='EMV Smartcard Protocol Library', long_description=long_description, license='MIT', author='Russ Garrett', author_email='[email protected]', url='https://github.com/russss/python-emv', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3' ], keywords='smartcard emv payment', packages=['emv', 'emv.protocol', 'emv.command'], install_requires=['enum', 'argparse', 'pyscard'], entry_points={ 'console_scripts': { 'emvtool=emv.command.client:run' } } ) ## Instruction: Handle pandoc-generated readme file not being present ## Code After: from setuptools import setup from codecs import open from os import path here = path.abspath(path.dirname(__file__)) readme_rst = path.join(here, 'README.rst') if path.isfile(readme_rst): with open(readme_rst, encoding='utf-8') as f: long_description = f.read() else: long_description = '' version = {} with open(path.join(here, 'emv', "__init__.py")) as fp: exec(fp.read(), version) setup(name='emv', version=version['__version__'], description='EMV Smartcard Protocol Library', long_description=long_description, license='MIT', author='Russ Garrett', author_email='[email protected]', url='https://github.com/russss/python-emv', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3' ], keywords='smartcard emv payment', packages=['emv', 'emv.protocol', 'emv.command'], install_requires=['enum', 'argparse', 'pyscard'], entry_points={ 'console_scripts': { 'emvtool=emv.command.client:run' } } )
// ... existing code ... here = path.abspath(path.dirname(__file__)) readme_rst = path.join(here, 'README.rst') if path.isfile(readme_rst): with open(readme_rst, encoding='utf-8') as f: long_description = f.read() else: long_description = '' version = {} with open(path.join(here, 'emv', "__init__.py")) as fp: // ... rest of the code ...