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
dba6f3a456b3d75e1202ccb688581876a93e48f2
pwndbg/strings.py
pwndbg/strings.py
from __future__ import print_function import string import gdb import pwndbg.events import pwndbg.typeinfo length = 15 @pwndbg.events.stop def update_length(): r""" Unfortunately there's not a better way to get at this info. >>> gdb.execute('show print elements', from_tty=False, to_string=True) 'Limit on string chars or array elements to print is 21.\n' """ global length message = gdb.execute('show print elements', from_tty=False, to_string=True) message = message.split()[-1] message = message.strip('.') length = int(message) def get(address, maxlen = None): if maxlen is None: maxlen = length try: sz = gdb.Value(address) sz = sz.cast(pwndbg.typeinfo.pchar) sz = sz.string('ascii', 'ignore') sz = str(sz) except Exception as e: return None if not all(s in string.printable for s in sz.rstrip('\x00')): return None if len(sz) < maxlen: return sz return sz[:maxlen] + '...'
from __future__ import print_function import string import gdb import pwndbg.events import pwndbg.typeinfo length = 15 @pwndbg.events.stop def update_length(): r""" Unfortunately there's not a better way to get at this info. >>> gdb.execute('show print elements', from_tty=False, to_string=True) 'Limit on string chars or array elements to print is 21.\n' """ global length message = gdb.execute('show print elements', from_tty=False, to_string=True) message = message.split()[-1] message = message.strip('.') length = int(message) def get(address, maxlen = None): if maxlen is None: maxlen = length try: sz = gdb.Value(address) sz = sz.cast(pwndbg.typeinfo.pchar) sz = sz.string('ascii', 'replace', maxlen) sz = pwndbg.memory.read(address, len(sz)) if not all(s in string.printable for s in sz.rstrip('\x00')): return None sz = str(sz) except Exception as e: return None if len(sz) < maxlen: return sz return sz[:maxlen] + '...'
Fix string extraction. The "ignore" setting was getting us lots of non-string stuff.
Fix string extraction. The "ignore" setting was getting us lots of non-string stuff.
Python
mit
anthraxx/pwndbg,cebrusfs/217gdb,pwndbg/pwndbg,chubbymaggie/pwndbg,disconnect3d/pwndbg,zachriggle/pwndbg,cebrusfs/217gdb,anthraxx/pwndbg,pwndbg/pwndbg,disconnect3d/pwndbg,cebrusfs/217gdb,disconnect3d/pwndbg,anthraxx/pwndbg,0xddaa/pwndbg,pwndbg/pwndbg,chubbymaggie/pwndbg,cebrusfs/217gdb,anthraxx/pwndbg,zachriggle/pwndbg,0xddaa/pwndbg,pwndbg/pwndbg,0xddaa/pwndbg
python
## Code Before: from __future__ import print_function import string import gdb import pwndbg.events import pwndbg.typeinfo length = 15 @pwndbg.events.stop def update_length(): r""" Unfortunately there's not a better way to get at this info. >>> gdb.execute('show print elements', from_tty=False, to_string=True) 'Limit on string chars or array elements to print is 21.\n' """ global length message = gdb.execute('show print elements', from_tty=False, to_string=True) message = message.split()[-1] message = message.strip('.') length = int(message) def get(address, maxlen = None): if maxlen is None: maxlen = length try: sz = gdb.Value(address) sz = sz.cast(pwndbg.typeinfo.pchar) sz = sz.string('ascii', 'ignore') sz = str(sz) except Exception as e: return None if not all(s in string.printable for s in sz.rstrip('\x00')): return None if len(sz) < maxlen: return sz return sz[:maxlen] + '...' ## Instruction: Fix string extraction. The "ignore" setting was getting us lots of non-string stuff. ## Code After: from __future__ import print_function import string import gdb import pwndbg.events import pwndbg.typeinfo length = 15 @pwndbg.events.stop def update_length(): r""" Unfortunately there's not a better way to get at this info. >>> gdb.execute('show print elements', from_tty=False, to_string=True) 'Limit on string chars or array elements to print is 21.\n' """ global length message = gdb.execute('show print elements', from_tty=False, to_string=True) message = message.split()[-1] message = message.strip('.') length = int(message) def get(address, maxlen = None): if maxlen is None: maxlen = length try: sz = gdb.Value(address) sz = sz.cast(pwndbg.typeinfo.pchar) sz = sz.string('ascii', 'replace', maxlen) sz = pwndbg.memory.read(address, len(sz)) if not all(s in string.printable for s in sz.rstrip('\x00')): return None sz = str(sz) except Exception as e: return None if len(sz) < maxlen: return sz return sz[:maxlen] + '...'
// ... existing code ... try: sz = gdb.Value(address) sz = sz.cast(pwndbg.typeinfo.pchar) sz = sz.string('ascii', 'replace', maxlen) sz = pwndbg.memory.read(address, len(sz)) if not all(s in string.printable for s in sz.rstrip('\x00')): return None sz = str(sz) except Exception as e: return None if len(sz) < maxlen: return sz // ... rest of the code ...
6ee7d39c7c39a018a71cbb028dd847e3da521263
views.py
views.py
from rest_framework import viewsets, permissions from rest_framework_word_filter import FullWordSearchFilter from quotedb.models import Quote from quotedb.permissions import IsOwnerOrReadOnly from quotedb.serializers import QuoteSerializer class QuoteViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ queryset = Quote.objects.all() serializer_class = QuoteSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) filter_backends = (FullWordSearchFilter,) word_fields = ('body',) def perform_create(self, serializer): serializer.save(owner=self.request.user)
from rest_framework import viewsets, permissions from rest_framework.decorators import list_route from rest_framework.response import Response from rest_framework_word_filter import FullWordSearchFilter from quotedb.models import Quote from quotedb.permissions import IsOwnerOrReadOnly from quotedb.serializers import QuoteSerializer class QuoteViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ queryset = Quote.objects.all() serializer_class = QuoteSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) filter_backends = (FullWordSearchFilter,) word_fields = ('body',) def perform_create(self, serializer): serializer.save(owner=self.request.user) @list_route() def random(self, request): queryset = Quote.objects.order_by('?').first() serializer = self.serializer_class(queryset) return Response(serializer.data)
Add route to get random quote
Add route to get random quote
Python
mit
kfdm/django-qdb,kfdm/django-qdb
python
## Code Before: from rest_framework import viewsets, permissions from rest_framework_word_filter import FullWordSearchFilter from quotedb.models import Quote from quotedb.permissions import IsOwnerOrReadOnly from quotedb.serializers import QuoteSerializer class QuoteViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ queryset = Quote.objects.all() serializer_class = QuoteSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) filter_backends = (FullWordSearchFilter,) word_fields = ('body',) def perform_create(self, serializer): serializer.save(owner=self.request.user) ## Instruction: Add route to get random quote ## Code After: from rest_framework import viewsets, permissions from rest_framework.decorators import list_route from rest_framework.response import Response from rest_framework_word_filter import FullWordSearchFilter from quotedb.models import Quote from quotedb.permissions import IsOwnerOrReadOnly from quotedb.serializers import QuoteSerializer class QuoteViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ queryset = Quote.objects.all() serializer_class = QuoteSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) filter_backends = (FullWordSearchFilter,) word_fields = ('body',) def perform_create(self, serializer): serializer.save(owner=self.request.user) @list_route() def random(self, request): queryset = Quote.objects.order_by('?').first() serializer = self.serializer_class(queryset) return Response(serializer.data)
// ... existing code ... from rest_framework import viewsets, permissions from rest_framework.decorators import list_route from rest_framework.response import Response from rest_framework_word_filter import FullWordSearchFilter from quotedb.models import Quote // ... modified code ... def perform_create(self, serializer): serializer.save(owner=self.request.user) @list_route() def random(self, request): queryset = Quote.objects.order_by('?').first() serializer = self.serializer_class(queryset) return Response(serializer.data) // ... rest of the code ...
397e185ae225613969ecff11e1cfed1e642daca0
troposphere/codeartifact.py
troposphere/codeartifact.py
from . import AWSObject class Domain(AWSObject): resource_type = "AWS::CodeArtifact::Domain" props = { 'DomainName': (basestring, True), 'PermissionsPolicyDocument': (dict, False), } class Repository(AWSObject): resource_type = "AWS::CodeArtifact::Repository" props = { 'Description': (basestring, False), 'DomainName': (basestring, True), 'DomainOwner': (basestring, False), 'ExternalConnections': ([basestring], False), 'PermissionsPolicyDocument': (dict, False), 'RepositoryName': (basestring, True), 'Upstreams': ([basestring], False), }
from . import AWSObject from troposphere import Tags class Domain(AWSObject): resource_type = "AWS::CodeArtifact::Domain" props = { 'DomainName': (basestring, True), 'EncryptionKey': (basestring, False), 'PermissionsPolicyDocument': (dict, False), 'Tags': (Tags, False), } class Repository(AWSObject): resource_type = "AWS::CodeArtifact::Repository" props = { 'Description': (basestring, False), 'DomainName': (basestring, True), 'DomainOwner': (basestring, False), 'ExternalConnections': ([basestring], False), 'PermissionsPolicyDocument': (dict, False), 'RepositoryName': (basestring, True), 'Tags': (Tags, False), 'Upstreams': ([basestring], False), }
Update CodeArtifact per 2020-11-05 changes
Update CodeArtifact per 2020-11-05 changes
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
python
## Code Before: from . import AWSObject class Domain(AWSObject): resource_type = "AWS::CodeArtifact::Domain" props = { 'DomainName': (basestring, True), 'PermissionsPolicyDocument': (dict, False), } class Repository(AWSObject): resource_type = "AWS::CodeArtifact::Repository" props = { 'Description': (basestring, False), 'DomainName': (basestring, True), 'DomainOwner': (basestring, False), 'ExternalConnections': ([basestring], False), 'PermissionsPolicyDocument': (dict, False), 'RepositoryName': (basestring, True), 'Upstreams': ([basestring], False), } ## Instruction: Update CodeArtifact per 2020-11-05 changes ## Code After: from . import AWSObject from troposphere import Tags class Domain(AWSObject): resource_type = "AWS::CodeArtifact::Domain" props = { 'DomainName': (basestring, True), 'EncryptionKey': (basestring, False), 'PermissionsPolicyDocument': (dict, False), 'Tags': (Tags, False), } class Repository(AWSObject): resource_type = "AWS::CodeArtifact::Repository" props = { 'Description': (basestring, False), 'DomainName': (basestring, True), 'DomainOwner': (basestring, False), 'ExternalConnections': ([basestring], False), 'PermissionsPolicyDocument': (dict, False), 'RepositoryName': (basestring, True), 'Tags': (Tags, False), 'Upstreams': ([basestring], False), }
... from . import AWSObject from troposphere import Tags class Domain(AWSObject): ... props = { 'DomainName': (basestring, True), 'EncryptionKey': (basestring, False), 'PermissionsPolicyDocument': (dict, False), 'Tags': (Tags, False), } ... 'ExternalConnections': ([basestring], False), 'PermissionsPolicyDocument': (dict, False), 'RepositoryName': (basestring, True), 'Tags': (Tags, False), 'Upstreams': ([basestring], False), } ...
1c10f140e6e0bc7784f3fe74fd3df07873ba8dc1
src/main/java/com/fernandocejas/java/samples/optional/UseCaseScenario03.java
src/main/java/com/fernandocejas/java/samples/optional/UseCaseScenario03.java
package com.fernandocejas.java.samples.optional; import com.fernandocejas.arrow.annotations.See; import com.fernandocejas.arrow.strings.Strings; @See(ref = "") public class UseCaseScenario03 { public UseCaseScenario03() { //empty } @Override public String toString() { return Strings.EMPTY; } }
package com.fernandocejas.java.samples.optional; import com.fernandocejas.arrow.annotations.See; import com.fernandocejas.arrow.optional.Optional; import java.util.Arrays; import java.util.Collections; import java.util.List; import rx.Observable; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; @See(ref = "") public class UseCaseScenario03 { public static final Func1<Optional<List<String>>, Observable<List<String>>> TO_AD_ITEM = new Func1<Optional<List<String>>, Observable<List<String>>>() { @Override public Observable<List<String>> call(Optional<List<String>> ads) { return ads.isPresent() ? Observable.just(ads.get()) : Observable.just(Collections.<String>emptyList()); } }; public static final Func1<List<String>, Boolean> EMPTY_ELEMENTS = new Func1<List<String>, Boolean>() { @Override public Boolean call(List<String> ads) { return !ads.isEmpty(); } }; public UseCaseScenario03() { //empty } @Override public String toString() { final StringBuilder builder = new StringBuilder(); feed().subscribe(new Action1<List<String>>() { @Override public void call(List<String> feed) { for (String feedElement : feed) { builder.append("\n").append(feedElement); } } }); return builder.toString(); } private Observable<List<String>> feed() { return ads() .flatMap(TO_AD_ITEM) .filter(EMPTY_ELEMENTS) .concatWith(users()) .observeOn(Schedulers.immediate()); } private Observable<List<String>> users() { return Observable.just(Arrays.asList("IronMan", "Wolverine", "Batman", "Superman")); } private Observable<Optional<List<String>>> ads() { return Observable.just(Optional.fromNullable(Collections.singletonList("This is and Ad"))); } }
Add third case scenario for Optional sample.
Add third case scenario for Optional sample.
Java
apache-2.0
android10/java-code-examples
java
## Code Before: package com.fernandocejas.java.samples.optional; import com.fernandocejas.arrow.annotations.See; import com.fernandocejas.arrow.strings.Strings; @See(ref = "") public class UseCaseScenario03 { public UseCaseScenario03() { //empty } @Override public String toString() { return Strings.EMPTY; } } ## Instruction: Add third case scenario for Optional sample. ## Code After: package com.fernandocejas.java.samples.optional; import com.fernandocejas.arrow.annotations.See; import com.fernandocejas.arrow.optional.Optional; import java.util.Arrays; import java.util.Collections; import java.util.List; import rx.Observable; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; @See(ref = "") public class UseCaseScenario03 { public static final Func1<Optional<List<String>>, Observable<List<String>>> TO_AD_ITEM = new Func1<Optional<List<String>>, Observable<List<String>>>() { @Override public Observable<List<String>> call(Optional<List<String>> ads) { return ads.isPresent() ? Observable.just(ads.get()) : Observable.just(Collections.<String>emptyList()); } }; public static final Func1<List<String>, Boolean> EMPTY_ELEMENTS = new Func1<List<String>, Boolean>() { @Override public Boolean call(List<String> ads) { return !ads.isEmpty(); } }; public UseCaseScenario03() { //empty } @Override public String toString() { final StringBuilder builder = new StringBuilder(); feed().subscribe(new Action1<List<String>>() { @Override public void call(List<String> feed) { for (String feedElement : feed) { builder.append("\n").append(feedElement); } } }); return builder.toString(); } private Observable<List<String>> feed() { return ads() .flatMap(TO_AD_ITEM) .filter(EMPTY_ELEMENTS) .concatWith(users()) .observeOn(Schedulers.immediate()); } private Observable<List<String>> users() { return Observable.just(Arrays.asList("IronMan", "Wolverine", "Batman", "Superman")); } private Observable<Optional<List<String>>> ads() { return Observable.just(Optional.fromNullable(Collections.singletonList("This is and Ad"))); } }
... package com.fernandocejas.java.samples.optional; import com.fernandocejas.arrow.annotations.See; import com.fernandocejas.arrow.optional.Optional; import java.util.Arrays; import java.util.Collections; import java.util.List; import rx.Observable; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; @See(ref = "") public class UseCaseScenario03 { public static final Func1<Optional<List<String>>, Observable<List<String>>> TO_AD_ITEM = new Func1<Optional<List<String>>, Observable<List<String>>>() { @Override public Observable<List<String>> call(Optional<List<String>> ads) { return ads.isPresent() ? Observable.just(ads.get()) : Observable.just(Collections.<String>emptyList()); } }; public static final Func1<List<String>, Boolean> EMPTY_ELEMENTS = new Func1<List<String>, Boolean>() { @Override public Boolean call(List<String> ads) { return !ads.isEmpty(); } }; public UseCaseScenario03() { //empty ... } @Override public String toString() { final StringBuilder builder = new StringBuilder(); feed().subscribe(new Action1<List<String>>() { @Override public void call(List<String> feed) { for (String feedElement : feed) { builder.append("\n").append(feedElement); } } }); return builder.toString(); } private Observable<List<String>> feed() { return ads() .flatMap(TO_AD_ITEM) .filter(EMPTY_ELEMENTS) .concatWith(users()) .observeOn(Schedulers.immediate()); } private Observable<List<String>> users() { return Observable.just(Arrays.asList("IronMan", "Wolverine", "Batman", "Superman")); } private Observable<Optional<List<String>>> ads() { return Observable.just(Optional.fromNullable(Collections.singletonList("This is and Ad"))); } } ...
95bac0b68e271d7ad5a4f8fa22c441d18a65390c
client/serial_datagrams.py
client/serial_datagrams.py
import struct from zlib import crc32 class CRCMismatchError(RuntimeError): """ Error raised when a datagram has an invalid CRC. """ pass class FrameError(RuntimeError): """ Error raised when a datagram is too short to be valid. """ END = b'\xC0' ESC = b'\xDB' ESC_END = b'\xDC' ESC_ESC = b'\xDD' def datagram_encode(data): """ Encodes the given datagram (bytes object) by adding a CRC at the end then an end marker. It also escapes the end marker correctly. """ data = data + struct.pack('>I', crc32(data)) data = data.replace(ESC, ESC + ESC_ESC) data = data.replace(END, ESC + ESC_END) return data + END def datagram_decode(data): """ Decodes a datagram. Exact inverse of datagram_encode() """ # Checks if the data is at least long enough for the CRC and the END marker if len(data) < 5: raise FrameError data = data[:-1] # remote end marker data = data.replace(ESC + ESC_END, END) data = data.replace(ESC + ESC_ESC, ESC) expected_crc = struct.unpack('>I', data[-4:])[0] actual_crc = crc32(data[:-4]) if expected_crc != actual_crc: raise CRCMismatchError return data[:-4]
import struct from zlib import crc32 class CRCMismatchError(RuntimeError): """ Error raised when a datagram has an invalid CRC. """ pass class FrameError(RuntimeError): """ Error raised when a datagram is too short to be valid. """ END = b'\xC0' ESC = b'\xDB' ESC_END = b'\xDC' ESC_ESC = b'\xDD' def datagram_encode(data): """ Encodes the given datagram (bytes object) by adding a CRC at the end then an end marker. It also escapes the end marker correctly. """ # to generate same numeric value for all python versions crc = crc32(data) & 0xffffffff data = data + struct.pack('>I', crc) data = data.replace(ESC, ESC + ESC_ESC) data = data.replace(END, ESC + ESC_END) return data + END def datagram_decode(data): """ Decodes a datagram. Exact inverse of datagram_encode() """ # Checks if the data is at least long enough for the CRC and the END marker if len(data) < 5: raise FrameError data = data[:-1] # remote end marker data = data.replace(ESC + ESC_END, END) data = data.replace(ESC + ESC_ESC, ESC) expected_crc = struct.unpack('>I', data[-4:])[0] actual_crc = crc32(data[:-4]) if expected_crc != actual_crc: raise CRCMismatchError return data[:-4]
Correct crc32 behaviour for all python versions.
Correct crc32 behaviour for all python versions. This fixes signedness issue with crc32 from different python versions. Was suggested in the documentation: https://docs.python.org/3.4/library/zlib.html
Python
bsd-2-clause
cvra/can-bootloader,cvra/can-bootloader,cvra/can-bootloader,cvra/can-bootloader
python
## Code Before: import struct from zlib import crc32 class CRCMismatchError(RuntimeError): """ Error raised when a datagram has an invalid CRC. """ pass class FrameError(RuntimeError): """ Error raised when a datagram is too short to be valid. """ END = b'\xC0' ESC = b'\xDB' ESC_END = b'\xDC' ESC_ESC = b'\xDD' def datagram_encode(data): """ Encodes the given datagram (bytes object) by adding a CRC at the end then an end marker. It also escapes the end marker correctly. """ data = data + struct.pack('>I', crc32(data)) data = data.replace(ESC, ESC + ESC_ESC) data = data.replace(END, ESC + ESC_END) return data + END def datagram_decode(data): """ Decodes a datagram. Exact inverse of datagram_encode() """ # Checks if the data is at least long enough for the CRC and the END marker if len(data) < 5: raise FrameError data = data[:-1] # remote end marker data = data.replace(ESC + ESC_END, END) data = data.replace(ESC + ESC_ESC, ESC) expected_crc = struct.unpack('>I', data[-4:])[0] actual_crc = crc32(data[:-4]) if expected_crc != actual_crc: raise CRCMismatchError return data[:-4] ## Instruction: Correct crc32 behaviour for all python versions. This fixes signedness issue with crc32 from different python versions. Was suggested in the documentation: https://docs.python.org/3.4/library/zlib.html ## Code After: import struct from zlib import crc32 class CRCMismatchError(RuntimeError): """ Error raised when a datagram has an invalid CRC. """ pass class FrameError(RuntimeError): """ Error raised when a datagram is too short to be valid. """ END = b'\xC0' ESC = b'\xDB' ESC_END = b'\xDC' ESC_ESC = b'\xDD' def datagram_encode(data): """ Encodes the given datagram (bytes object) by adding a CRC at the end then an end marker. It also escapes the end marker correctly. """ # to generate same numeric value for all python versions crc = crc32(data) & 0xffffffff data = data + struct.pack('>I', crc) data = data.replace(ESC, ESC + ESC_ESC) data = data.replace(END, ESC + ESC_END) return data + END def datagram_decode(data): """ Decodes a datagram. Exact inverse of datagram_encode() """ # Checks if the data is at least long enough for the CRC and the END marker if len(data) < 5: raise FrameError data = data[:-1] # remote end marker data = data.replace(ESC + ESC_END, END) data = data.replace(ESC + ESC_ESC, ESC) expected_crc = struct.unpack('>I', data[-4:])[0] actual_crc = crc32(data[:-4]) if expected_crc != actual_crc: raise CRCMismatchError return data[:-4]
# ... existing code ... Encodes the given datagram (bytes object) by adding a CRC at the end then an end marker. It also escapes the end marker correctly. """ # to generate same numeric value for all python versions crc = crc32(data) & 0xffffffff data = data + struct.pack('>I', crc) data = data.replace(ESC, ESC + ESC_ESC) data = data.replace(END, ESC + ESC_END) return data + END # ... rest of the code ...
dbbd29a1cdfcd3f11a968c0aeb38bd54ef7014e3
gfusion/tests/test_main.py
gfusion/tests/test_main.py
"""Tests for main.py""" from ..main import _solve_weight_vector import numpy as np from nose.tools import assert_raises, assert_equal, assert_true def test_solve_weight_vector(): # smoke test n_nodes = 4 n_communities = 2 n_similarities = 3 delta = 0.3 similarities = np.random.random((n_similarities, n_nodes * (n_nodes-1)/2)) * 10 grouping_matrix = np.random.random((n_nodes, n_communities)) weight = _solve_weight_vector(similarities, grouping_matrix, delta) assert_equal(weight.ndim, 2) assert_equal(weight.shape[1], n_similarities) assert_true(np.all(weight >= 0)) # check raises assert_raises(ValueError, _solve_weight_vector, similarities, grouping_matrix, -1) similarities_invalid = similarities.copy() similarities_invalid[0, 3] = -4. assert_raises(ValueError, _solve_weight_vector, similarities_invalid, grouping_matrix, delta)
"""Tests for main.py""" from ..main import _solve_weight_vector import numpy as np from numpy.testing import assert_array_almost_equal from nose.tools import assert_raises, assert_equal, assert_true def test_solve_weight_vector(): # smoke test n_nodes = 4 n_communities = 2 n_similarities = 3 delta = 0.3 similarities = np.random.random((n_similarities, n_nodes * (n_nodes-1)/2)) * 10 grouping_matrix = np.random.random((n_nodes, n_communities)) weight = _solve_weight_vector(similarities, grouping_matrix, delta) assert_equal(weight.ndim, 2) assert_equal(weight.shape[1], n_similarities) assert_true(np.all(weight >= 0)) # check raises assert_raises(ValueError, _solve_weight_vector, similarities, grouping_matrix, -1) similarities_invalid = similarities.copy() similarities_invalid[0, 3] = -4. assert_raises(ValueError, _solve_weight_vector, similarities_invalid, grouping_matrix, delta) # if I have two similarities, and one is null + the grouping matrix is all # to all, and delta is 0 (no regularization), then I expect that the weight # vector is [1, 0] similarities = np.vstack((1000*np.ones((1, 6)), np.zeros((1, 6)) )) grouping_matrix = np.ones((4, 4)) delta = 1 assert_array_almost_equal(np.atleast_2d([1., 0.]), _solve_weight_vector(similarities, grouping_matrix, delta))
Add a more semantic test
Add a more semantic test
Python
mit
mvdoc/gfusion
python
## Code Before: """Tests for main.py""" from ..main import _solve_weight_vector import numpy as np from nose.tools import assert_raises, assert_equal, assert_true def test_solve_weight_vector(): # smoke test n_nodes = 4 n_communities = 2 n_similarities = 3 delta = 0.3 similarities = np.random.random((n_similarities, n_nodes * (n_nodes-1)/2)) * 10 grouping_matrix = np.random.random((n_nodes, n_communities)) weight = _solve_weight_vector(similarities, grouping_matrix, delta) assert_equal(weight.ndim, 2) assert_equal(weight.shape[1], n_similarities) assert_true(np.all(weight >= 0)) # check raises assert_raises(ValueError, _solve_weight_vector, similarities, grouping_matrix, -1) similarities_invalid = similarities.copy() similarities_invalid[0, 3] = -4. assert_raises(ValueError, _solve_weight_vector, similarities_invalid, grouping_matrix, delta) ## Instruction: Add a more semantic test ## Code After: """Tests for main.py""" from ..main import _solve_weight_vector import numpy as np from numpy.testing import assert_array_almost_equal from nose.tools import assert_raises, assert_equal, assert_true def test_solve_weight_vector(): # smoke test n_nodes = 4 n_communities = 2 n_similarities = 3 delta = 0.3 similarities = np.random.random((n_similarities, n_nodes * (n_nodes-1)/2)) * 10 grouping_matrix = np.random.random((n_nodes, n_communities)) weight = _solve_weight_vector(similarities, grouping_matrix, delta) assert_equal(weight.ndim, 2) assert_equal(weight.shape[1], n_similarities) assert_true(np.all(weight >= 0)) # check raises assert_raises(ValueError, _solve_weight_vector, similarities, grouping_matrix, -1) similarities_invalid = similarities.copy() similarities_invalid[0, 3] = -4. assert_raises(ValueError, _solve_weight_vector, similarities_invalid, grouping_matrix, delta) # if I have two similarities, and one is null + the grouping matrix is all # to all, and delta is 0 (no regularization), then I expect that the weight # vector is [1, 0] similarities = np.vstack((1000*np.ones((1, 6)), np.zeros((1, 6)) )) grouping_matrix = np.ones((4, 4)) delta = 1 assert_array_almost_equal(np.atleast_2d([1., 0.]), _solve_weight_vector(similarities, grouping_matrix, delta))
... """Tests for main.py""" from ..main import _solve_weight_vector import numpy as np from numpy.testing import assert_array_almost_equal from nose.tools import assert_raises, assert_equal, assert_true ... assert_raises(ValueError, _solve_weight_vector, similarities_invalid, grouping_matrix, delta) # if I have two similarities, and one is null + the grouping matrix is all # to all, and delta is 0 (no regularization), then I expect that the weight # vector is [1, 0] similarities = np.vstack((1000*np.ones((1, 6)), np.zeros((1, 6)) )) grouping_matrix = np.ones((4, 4)) delta = 1 assert_array_almost_equal(np.atleast_2d([1., 0.]), _solve_weight_vector(similarities, grouping_matrix, delta)) ...
1776b4704a26b3cf388e66e2e9f945dde1ba57cb
src/clock_posix.c
src/clock_posix.c
extern int clock_init(struct SPDR_Clock **clockp, struct SPDR_Allocator *allocator) { struct timespec res; if (clock_getres(CLOCK_MONOTONIC, &res) != 0 || res.tv_nsec > 1000) { /* unknown clock or insufficient resolution */ return -1; } return clock_init_base(clockp, allocator, 1, 1000); } extern uint64_t clock_ticks(struct SPDR_Clock const *const clock) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); (void)clock; return ts.tv_sec * 1000000000LL + ts.tv_nsec; }
extern int clock_init(struct SPDR_Clock **clockp, struct SPDR_Allocator *allocator) { struct timespec res; if (clock_getres(CLOCK_MONOTONIC, &res) != 0 || res.tv_nsec > 1000) { /* unknown clock or insufficient resolution */ return -1; } return clock_init_base(clockp, allocator, 1, 1000); } extern uint64_t clock_ticks(struct SPDR_Clock const *const clock) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); (void)clock; return ts.tv_sec * 1000000000LL + ts.tv_nsec; }
Fix signature of clock_init for posix
Fix signature of clock_init for posix
C
mit
uucidl/uu.spdr,uucidl/uu.spdr,uucidl/uu.spdr
c
## Code Before: extern int clock_init(struct SPDR_Clock **clockp, struct SPDR_Allocator *allocator) { struct timespec res; if (clock_getres(CLOCK_MONOTONIC, &res) != 0 || res.tv_nsec > 1000) { /* unknown clock or insufficient resolution */ return -1; } return clock_init_base(clockp, allocator, 1, 1000); } extern uint64_t clock_ticks(struct SPDR_Clock const *const clock) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); (void)clock; return ts.tv_sec * 1000000000LL + ts.tv_nsec; } ## Instruction: Fix signature of clock_init for posix ## Code After: extern int clock_init(struct SPDR_Clock **clockp, struct SPDR_Allocator *allocator) { struct timespec res; if (clock_getres(CLOCK_MONOTONIC, &res) != 0 || res.tv_nsec > 1000) { /* unknown clock or insufficient resolution */ return -1; } return clock_init_base(clockp, allocator, 1, 1000); } extern uint64_t clock_ticks(struct SPDR_Clock const *const clock) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); (void)clock; return ts.tv_sec * 1000000000LL + ts.tv_nsec; }
# ... existing code ... extern int clock_init(struct SPDR_Clock **clockp, struct SPDR_Allocator *allocator) { struct timespec res; # ... rest of the code ...
1edd6ee6b71b3f3ac9654cc47804592613dd61ec
clowder/clowder/cli/init_controller.py
clowder/clowder/cli/init_controller.py
from cement.ext.ext_argparse import expose from clowder.cli.abstract_base_controller import AbstractBaseController class InitController(AbstractBaseController): class Meta: label = 'init' stacked_on = 'base' stacked_type = 'nested' description = 'Clone repository to clowder directory and create clowder.yaml symlink' arguments = [ (['url'], dict(metavar='URL', help='url of repo containing clowder.yaml')), (['--branch', '-b'], dict(nargs=1, metavar='BRANCH', help='branch of repo containing clowder.yaml')) ] @expose(help="second-controller default command", hide=True) def default(self): print("Inside SecondController.default()")
import sys from cement.ext.ext_argparse import expose from termcolor import colored, cprint from clowder.cli.abstract_base_controller import AbstractBaseController from clowder.util.decorators import network_connection_required class InitController(AbstractBaseController): class Meta: label = 'init' stacked_on = 'base' stacked_type = 'nested' description = 'Clone repository to clowder directory and create clowder.yaml symlink' arguments = [ (['url'], dict(metavar='URL', help='url of repo containing clowder.yaml')), (['--branch', '-b'], dict(nargs=1, metavar='BRANCH', help='branch of repo containing clowder.yaml')) ] @expose(help="second-controller default command", hide=True) @network_connection_required def default(self): if self.clowder_repo: cprint('Clowder already initialized in this directory\n', 'red') sys.exit(1) url_output = colored(self.app.pargs.url, 'green') print('Create clowder repo from ' + url_output + '\n') if self.app.pargs.branch is None: branch = 'master' else: branch = str(self.app.pargs.branch[0]) self.clowder_repo.init(self.app.pargs.url, branch)
Add `clowder init` logic to Cement controller
Add `clowder init` logic to Cement controller
Python
mit
JrGoodle/clowder,JrGoodle/clowder,JrGoodle/clowder
python
## Code Before: from cement.ext.ext_argparse import expose from clowder.cli.abstract_base_controller import AbstractBaseController class InitController(AbstractBaseController): class Meta: label = 'init' stacked_on = 'base' stacked_type = 'nested' description = 'Clone repository to clowder directory and create clowder.yaml symlink' arguments = [ (['url'], dict(metavar='URL', help='url of repo containing clowder.yaml')), (['--branch', '-b'], dict(nargs=1, metavar='BRANCH', help='branch of repo containing clowder.yaml')) ] @expose(help="second-controller default command", hide=True) def default(self): print("Inside SecondController.default()") ## Instruction: Add `clowder init` logic to Cement controller ## Code After: import sys from cement.ext.ext_argparse import expose from termcolor import colored, cprint from clowder.cli.abstract_base_controller import AbstractBaseController from clowder.util.decorators import network_connection_required class InitController(AbstractBaseController): class Meta: label = 'init' stacked_on = 'base' stacked_type = 'nested' description = 'Clone repository to clowder directory and create clowder.yaml symlink' arguments = [ (['url'], dict(metavar='URL', help='url of repo containing clowder.yaml')), (['--branch', '-b'], dict(nargs=1, metavar='BRANCH', help='branch of repo containing clowder.yaml')) ] @expose(help="second-controller default command", hide=True) @network_connection_required def default(self): if self.clowder_repo: cprint('Clowder already initialized in this directory\n', 'red') sys.exit(1) url_output = colored(self.app.pargs.url, 'green') print('Create clowder repo from ' + url_output + '\n') if self.app.pargs.branch is None: branch = 'master' else: branch = str(self.app.pargs.branch[0]) self.clowder_repo.init(self.app.pargs.url, branch)
... import sys from cement.ext.ext_argparse import expose from termcolor import colored, cprint from clowder.cli.abstract_base_controller import AbstractBaseController from clowder.util.decorators import network_connection_required class InitController(AbstractBaseController): ... ] @expose(help="second-controller default command", hide=True) @network_connection_required def default(self): if self.clowder_repo: cprint('Clowder already initialized in this directory\n', 'red') sys.exit(1) url_output = colored(self.app.pargs.url, 'green') print('Create clowder repo from ' + url_output + '\n') if self.app.pargs.branch is None: branch = 'master' else: branch = str(self.app.pargs.branch[0]) self.clowder_repo.init(self.app.pargs.url, branch) ...
75e972693c3cc1d0fc39ff4ae0af62dc34ec3694
src/main/java/valandur/webapi/servlet/registry/RegistryServlet.java
src/main/java/valandur/webapi/servlet/registry/RegistryServlet.java
package valandur.webapi.servlet.registry; import org.eclipse.jetty.http.HttpMethod; import org.spongepowered.api.CatalogType; import org.spongepowered.api.Sponge; import valandur.webapi.api.annotation.WebAPIEndpoint; import valandur.webapi.api.annotation.WebAPIServlet; import valandur.webapi.api.servlet.WebAPIBaseServlet; import valandur.webapi.servlet.ServletData; import javax.servlet.http.HttpServletResponse; import java.util.Collection; @WebAPIServlet(basePath = "registry") public class RegistryServlet extends WebAPIBaseServlet { @WebAPIEndpoint(method = HttpMethod.GET, path = "/:class", perm = "one") public void getRegistry(ServletData data, String className) { try { Class type = Class.forName(className); if (!CatalogType.class.isAssignableFrom(type)) { data.sendError(HttpServletResponse.SC_BAD_REQUEST, "Class must be a CatalogType"); return; } Collection<CatalogType> types = Sponge.getRegistry().getAllOf(type); data.addJson("types", types, false); } catch (ClassNotFoundException e) { data.sendError(HttpServletResponse.SC_NOT_FOUND, "Class " + className + " could not be found"); } } }
package valandur.webapi.servlet.registry; import org.eclipse.jetty.http.HttpMethod; import org.spongepowered.api.CatalogType; import org.spongepowered.api.Sponge; import valandur.webapi.api.annotation.WebAPIEndpoint; import valandur.webapi.api.annotation.WebAPIServlet; import valandur.webapi.api.servlet.WebAPIBaseServlet; import valandur.webapi.servlet.ServletData; import javax.servlet.http.HttpServletResponse; import java.util.Collection; @WebAPIServlet(basePath = "registry") public class RegistryServlet extends WebAPIBaseServlet { @WebAPIEndpoint(method = HttpMethod.GET, path = "/:class", perm = "one") public void getRegistry(ServletData data, String className) { try { Class type = Class.forName(className); if (!CatalogType.class.isAssignableFrom(type)) { data.sendError(HttpServletResponse.SC_BAD_REQUEST, "Class must be a CatalogType"); return; } Collection<CatalogType> types = Sponge.getRegistry().getAllOf(type); data.addJson("ok", true, false); data.addJson("types", types, false); } catch (ClassNotFoundException e) { data.sendError(HttpServletResponse.SC_NOT_FOUND, "Class " + className + " could not be found"); } } }
Return "ok" field in json response
fix(registry): Return "ok" field in json response
Java
mit
Valandur/Web-API,Valandur/Web-API,Valandur/Web-API
java
## Code Before: package valandur.webapi.servlet.registry; import org.eclipse.jetty.http.HttpMethod; import org.spongepowered.api.CatalogType; import org.spongepowered.api.Sponge; import valandur.webapi.api.annotation.WebAPIEndpoint; import valandur.webapi.api.annotation.WebAPIServlet; import valandur.webapi.api.servlet.WebAPIBaseServlet; import valandur.webapi.servlet.ServletData; import javax.servlet.http.HttpServletResponse; import java.util.Collection; @WebAPIServlet(basePath = "registry") public class RegistryServlet extends WebAPIBaseServlet { @WebAPIEndpoint(method = HttpMethod.GET, path = "/:class", perm = "one") public void getRegistry(ServletData data, String className) { try { Class type = Class.forName(className); if (!CatalogType.class.isAssignableFrom(type)) { data.sendError(HttpServletResponse.SC_BAD_REQUEST, "Class must be a CatalogType"); return; } Collection<CatalogType> types = Sponge.getRegistry().getAllOf(type); data.addJson("types", types, false); } catch (ClassNotFoundException e) { data.sendError(HttpServletResponse.SC_NOT_FOUND, "Class " + className + " could not be found"); } } } ## Instruction: fix(registry): Return "ok" field in json response ## Code After: package valandur.webapi.servlet.registry; import org.eclipse.jetty.http.HttpMethod; import org.spongepowered.api.CatalogType; import org.spongepowered.api.Sponge; import valandur.webapi.api.annotation.WebAPIEndpoint; import valandur.webapi.api.annotation.WebAPIServlet; import valandur.webapi.api.servlet.WebAPIBaseServlet; import valandur.webapi.servlet.ServletData; import javax.servlet.http.HttpServletResponse; import java.util.Collection; @WebAPIServlet(basePath = "registry") public class RegistryServlet extends WebAPIBaseServlet { @WebAPIEndpoint(method = HttpMethod.GET, path = "/:class", perm = "one") public void getRegistry(ServletData data, String className) { try { Class type = Class.forName(className); if (!CatalogType.class.isAssignableFrom(type)) { data.sendError(HttpServletResponse.SC_BAD_REQUEST, "Class must be a CatalogType"); return; } Collection<CatalogType> types = Sponge.getRegistry().getAllOf(type); data.addJson("ok", true, false); data.addJson("types", types, false); } catch (ClassNotFoundException e) { data.sendError(HttpServletResponse.SC_NOT_FOUND, "Class " + className + " could not be found"); } } }
# ... existing code ... } Collection<CatalogType> types = Sponge.getRegistry().getAllOf(type); data.addJson("ok", true, false); data.addJson("types", types, false); } catch (ClassNotFoundException e) { data.sendError(HttpServletResponse.SC_NOT_FOUND, "Class " + className + " could not be found"); # ... rest of the code ...
4446de2c5a3f327eb1780dead5970ad4fa4bc5f0
test/CodeGen/2007-06-18-SextAttrAggregate.c
test/CodeGen/2007-06-18-SextAttrAggregate.c
// RUN: %clang_cc1 %s -o - -emit-llvm | FileCheck %s // XFAIL: aarch64, arm64, x86_64-pc-win32, x86_64-w64-mingw32 // PR1513 // AArch64 ABI actually requires the reverse of what this is testing: the callee // does any extensions and remaining bits are unspecified. // Win64 ABI does expect extensions for type smaller than 64bits. // Technically this test wasn't written to test that feature, but it's a // valuable check nevertheless. struct s{ long a; long b; }; void f(struct s a, char *b, signed char C) { // CHECK: i8 signext }
// RUN: %clang_cc1 %s -o - -emit-llvm | FileCheck %s // XFAIL: aarch64, arm64, x86_64-pc-win32, x86_64-w64-mingw32, x86_64-pc-windows-gnu // PR1513 // AArch64 ABI actually requires the reverse of what this is testing: the callee // does any extensions and remaining bits are unspecified. // Win64 ABI does expect extensions for type smaller than 64bits. // Technically this test wasn't written to test that feature, but it's a // valuable check nevertheless. struct s{ long a; long b; }; void f(struct s a, char *b, signed char C) { // CHECK: i8 signext }
Add expected fail triple x86_64-pc-windows-gnu to test as x86_64-w64-mingw32 is already there
Add expected fail triple x86_64-pc-windows-gnu to test as x86_64-w64-mingw32 is already there git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@336047 91177308-0d34-0410-b5e6-96231b3b80d8
C
apache-2.0
apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang
c
## Code Before: // RUN: %clang_cc1 %s -o - -emit-llvm | FileCheck %s // XFAIL: aarch64, arm64, x86_64-pc-win32, x86_64-w64-mingw32 // PR1513 // AArch64 ABI actually requires the reverse of what this is testing: the callee // does any extensions and remaining bits are unspecified. // Win64 ABI does expect extensions for type smaller than 64bits. // Technically this test wasn't written to test that feature, but it's a // valuable check nevertheless. struct s{ long a; long b; }; void f(struct s a, char *b, signed char C) { // CHECK: i8 signext } ## Instruction: Add expected fail triple x86_64-pc-windows-gnu to test as x86_64-w64-mingw32 is already there git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@336047 91177308-0d34-0410-b5e6-96231b3b80d8 ## Code After: // RUN: %clang_cc1 %s -o - -emit-llvm | FileCheck %s // XFAIL: aarch64, arm64, x86_64-pc-win32, x86_64-w64-mingw32, x86_64-pc-windows-gnu // PR1513 // AArch64 ABI actually requires the reverse of what this is testing: the callee // does any extensions and remaining bits are unspecified. // Win64 ABI does expect extensions for type smaller than 64bits. // Technically this test wasn't written to test that feature, but it's a // valuable check nevertheless. struct s{ long a; long b; }; void f(struct s a, char *b, signed char C) { // CHECK: i8 signext }
... // RUN: %clang_cc1 %s -o - -emit-llvm | FileCheck %s // XFAIL: aarch64, arm64, x86_64-pc-win32, x86_64-w64-mingw32, x86_64-pc-windows-gnu // PR1513 ...
3fe23451ac6b2face3c534e19b2508568d31655a
dspace/modules/dryad-rest-webapp/src/main/java/org/datadryad/rest/storage/resolvers/OrganizationStorageResolver.java
dspace/modules/dryad-rest-webapp/src/main/java/org/datadryad/rest/storage/resolvers/OrganizationStorageResolver.java
/* */ package org.datadryad.rest.storage.resolvers; import org.datadryad.rest.storage.rdbms.DatabaseOrganizationStorageImpl; import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider; import java.io.File; import javax.ws.rs.core.Context; import javax.ws.rs.ext.Provider; import org.datadryad.rest.storage.AbstractOrganizationStorage; import org.datadryad.rest.storage.json.OrganizationJSONStorageImpl; /** * * @author Dan Leehr <[email protected]> */ @Provider public class OrganizationStorageResolver extends SingletonTypeInjectableProvider<Context, AbstractOrganizationStorage> { private static final String PATH = "/tmp/dryad_rest"; public OrganizationStorageResolver() { super(AbstractOrganizationStorage.class, new OrganizationJSONStorageImpl(new File(PATH))); File directory = new File(PATH); if(!directory.exists()) { directory.mkdir(); } } }
/* */ package org.datadryad.rest.storage.resolvers; import org.datadryad.rest.storage.rdbms.DatabaseOrganizationStorageImpl; import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider; import javax.ws.rs.core.Context; import javax.ws.rs.ext.Provider; import org.datadryad.rest.storage.AbstractOrganizationStorage; /** * * @author Dan Leehr <[email protected]> */ @Provider public class OrganizationStorageResolver extends SingletonTypeInjectableProvider<Context, AbstractOrganizationStorage> { public OrganizationStorageResolver() { super(AbstractOrganizationStorage.class, new DatabaseOrganizationStorageImpl("/opt/dryad/config/dspace.cfg")); } }
Revert "Switched organization storage back to JSON"
Revert "Switched organization storage back to JSON" This reverts commit 0a1fcfbea514419bd72bfda0c37cd57479e1b491.
Java
bsd-3-clause
ojacobson/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,jamie-dryad/dryad-repo,rnathanday/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,jimallman/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo
java
## Code Before: /* */ package org.datadryad.rest.storage.resolvers; import org.datadryad.rest.storage.rdbms.DatabaseOrganizationStorageImpl; import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider; import java.io.File; import javax.ws.rs.core.Context; import javax.ws.rs.ext.Provider; import org.datadryad.rest.storage.AbstractOrganizationStorage; import org.datadryad.rest.storage.json.OrganizationJSONStorageImpl; /** * * @author Dan Leehr <[email protected]> */ @Provider public class OrganizationStorageResolver extends SingletonTypeInjectableProvider<Context, AbstractOrganizationStorage> { private static final String PATH = "/tmp/dryad_rest"; public OrganizationStorageResolver() { super(AbstractOrganizationStorage.class, new OrganizationJSONStorageImpl(new File(PATH))); File directory = new File(PATH); if(!directory.exists()) { directory.mkdir(); } } } ## Instruction: Revert "Switched organization storage back to JSON" This reverts commit 0a1fcfbea514419bd72bfda0c37cd57479e1b491. ## Code After: /* */ package org.datadryad.rest.storage.resolvers; import org.datadryad.rest.storage.rdbms.DatabaseOrganizationStorageImpl; import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider; import javax.ws.rs.core.Context; import javax.ws.rs.ext.Provider; import org.datadryad.rest.storage.AbstractOrganizationStorage; /** * * @author Dan Leehr <[email protected]> */ @Provider public class OrganizationStorageResolver extends SingletonTypeInjectableProvider<Context, AbstractOrganizationStorage> { public OrganizationStorageResolver() { super(AbstractOrganizationStorage.class, new DatabaseOrganizationStorageImpl("/opt/dryad/config/dspace.cfg")); } }
// ... existing code ... import org.datadryad.rest.storage.rdbms.DatabaseOrganizationStorageImpl; import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider; import javax.ws.rs.core.Context; import javax.ws.rs.ext.Provider; import org.datadryad.rest.storage.AbstractOrganizationStorage; /** * // ... modified code ... */ @Provider public class OrganizationStorageResolver extends SingletonTypeInjectableProvider<Context, AbstractOrganizationStorage> { public OrganizationStorageResolver() { super(AbstractOrganizationStorage.class, new DatabaseOrganizationStorageImpl("/opt/dryad/config/dspace.cfg")); } } // ... rest of the code ...
9921b6bd73c5256a3b65c2a5106717ce0fc8f0cf
djangorestframework/utils/breadcrumbs.py
djangorestframework/utils/breadcrumbs.py
from django.core.urlresolvers import resolve def get_breadcrumbs(url): """Given a url returns a list of breadcrumbs, which are each a tuple of (name, url).""" from djangorestframework.views import APIView def breadcrumbs_recursive(url, breadcrumbs_list): """Add tuples of (name, url) to the breadcrumbs list, progressively chomping off parts of the url.""" try: (view, unused_args, unused_kwargs) = resolve(url) except Exception: pass else: # Check if this is a REST framework view, and if so add it to the breadcrumbs if isinstance(getattr(view, 'cls_instance', None), APIView): breadcrumbs_list.insert(0, (view.cls_instance.get_name(), url)) if url == '': # All done return breadcrumbs_list elif url.endswith('/'): # Drop trailing slash off the end and continue to try to resolve more breadcrumbs return breadcrumbs_recursive(url.rstrip('/'), breadcrumbs_list) # Drop trailing non-slash off the end and continue to try to resolve more breadcrumbs return breadcrumbs_recursive(url[:url.rfind('/') + 1], breadcrumbs_list) return breadcrumbs_recursive(url, [])
from django.core.urlresolvers import resolve, get_script_prefix def get_breadcrumbs(url): """Given a url returns a list of breadcrumbs, which are each a tuple of (name, url).""" from djangorestframework.views import APIView def breadcrumbs_recursive(url, breadcrumbs_list, prefix): """Add tuples of (name, url) to the breadcrumbs list, progressively chomping off parts of the url.""" try: (view, unused_args, unused_kwargs) = resolve(url) except Exception: pass else: # Check if this is a REST framework view, and if so add it to the breadcrumbs if isinstance(getattr(view, 'cls_instance', None), APIView): breadcrumbs_list.insert(0, (view.cls_instance.get_name(), prefix + url)) if url == '': # All done return breadcrumbs_list elif url.endswith('/'): # Drop trailing slash off the end and continue to try to resolve more breadcrumbs return breadcrumbs_recursive(url.rstrip('/'), breadcrumbs_list, prefix) # Drop trailing non-slash off the end and continue to try to resolve more breadcrumbs return breadcrumbs_recursive(url[:url.rfind('/') + 1], breadcrumbs_list, prefix) prefix = get_script_prefix() url = url[len(prefix):] return breadcrumbs_recursive(url, [], prefix)
Use get_script_prefix to play nicely if not installed at the root.
Use get_script_prefix to play nicely if not installed at the root.
Python
bsd-2-clause
rafaelcaricio/django-rest-framework,maryokhin/django-rest-framework,jtiai/django-rest-framework,cheif/django-rest-framework,vstoykov/django-rest-framework,wwj718/django-rest-framework,ebsaral/django-rest-framework,jpadilla/django-rest-framework,damycra/django-rest-framework,kezabelle/django-rest-framework,cyberj/django-rest-framework,hnarayanan/django-rest-framework,kgeorgy/django-rest-framework,antonyc/django-rest-framework,lubomir/django-rest-framework,ambivalentno/django-rest-framework,potpath/django-rest-framework,ashishfinoit/django-rest-framework,waytai/django-rest-framework,nhorelik/django-rest-framework,iheitlager/django-rest-framework,rubendura/django-rest-framework,aericson/django-rest-framework,rubendura/django-rest-framework,uploadcare/django-rest-framework,atombrella/django-rest-framework,krinart/django-rest-framework,HireAnEsquire/django-rest-framework,gregmuellegger/django-rest-framework,thedrow/django-rest-framework-1,mgaitan/django-rest-framework,hnakamur/django-rest-framework,callorico/django-rest-framework,hnakamur/django-rest-framework,tigeraniya/django-rest-framework,douwevandermeij/django-rest-framework,dmwyatt/django-rest-framework,agconti/django-rest-framework,canassa/django-rest-framework,johnraz/django-rest-framework,linovia/django-rest-framework,wwj718/django-rest-framework,brandoncazander/django-rest-framework,canassa/django-rest-framework,ashishfinoit/django-rest-framework,agconti/django-rest-framework,krinart/django-rest-framework,xiaotangyuan/django-rest-framework,cyberj/django-rest-framework,uruz/django-rest-framework,akalipetis/django-rest-framework,tcroiset/django-rest-framework,buptlsl/django-rest-framework,d0ugal/django-rest-framework,kgeorgy/django-rest-framework,vstoykov/django-rest-framework,thedrow/django-rest-framework-1,jerryhebert/django-rest-framework,delinhabit/django-rest-framework,davesque/django-rest-framework,potpath/django-rest-framework,kennydude/django-rest-framework,qsorix/django-rest-framework,uploadcare/django-rest-framework,ebsaral/django-rest-framework,jness/django-rest-framework,MJafarMashhadi/django-rest-framework,tcroiset/django-rest-framework,adambain-vokal/django-rest-framework,johnraz/django-rest-framework,mgaitan/django-rest-framework,wedaly/django-rest-framework,sheppard/django-rest-framework,uploadcare/django-rest-framework,rhblind/django-rest-framework,sehmaschine/django-rest-framework,sbellem/django-rest-framework,arpheno/django-rest-framework,rafaelang/django-rest-framework,bluedazzle/django-rest-framework,jtiai/django-rest-framework,antonyc/django-rest-framework,ajaali/django-rest-framework,rhblind/django-rest-framework,ebsaral/django-rest-framework,akalipetis/django-rest-framework,buptlsl/django-rest-framework,potpath/django-rest-framework,xiaotangyuan/django-rest-framework,jerryhebert/django-rest-framework,douwevandermeij/django-rest-framework,qsorix/django-rest-framework,callorico/django-rest-framework,sbellem/django-rest-framework,sehmaschine/django-rest-framework,elim/django-rest-framework,akalipetis/django-rest-framework,kylefox/django-rest-framework,adambain-vokal/django-rest-framework,maryokhin/django-rest-framework,fishky/django-rest-framework,werthen/django-rest-framework,simudream/django-rest-framework,delinhabit/django-rest-framework,aericson/django-rest-framework,abdulhaq-e/django-rest-framework,simudream/django-rest-framework,paolopaolopaolo/django-rest-framework,jpulec/django-rest-framework,James1345/django-rest-framework,fishky/django-rest-framework,ajaali/django-rest-framework,ashishfinoit/django-rest-framework,alacritythief/django-rest-framework,ticosax/django-rest-framework,cheif/django-rest-framework,wedaly/django-rest-framework,callorico/django-rest-framework,YBJAY00000/django-rest-framework,mgaitan/django-rest-framework,YBJAY00000/django-rest-framework,wzbozon/django-rest-framework,bluedazzle/django-rest-framework,elim/django-rest-framework,kylefox/django-rest-framework,alacritythief/django-rest-framework,kennydude/django-rest-framework,hunter007/django-rest-framework,abdulhaq-e/django-rest-framework,leeahoward/django-rest-framework,damycra/django-rest-framework,andriy-s/django-rest-framework,waytai/django-rest-framework,aericson/django-rest-framework,leeahoward/django-rest-framework,wzbozon/django-rest-framework,wangpanjun/django-rest-framework,tcroiset/django-rest-framework,bluedazzle/django-rest-framework,jness/django-rest-framework,tigeraniya/django-rest-framework,andriy-s/django-rest-framework,hnakamur/django-rest-framework,rhblind/django-rest-framework,nryoung/django-rest-framework,edx/django-rest-framework,AlexandreProenca/django-rest-framework,simudream/django-rest-framework,nhorelik/django-rest-framework,krinart/django-rest-framework,wangpanjun/django-rest-framework,davesque/django-rest-framework,ticosax/django-rest-framework,jpulec/django-rest-framework,hunter007/django-rest-framework,jpulec/django-rest-framework,maryokhin/django-rest-framework,iheitlager/django-rest-framework,rafaelcaricio/django-rest-framework,yiyocx/django-rest-framework,jpadilla/django-rest-framework,jerryhebert/django-rest-framework,ezheidtmann/django-rest-framework,waytai/django-rest-framework,tomchristie/django-rest-framework,gregmuellegger/django-rest-framework,wzbozon/django-rest-framework,James1345/django-rest-framework,werthen/django-rest-framework,atombrella/django-rest-framework,pombredanne/django-rest-framework,adambain-vokal/django-rest-framework,paolopaolopaolo/django-rest-framework,gregmuellegger/django-rest-framework,qsorix/django-rest-framework,raphaelmerx/django-rest-framework,dmwyatt/django-rest-framework,brandoncazander/django-rest-framework,xiaotangyuan/django-rest-framework,AlexandreProenca/django-rest-framework,werthen/django-rest-framework,kgeorgy/django-rest-framework,hnarayanan/django-rest-framework,jpadilla/django-rest-framework,ajaali/django-rest-framework,kylefox/django-rest-framework,ossanna16/django-rest-framework,justanr/django-rest-framework,pombredanne/django-rest-framework,YBJAY00000/django-rest-framework,atombrella/django-rest-framework,kezabelle/django-rest-framework,James1345/django-rest-framework,MJafarMashhadi/django-rest-framework,iheitlager/django-rest-framework,wangpanjun/django-rest-framework,ticosax/django-rest-framework,edx/django-rest-framework,d0ugal/django-rest-framework,rubendura/django-rest-framework,HireAnEsquire/django-rest-framework,cheif/django-rest-framework,nryoung/django-rest-framework,AlexandreProenca/django-rest-framework,brandoncazander/django-rest-framework,arpheno/django-rest-framework,MJafarMashhadi/django-rest-framework,raphaelmerx/django-rest-framework,kennydude/django-rest-framework,nryoung/django-rest-framework,lubomir/django-rest-framework,ossanna16/django-rest-framework,thedrow/django-rest-framework-1,justanr/django-rest-framework,buptlsl/django-rest-framework,lubomir/django-rest-framework,vstoykov/django-rest-framework,zeldalink0515/django-rest-framework,raphaelmerx/django-rest-framework,damycra/django-rest-framework,ambivalentno/django-rest-framework,nhorelik/django-rest-framework,VishvajitP/django-rest-framework,kezabelle/django-rest-framework,sheppard/django-rest-framework,leeahoward/django-rest-framework,dmwyatt/django-rest-framework,wedaly/django-rest-framework,justanr/django-rest-framework,uruz/django-rest-framework,delinhabit/django-rest-framework,tomchristie/django-rest-framework,VishvajitP/django-rest-framework,canassa/django-rest-framework,rafaelang/django-rest-framework,andriy-s/django-rest-framework,hunter007/django-rest-framework,paolopaolopaolo/django-rest-framework,hnarayanan/django-rest-framework,HireAnEsquire/django-rest-framework,abdulhaq-e/django-rest-framework,jness/django-rest-framework,douwevandermeij/django-rest-framework,pombredanne/django-rest-framework,ossanna16/django-rest-framework,linovia/django-rest-framework,cyberj/django-rest-framework,wwj718/django-rest-framework,d0ugal/django-rest-framework,sheppard/django-rest-framework,sehmaschine/django-rest-framework,tigeraniya/django-rest-framework,linovia/django-rest-framework,zeldalink0515/django-rest-framework,alacritythief/django-rest-framework,uruz/django-rest-framework,VishvajitP/django-rest-framework,ambivalentno/django-rest-framework,fishky/django-rest-framework,tomchristie/django-rest-framework,sbellem/django-rest-framework,zeldalink0515/django-rest-framework,arpheno/django-rest-framework,agconti/django-rest-framework,davesque/django-rest-framework,elim/django-rest-framework,jtiai/django-rest-framework,yiyocx/django-rest-framework,yiyocx/django-rest-framework,edx/django-rest-framework,johnraz/django-rest-framework,antonyc/django-rest-framework,ezheidtmann/django-rest-framework,ezheidtmann/django-rest-framework,rafaelcaricio/django-rest-framework,rafaelang/django-rest-framework
python
## Code Before: from django.core.urlresolvers import resolve def get_breadcrumbs(url): """Given a url returns a list of breadcrumbs, which are each a tuple of (name, url).""" from djangorestframework.views import APIView def breadcrumbs_recursive(url, breadcrumbs_list): """Add tuples of (name, url) to the breadcrumbs list, progressively chomping off parts of the url.""" try: (view, unused_args, unused_kwargs) = resolve(url) except Exception: pass else: # Check if this is a REST framework view, and if so add it to the breadcrumbs if isinstance(getattr(view, 'cls_instance', None), APIView): breadcrumbs_list.insert(0, (view.cls_instance.get_name(), url)) if url == '': # All done return breadcrumbs_list elif url.endswith('/'): # Drop trailing slash off the end and continue to try to resolve more breadcrumbs return breadcrumbs_recursive(url.rstrip('/'), breadcrumbs_list) # Drop trailing non-slash off the end and continue to try to resolve more breadcrumbs return breadcrumbs_recursive(url[:url.rfind('/') + 1], breadcrumbs_list) return breadcrumbs_recursive(url, []) ## Instruction: Use get_script_prefix to play nicely if not installed at the root. ## Code After: from django.core.urlresolvers import resolve, get_script_prefix def get_breadcrumbs(url): """Given a url returns a list of breadcrumbs, which are each a tuple of (name, url).""" from djangorestframework.views import APIView def breadcrumbs_recursive(url, breadcrumbs_list, prefix): """Add tuples of (name, url) to the breadcrumbs list, progressively chomping off parts of the url.""" try: (view, unused_args, unused_kwargs) = resolve(url) except Exception: pass else: # Check if this is a REST framework view, and if so add it to the breadcrumbs if isinstance(getattr(view, 'cls_instance', None), APIView): breadcrumbs_list.insert(0, (view.cls_instance.get_name(), prefix + url)) if url == '': # All done return breadcrumbs_list elif url.endswith('/'): # Drop trailing slash off the end and continue to try to resolve more breadcrumbs return breadcrumbs_recursive(url.rstrip('/'), breadcrumbs_list, prefix) # Drop trailing non-slash off the end and continue to try to resolve more breadcrumbs return breadcrumbs_recursive(url[:url.rfind('/') + 1], breadcrumbs_list, prefix) prefix = get_script_prefix() url = url[len(prefix):] return breadcrumbs_recursive(url, [], prefix)
# ... existing code ... from django.core.urlresolvers import resolve, get_script_prefix def get_breadcrumbs(url): # ... modified code ... from djangorestframework.views import APIView def breadcrumbs_recursive(url, breadcrumbs_list, prefix): """Add tuples of (name, url) to the breadcrumbs list, progressively chomping off parts of the url.""" try: ... else: # Check if this is a REST framework view, and if so add it to the breadcrumbs if isinstance(getattr(view, 'cls_instance', None), APIView): breadcrumbs_list.insert(0, (view.cls_instance.get_name(), prefix + url)) if url == '': # All done ... elif url.endswith('/'): # Drop trailing slash off the end and continue to try to resolve more breadcrumbs return breadcrumbs_recursive(url.rstrip('/'), breadcrumbs_list, prefix) # Drop trailing non-slash off the end and continue to try to resolve more breadcrumbs return breadcrumbs_recursive(url[:url.rfind('/') + 1], breadcrumbs_list, prefix) prefix = get_script_prefix() url = url[len(prefix):] return breadcrumbs_recursive(url, [], prefix) # ... rest of the code ...
90c82f0936addeb4469db2c42c1cd48713e7f3cf
progress_logger.py
progress_logger.py
import copy import wash # from http://stackoverflow.com/questions/8924173/how-do-i-print-bold-text-in-python class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' class TermLogger(object): def print_progress(self, lots, text, bold_lots): lots = copy.copy(lots) # so I can re-sort non-destructively print text lots.sort(cmp=wash.cmp_by_buy_date) bold_ids = [id(lot) for lot in bold_lots] for lot in lots: header = '' footer = '' if id(lot) in bold_ids: header = color.BOLD footer = color.END print header + str(lot) + footer raw_input('hit enter>') class NullLogger(object): def print_progress(self, lots, text, bold_lots): pass
import copy import wash # from http://stackoverflow.com/questions/8924173/how-do-i-print-bold-text-in-python class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' class TermLogger(object): def print_progress(self, lots, text, red_lots): lots = copy.copy(lots) # so I can re-sort non-destructively print text lots.sort(cmp=wash.cmp_by_buy_date) red_ids = [id(lot) for lot in red_lots] for lot in lots: header = '' footer = '' if id(lot) in red_ids: header = color.RED footer = color.END print header + str(lot) + footer raw_input('hit enter>') class NullLogger(object): def print_progress(self, lots, text, red_lots): pass
Switch from bold to red highlighting.
Switch from bold to red highlighting. With many terminal fonts bold is subtle. The red is much more clear.
Python
bsd-2-clause
adlr/wash-sale-calculator
python
## Code Before: import copy import wash # from http://stackoverflow.com/questions/8924173/how-do-i-print-bold-text-in-python class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' class TermLogger(object): def print_progress(self, lots, text, bold_lots): lots = copy.copy(lots) # so I can re-sort non-destructively print text lots.sort(cmp=wash.cmp_by_buy_date) bold_ids = [id(lot) for lot in bold_lots] for lot in lots: header = '' footer = '' if id(lot) in bold_ids: header = color.BOLD footer = color.END print header + str(lot) + footer raw_input('hit enter>') class NullLogger(object): def print_progress(self, lots, text, bold_lots): pass ## Instruction: Switch from bold to red highlighting. With many terminal fonts bold is subtle. The red is much more clear. ## Code After: import copy import wash # from http://stackoverflow.com/questions/8924173/how-do-i-print-bold-text-in-python class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' class TermLogger(object): def print_progress(self, lots, text, red_lots): lots = copy.copy(lots) # so I can re-sort non-destructively print text lots.sort(cmp=wash.cmp_by_buy_date) red_ids = [id(lot) for lot in red_lots] for lot in lots: header = '' footer = '' if id(lot) in red_ids: header = color.RED footer = color.END print header + str(lot) + footer raw_input('hit enter>') class NullLogger(object): def print_progress(self, lots, text, red_lots): pass
# ... existing code ... END = '\033[0m' class TermLogger(object): def print_progress(self, lots, text, red_lots): lots = copy.copy(lots) # so I can re-sort non-destructively print text lots.sort(cmp=wash.cmp_by_buy_date) red_ids = [id(lot) for lot in red_lots] for lot in lots: header = '' footer = '' if id(lot) in red_ids: header = color.RED footer = color.END print header + str(lot) + footer raw_input('hit enter>') class NullLogger(object): def print_progress(self, lots, text, red_lots): pass # ... rest of the code ...
155822548be11161aefdb0d93d5ec86095ab3624
rt.py
rt.py
import queue import threading def loop(queue, actor): while True: message = queue.get() actor.behavior(message) class Actor(object): def __init__(self): pass def _start_loop(self): self.queue = queue.Queue() self.dispatcher = threading.Thread( target=loop, args=(self.queue, self)) self.dispatcher.start() def __call__(self, message): self.queue.put(message) @classmethod def create(cls, *args): actor = cls(*args) actor._start_loop() return actor
import queue import threading def indiviual_loop(queue, actor): while True: message = queue.get() actor.behavior(message) def global_loop(queue): while True: actor, message = queue.get() actor.behavior(message) class EventLoop(object): loop = None def __init__(self): self.queue = queue.Queue() self.thread = threading.Thread( target=global_loop, args=(self.queue,), name='global-loop') self.thread.start() def schedule(self, message, target): self.queue.put((target, message)) @classmethod def get_loop(cls): if cls.loop is None: cls.loop = cls() return cls.loop class AbstractActor(object): def __call__(self, message): self._put(message) def _put(self, message): raise NotImplementedError() def _ensure_loop(self): pass @classmethod def create(cls, *args): actor = cls(*args) actor._ensure_loop() return actor class ActorOwnLoop(AbstractActor): def _put(self, message): self.queue.put(message) def _ensure_loop(self): self.queue = queue.Queue() self.dispatcher = threading.Thread( target=indiviual_loop, args=(self.queue, self), name=self._thread_name()) self.dispatcher.start() def _thread_name(self): return '{}-{}'.format( self.__class__.__name__, hex(id(self))) class ActorGlobalLoop(AbstractActor): def _put(self, message): self.loop.schedule(message, self) def _ensure_loop(self): self.loop = EventLoop.get_loop() Actor = ActorGlobalLoop
Refactor to allow different event loops
Refactor to allow different event loops
Python
mit
waltermoreira/tartpy
python
## Code Before: import queue import threading def loop(queue, actor): while True: message = queue.get() actor.behavior(message) class Actor(object): def __init__(self): pass def _start_loop(self): self.queue = queue.Queue() self.dispatcher = threading.Thread( target=loop, args=(self.queue, self)) self.dispatcher.start() def __call__(self, message): self.queue.put(message) @classmethod def create(cls, *args): actor = cls(*args) actor._start_loop() return actor ## Instruction: Refactor to allow different event loops ## Code After: import queue import threading def indiviual_loop(queue, actor): while True: message = queue.get() actor.behavior(message) def global_loop(queue): while True: actor, message = queue.get() actor.behavior(message) class EventLoop(object): loop = None def __init__(self): self.queue = queue.Queue() self.thread = threading.Thread( target=global_loop, args=(self.queue,), name='global-loop') self.thread.start() def schedule(self, message, target): self.queue.put((target, message)) @classmethod def get_loop(cls): if cls.loop is None: cls.loop = cls() return cls.loop class AbstractActor(object): def __call__(self, message): self._put(message) def _put(self, message): raise NotImplementedError() def _ensure_loop(self): pass @classmethod def create(cls, *args): actor = cls(*args) actor._ensure_loop() return actor class ActorOwnLoop(AbstractActor): def _put(self, message): self.queue.put(message) def _ensure_loop(self): self.queue = queue.Queue() self.dispatcher = threading.Thread( target=indiviual_loop, args=(self.queue, self), name=self._thread_name()) self.dispatcher.start() def _thread_name(self): return '{}-{}'.format( self.__class__.__name__, hex(id(self))) class ActorGlobalLoop(AbstractActor): def _put(self, message): self.loop.schedule(message, self) def _ensure_loop(self): self.loop = EventLoop.get_loop() Actor = ActorGlobalLoop
// ... existing code ... import threading def indiviual_loop(queue, actor): while True: message = queue.get() actor.behavior(message) def global_loop(queue): while True: actor, message = queue.get() actor.behavior(message) class EventLoop(object): loop = None def __init__(self): self.queue = queue.Queue() self.thread = threading.Thread( target=global_loop, args=(self.queue,), name='global-loop') self.thread.start() def schedule(self, message, target): self.queue.put((target, message)) @classmethod def get_loop(cls): if cls.loop is None: cls.loop = cls() return cls.loop class AbstractActor(object): def __call__(self, message): self._put(message) def _put(self, message): raise NotImplementedError() def _ensure_loop(self): pass @classmethod def create(cls, *args): actor = cls(*args) actor._ensure_loop() return actor class ActorOwnLoop(AbstractActor): def _put(self, message): self.queue.put(message) def _ensure_loop(self): self.queue = queue.Queue() self.dispatcher = threading.Thread( target=indiviual_loop, args=(self.queue, self), name=self._thread_name()) self.dispatcher.start() def _thread_name(self): return '{}-{}'.format( self.__class__.__name__, hex(id(self))) class ActorGlobalLoop(AbstractActor): def _put(self, message): self.loop.schedule(message, self) def _ensure_loop(self): self.loop = EventLoop.get_loop() Actor = ActorGlobalLoop // ... rest of the code ...
cbcd4ebcc01646382595ce9ee10d278120ce00ce
pets/common/views.py
pets/common/views.py
from django.db.models import Count from django.shortcuts import render from django.views.generic import TemplateView from django.views.generic.base import ContextMixin from meupet import models def get_adoption_kinds(): return get_kind_list([models.Pet.FOR_ADOPTION, models.Pet.ADOPTED]) def get_lost_kinds(): return get_kind_list([models.Pet.MISSING, models.Pet.FOUND]) def get_kind_list(status): return models.Kind.objects.filter(pet__status__in=status).annotate(num_pets=Count('pet')).order_by('kind') class MeuPetEspecieMixin(ContextMixin): def get_context_data(self, **kwargs): context = super(MeuPetEspecieMixin, self).get_context_data(**kwargs) context['kind_lost'] = get_lost_kinds() context['kind_adoption'] = get_adoption_kinds() return context class AboutPageView(MeuPetEspecieMixin, TemplateView): template_name = 'staticpages/about.html' class AssociacoesView(MeuPetEspecieMixin, TemplateView): template_name = 'staticpages/associacoes.html' def not_found(request): return render(request, 'staticpages/404.html') def home(request): pets = models.Pet.objects.select_related('city').order_by('-id')[:6] return render(request, 'common/home.html', {'pets': pets})
from django.db.models import Count from django.shortcuts import render from django.views.generic import TemplateView from django.views.generic.base import ContextMixin from meupet import models def get_adoption_kinds(): return get_kind_list([models.Pet.FOR_ADOPTION, models.Pet.ADOPTED]) def get_lost_kinds(): return get_kind_list([models.Pet.MISSING, models.Pet.FOUND]) def get_kind_list(status): return models.Kind.objects.filter(pet__status__in=status).annotate(num_pets=Count('pet')).order_by('kind') class MeuPetEspecieMixin(ContextMixin): def get_context_data(self, **kwargs): context = super(MeuPetEspecieMixin, self).get_context_data(**kwargs) context['kind_lost'] = get_lost_kinds() context['kind_adoption'] = get_adoption_kinds() return context class AboutPageView(MeuPetEspecieMixin, TemplateView): template_name = 'staticpages/about.html' class AssociacoesView(MeuPetEspecieMixin, TemplateView): template_name = 'staticpages/associacoes.html' def not_found(request): return render(request, 'staticpages/404.html') def home(request): return render(request, 'common/home.html')
Remove useless code from the home view
Remove useless code from the home view
Python
mit
dirtycoder/pets,dirtycoder/pets,dirtycoder/pets
python
## Code Before: from django.db.models import Count from django.shortcuts import render from django.views.generic import TemplateView from django.views.generic.base import ContextMixin from meupet import models def get_adoption_kinds(): return get_kind_list([models.Pet.FOR_ADOPTION, models.Pet.ADOPTED]) def get_lost_kinds(): return get_kind_list([models.Pet.MISSING, models.Pet.FOUND]) def get_kind_list(status): return models.Kind.objects.filter(pet__status__in=status).annotate(num_pets=Count('pet')).order_by('kind') class MeuPetEspecieMixin(ContextMixin): def get_context_data(self, **kwargs): context = super(MeuPetEspecieMixin, self).get_context_data(**kwargs) context['kind_lost'] = get_lost_kinds() context['kind_adoption'] = get_adoption_kinds() return context class AboutPageView(MeuPetEspecieMixin, TemplateView): template_name = 'staticpages/about.html' class AssociacoesView(MeuPetEspecieMixin, TemplateView): template_name = 'staticpages/associacoes.html' def not_found(request): return render(request, 'staticpages/404.html') def home(request): pets = models.Pet.objects.select_related('city').order_by('-id')[:6] return render(request, 'common/home.html', {'pets': pets}) ## Instruction: Remove useless code from the home view ## Code After: from django.db.models import Count from django.shortcuts import render from django.views.generic import TemplateView from django.views.generic.base import ContextMixin from meupet import models def get_adoption_kinds(): return get_kind_list([models.Pet.FOR_ADOPTION, models.Pet.ADOPTED]) def get_lost_kinds(): return get_kind_list([models.Pet.MISSING, models.Pet.FOUND]) def get_kind_list(status): return models.Kind.objects.filter(pet__status__in=status).annotate(num_pets=Count('pet')).order_by('kind') class MeuPetEspecieMixin(ContextMixin): def get_context_data(self, **kwargs): context = super(MeuPetEspecieMixin, self).get_context_data(**kwargs) context['kind_lost'] = get_lost_kinds() context['kind_adoption'] = get_adoption_kinds() return context class AboutPageView(MeuPetEspecieMixin, TemplateView): template_name = 'staticpages/about.html' class AssociacoesView(MeuPetEspecieMixin, TemplateView): template_name = 'staticpages/associacoes.html' def not_found(request): return render(request, 'staticpages/404.html') def home(request): return render(request, 'common/home.html')
# ... existing code ... def home(request): return render(request, 'common/home.html') # ... rest of the code ...
4503e6671828497189736c86d408f6c0a8b47058
lambda_tweet.py
lambda_tweet.py
import boto3 import tweepy import json import base64 from tweet_s3_images import TweetS3Images with open('./config.json', 'r') as file: config = json.loads(file.read()) # Decrypt API keys client = boto3.client('kms') response = client.decrypt(CiphertextBlob=base64.b64decode(config['secrets'])) secrets = json.loads(response['Plaintext']) CONSUMER_KEY = secrets['consumer-key'] CONSUMER_SECRET = secrets['consumer-secret'] ACCESS_TOKEN = secrets['access-token'] ACCESS_TOKEN_SECRET = secrets['access-token-secret'] def lambda_handler(event, context): print('Received event: ' + json.dumps(event, indent=2)) s3_info = event['Records'][0]['S3'] auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth) client = boto3.client('s3') tweet_images = TweetS3Images(api, client) tweet_images.send_image(s3_info['bucket']['name'], s3_info['object']['key'], cleanup=True)
import boto3 import tweepy import json import base64 from tweet_s3_images import TweetS3Images with open('./config.json', 'r') as file: config = json.loads(file.read()) # Decrypt API keys client = boto3.client('kms') response = client.decrypt(CiphertextBlob=base64.b64decode(config['secrets'])) secrets = json.loads(response['Plaintext']) CONSUMER_KEY = secrets['consumer-key'] CONSUMER_SECRET = secrets['consumer-secret'] ACCESS_TOKEN = secrets['access-token'] ACCESS_TOKEN_SECRET = secrets['access-token-secret'] def lambda_handler(event, context): print('Received event: ' + json.dumps(event, indent=2)) print() s3_info = event['Records'][0]['s3'] auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth) client = boto3.client('s3') tweet_images = TweetS3Images(api, client) tweet_images.send_image(s3_info['bucket']['name'], s3_info['object']['key'], cleanup=True)
Update key name for S3
Update key name for S3
Python
mit
onema/lambda-tweet
python
## Code Before: import boto3 import tweepy import json import base64 from tweet_s3_images import TweetS3Images with open('./config.json', 'r') as file: config = json.loads(file.read()) # Decrypt API keys client = boto3.client('kms') response = client.decrypt(CiphertextBlob=base64.b64decode(config['secrets'])) secrets = json.loads(response['Plaintext']) CONSUMER_KEY = secrets['consumer-key'] CONSUMER_SECRET = secrets['consumer-secret'] ACCESS_TOKEN = secrets['access-token'] ACCESS_TOKEN_SECRET = secrets['access-token-secret'] def lambda_handler(event, context): print('Received event: ' + json.dumps(event, indent=2)) s3_info = event['Records'][0]['S3'] auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth) client = boto3.client('s3') tweet_images = TweetS3Images(api, client) tweet_images.send_image(s3_info['bucket']['name'], s3_info['object']['key'], cleanup=True) ## Instruction: Update key name for S3 ## Code After: import boto3 import tweepy import json import base64 from tweet_s3_images import TweetS3Images with open('./config.json', 'r') as file: config = json.loads(file.read()) # Decrypt API keys client = boto3.client('kms') response = client.decrypt(CiphertextBlob=base64.b64decode(config['secrets'])) secrets = json.loads(response['Plaintext']) CONSUMER_KEY = secrets['consumer-key'] CONSUMER_SECRET = secrets['consumer-secret'] ACCESS_TOKEN = secrets['access-token'] ACCESS_TOKEN_SECRET = secrets['access-token-secret'] def lambda_handler(event, context): print('Received event: ' + json.dumps(event, indent=2)) print() s3_info = event['Records'][0]['s3'] auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth) client = boto3.client('s3') tweet_images = TweetS3Images(api, client) tweet_images.send_image(s3_info['bucket']['name'], s3_info['object']['key'], cleanup=True)
// ... existing code ... def lambda_handler(event, context): print('Received event: ' + json.dumps(event, indent=2)) print() s3_info = event['Records'][0]['s3'] auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) // ... rest of the code ...
c83d8c4f77ebbd865649df82f89f69fd12235f14
action-system/impl/com/intellij/ide/IdePopupManager.java
action-system/impl/com/intellij/ide/IdePopupManager.java
package com.intellij.ide; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.popup.IdePopup; import com.intellij.ui.popup.StackingPopupDispatcher; import com.intellij.ui.popup.JBPopupImpl; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; public final class IdePopupManager implements IdeEventQueue.EventDispatcher { private static final Logger LOG = Logger.getInstance("com.intellij.ide.IdePopupManager"); private IdePopup myActivePopup; boolean isPopupActive() { if (myActivePopup != null) { final Component component = myActivePopup.getComponent(); if (component == null || !component.isShowing()) { IdePopup activePopup = myActivePopup; myActivePopup = null; if (component == null) { LOG.error("Popup " + activePopup + " is set up as active but not showing (component=null)"); } else if (activePopup instanceof JBPopupImpl) { LOG.error("Popup [JBPop upImpl] " + ((JBPopupImpl) activePopup).getContent() + " is set up as active but not showing"); } else { LOG.error("Popup " + component + " is set up as active but not showing"); } } } return myActivePopup != null; } public boolean dispatch(AWTEvent e) { LOG.assertTrue(isPopupActive()); if (e instanceof KeyEvent || e instanceof MouseEvent) { return myActivePopup.dispatch(e); } return false; } public void setActivePopup(IdePopup popup) { myActivePopup = popup; } public void resetActivePopup() { myActivePopup = null; } public boolean closeActivePopup(){ return myActivePopup instanceof StackingPopupDispatcher && ((StackingPopupDispatcher)myActivePopup).closeActivePopup(); } }
package com.intellij.ide; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.popup.IdePopup; import com.intellij.ui.popup.StackingPopupDispatcher; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; public final class IdePopupManager implements IdeEventQueue.EventDispatcher { private static final Logger LOG = Logger.getInstance("com.intellij.ide.IdePopupManager"); private IdePopup myActivePopup; boolean isPopupActive() { if (myActivePopup != null) { final Component component = myActivePopup.getComponent(); if (component == null || !component.isShowing()) { myActivePopup = null; } } return myActivePopup != null; } public boolean dispatch(AWTEvent e) { LOG.assertTrue(isPopupActive()); if (e instanceof KeyEvent || e instanceof MouseEvent) { return myActivePopup.dispatch(e); } return false; } public void setActivePopup(IdePopup popup) { myActivePopup = popup; } public void resetActivePopup() { myActivePopup = null; } public boolean closeActivePopup(){ return myActivePopup instanceof StackingPopupDispatcher && ((StackingPopupDispatcher)myActivePopup).closeActivePopup(); } }
Remove assertion in favor to correct recover.
Remove assertion in favor to correct recover.
Java
apache-2.0
ol-loginov/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,caot/intellij-community,caot/intellij-community,allotria/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,holmes/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,signed/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,da1z/intellij-community,petteyg/intellij-community,apixandru/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,wreckJ/intellij-community,joewalnes/idea-community,petteyg/intellij-community,diorcety/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,semonte/intellij-community,signed/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,robovm/robovm-studio,adedayo/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,vladmm/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,diorcety/intellij-community,fitermay/intellij-community,ryano144/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,xfournet/intellij-community,robovm/robovm-studio,retomerz/intellij-community,vvv1559/intellij-community,da1z/intellij-community,blademainer/intellij-community,signed/intellij-community,FHannes/intellij-community,joewalnes/idea-community,apixandru/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,caot/intellij-community,semonte/intellij-community,samthor/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,ryano144/intellij-community,fnouama/intellij-community,blademainer/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,allotria/intellij-community,ibinti/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,robovm/robovm-studio,semonte/intellij-community,clumsy/intellij-community,supersven/intellij-community,FHannes/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,hurricup/intellij-community,fitermay/intellij-community,joewalnes/idea-community,ibinti/intellij-community,clumsy/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,kool79/intellij-community,dslomov/intellij-community,blademainer/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,jagguli/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,caot/intellij-community,robovm/robovm-studio,fitermay/intellij-community,FHannes/intellij-community,xfournet/intellij-community,slisson/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,diorcety/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,diorcety/intellij-community,supersven/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,petteyg/intellij-community,adedayo/intellij-community,xfournet/intellij-community,consulo/consulo,mglukhikh/intellij-community,jagguli/intellij-community,asedunov/intellij-community,kool79/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,robovm/robovm-studio,dslomov/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,ernestp/consulo,fnouama/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,izonder/intellij-community,samthor/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,izonder/intellij-community,holmes/intellij-community,vladmm/intellij-community,kool79/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,amith01994/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,hurricup/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,kool79/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,ryano144/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,slisson/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,izonder/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,signed/intellij-community,kool79/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,xfournet/intellij-community,retomerz/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,semonte/intellij-community,allotria/intellij-community,clumsy/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,caot/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,diorcety/intellij-community,FHannes/intellij-community,samthor/intellij-community,FHannes/intellij-community,ibinti/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,jagguli/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,samthor/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,caot/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,fengbaicanhe/intellij-community,suncycheng/intellij-community,semonte/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,caot/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,allotria/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,holmes/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,hurricup/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,ryano144/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,signed/intellij-community,jagguli/intellij-community,retomerz/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,caot/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,semonte/intellij-community,ibinti/intellij-community,jexp/idea2,ernestp/consulo,consulo/consulo,dslomov/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,signed/intellij-community,asedunov/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,ryano144/intellij-community,samthor/intellij-community,retomerz/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,hurricup/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,semonte/intellij-community,jexp/idea2,vvv1559/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,supersven/intellij-community,jagguli/intellij-community,caot/intellij-community,holmes/intellij-community,fnouama/intellij-community,da1z/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,allotria/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,kool79/intellij-community,consulo/consulo,clumsy/intellij-community,slisson/intellij-community,adedayo/intellij-community,petteyg/intellij-community,samthor/intellij-community,FHannes/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,retomerz/intellij-community,FHannes/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,holmes/intellij-community,FHannes/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,samthor/intellij-community,ibinti/intellij-community,clumsy/intellij-community,vladmm/intellij-community,kool79/intellij-community,ernestp/consulo,izonder/intellij-community,joewalnes/idea-community,consulo/consulo,muntasirsyed/intellij-community,holmes/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,jexp/idea2,tmpgit/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,da1z/intellij-community,ernestp/consulo,semonte/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,kdwink/intellij-community,samthor/intellij-community,akosyakov/intellij-community,caot/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,da1z/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,ernestp/consulo,joewalnes/idea-community,xfournet/intellij-community,asedunov/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,ibinti/intellij-community,kool79/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,jexp/idea2,ibinti/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,clumsy/intellij-community,dslomov/intellij-community,izonder/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,signed/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,supersven/intellij-community,izonder/intellij-community,diorcety/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,consulo/consulo,FHannes/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,slisson/intellij-community,hurricup/intellij-community,holmes/intellij-community,kdwink/intellij-community,kdwink/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,jexp/idea2,dslomov/intellij-community,xfournet/intellij-community,blademainer/intellij-community,vladmm/intellij-community,holmes/intellij-community,orekyuu/intellij-community,holmes/intellij-community,izonder/intellij-community,slisson/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,kool79/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,caot/intellij-community,kool79/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,jexp/idea2,petteyg/intellij-community,fnouama/intellij-community,jexp/idea2,da1z/intellij-community,adedayo/intellij-community,ibinti/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,jexp/idea2,apixandru/intellij-community,da1z/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,blademainer/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,amith01994/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,holmes/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,signed/intellij-community,orekyuu/intellij-community,slisson/intellij-community
java
## Code Before: package com.intellij.ide; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.popup.IdePopup; import com.intellij.ui.popup.StackingPopupDispatcher; import com.intellij.ui.popup.JBPopupImpl; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; public final class IdePopupManager implements IdeEventQueue.EventDispatcher { private static final Logger LOG = Logger.getInstance("com.intellij.ide.IdePopupManager"); private IdePopup myActivePopup; boolean isPopupActive() { if (myActivePopup != null) { final Component component = myActivePopup.getComponent(); if (component == null || !component.isShowing()) { IdePopup activePopup = myActivePopup; myActivePopup = null; if (component == null) { LOG.error("Popup " + activePopup + " is set up as active but not showing (component=null)"); } else if (activePopup instanceof JBPopupImpl) { LOG.error("Popup [JBPop upImpl] " + ((JBPopupImpl) activePopup).getContent() + " is set up as active but not showing"); } else { LOG.error("Popup " + component + " is set up as active but not showing"); } } } return myActivePopup != null; } public boolean dispatch(AWTEvent e) { LOG.assertTrue(isPopupActive()); if (e instanceof KeyEvent || e instanceof MouseEvent) { return myActivePopup.dispatch(e); } return false; } public void setActivePopup(IdePopup popup) { myActivePopup = popup; } public void resetActivePopup() { myActivePopup = null; } public boolean closeActivePopup(){ return myActivePopup instanceof StackingPopupDispatcher && ((StackingPopupDispatcher)myActivePopup).closeActivePopup(); } } ## Instruction: Remove assertion in favor to correct recover. ## Code After: package com.intellij.ide; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.popup.IdePopup; import com.intellij.ui.popup.StackingPopupDispatcher; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; public final class IdePopupManager implements IdeEventQueue.EventDispatcher { private static final Logger LOG = Logger.getInstance("com.intellij.ide.IdePopupManager"); private IdePopup myActivePopup; boolean isPopupActive() { if (myActivePopup != null) { final Component component = myActivePopup.getComponent(); if (component == null || !component.isShowing()) { myActivePopup = null; } } return myActivePopup != null; } public boolean dispatch(AWTEvent e) { LOG.assertTrue(isPopupActive()); if (e instanceof KeyEvent || e instanceof MouseEvent) { return myActivePopup.dispatch(e); } return false; } public void setActivePopup(IdePopup popup) { myActivePopup = popup; } public void resetActivePopup() { myActivePopup = null; } public boolean closeActivePopup(){ return myActivePopup instanceof StackingPopupDispatcher && ((StackingPopupDispatcher)myActivePopup).closeActivePopup(); } }
# ... existing code ... import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.popup.IdePopup; import com.intellij.ui.popup.StackingPopupDispatcher; import java.awt.*; import java.awt.event.KeyEvent; # ... modified code ... if (myActivePopup != null) { final Component component = myActivePopup.getComponent(); if (component == null || !component.isShowing()) { myActivePopup = null; } } return myActivePopup != null; # ... rest of the code ...
a760beb8d66222b456b160344eb0b4b7fccbf84a
Lib/test/test_linuxaudiodev.py
Lib/test/test_linuxaudiodev.py
from test_support import verbose, findfile, TestFailed import linuxaudiodev import errno import os def play_sound_file(path): fp = open(path, 'r') data = fp.read() fp.close() try: a = linuxaudiodev.open('w') except linuxaudiodev.error, msg: if msg[0] in (errno.EACCES, errno.ENODEV): raise ImportError, msg raise TestFailed, msg else: a.write(data) a.close() def test(): play_sound_file(findfile('audiotest.au')) test()
from test_support import verbose, findfile, TestFailed, TestSkipped import linuxaudiodev import errno import os def play_sound_file(path): fp = open(path, 'r') data = fp.read() fp.close() try: a = linuxaudiodev.open('w') except linuxaudiodev.error, msg: if msg[0] in (errno.EACCES, errno.ENODEV): raise TestSkipped, msg raise TestFailed, msg else: a.write(data) a.close() def test(): play_sound_file(findfile('audiotest.au')) test()
Raise TestSkipped, not ImportError. Honesty's the best policy.
Raise TestSkipped, not ImportError. Honesty's the best policy.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
python
## Code Before: from test_support import verbose, findfile, TestFailed import linuxaudiodev import errno import os def play_sound_file(path): fp = open(path, 'r') data = fp.read() fp.close() try: a = linuxaudiodev.open('w') except linuxaudiodev.error, msg: if msg[0] in (errno.EACCES, errno.ENODEV): raise ImportError, msg raise TestFailed, msg else: a.write(data) a.close() def test(): play_sound_file(findfile('audiotest.au')) test() ## Instruction: Raise TestSkipped, not ImportError. Honesty's the best policy. ## Code After: from test_support import verbose, findfile, TestFailed, TestSkipped import linuxaudiodev import errno import os def play_sound_file(path): fp = open(path, 'r') data = fp.read() fp.close() try: a = linuxaudiodev.open('w') except linuxaudiodev.error, msg: if msg[0] in (errno.EACCES, errno.ENODEV): raise TestSkipped, msg raise TestFailed, msg else: a.write(data) a.close() def test(): play_sound_file(findfile('audiotest.au')) test()
... from test_support import verbose, findfile, TestFailed, TestSkipped import linuxaudiodev import errno import os ... a = linuxaudiodev.open('w') except linuxaudiodev.error, msg: if msg[0] in (errno.EACCES, errno.ENODEV): raise TestSkipped, msg raise TestFailed, msg else: a.write(data) ...
bc8e064e41d43a4579c8111f1480b55e660ca186
pep8ify/fixes/fix_tabs.py
pep8ify/fixes/fix_tabs.py
from __future__ import unicode_literals from lib2to3.fixer_base import BaseFix from lib2to3.pytree import Leaf SPACES = ' ' * 4 class FixTabs(BaseFix): ''' For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do. ''' def match(self, node): if node.prefix.count('\t') or (isinstance(node, Leaf) and node.value.count('\t')): return True return False def transform(self, node, results): new_prefix = node.prefix.replace('\t', SPACES) new_value = node.value.replace('\t', SPACES) if node.prefix != new_prefix or node.value != new_value: node.prefix = new_prefix node.value = new_value node.changed()
from __future__ import unicode_literals from lib2to3.fixer_base import BaseFix from lib2to3.pytree import Leaf from .utils import SPACES class FixTabs(BaseFix): ''' For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do. ''' def match(self, node): if node.prefix.count('\t') or (isinstance(node, Leaf) and node.value.count('\t')): return True return False def transform(self, node, results): new_prefix = node.prefix.replace('\t', SPACES) new_value = node.value.replace('\t', SPACES) if node.prefix != new_prefix or node.value != new_value: node.prefix = new_prefix node.value = new_value node.changed()
Use globally define number of spaces.
Clean-up: Use globally define number of spaces.
Python
apache-2.0
spulec/pep8ify
python
## Code Before: from __future__ import unicode_literals from lib2to3.fixer_base import BaseFix from lib2to3.pytree import Leaf SPACES = ' ' * 4 class FixTabs(BaseFix): ''' For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do. ''' def match(self, node): if node.prefix.count('\t') or (isinstance(node, Leaf) and node.value.count('\t')): return True return False def transform(self, node, results): new_prefix = node.prefix.replace('\t', SPACES) new_value = node.value.replace('\t', SPACES) if node.prefix != new_prefix or node.value != new_value: node.prefix = new_prefix node.value = new_value node.changed() ## Instruction: Clean-up: Use globally define number of spaces. ## Code After: from __future__ import unicode_literals from lib2to3.fixer_base import BaseFix from lib2to3.pytree import Leaf from .utils import SPACES class FixTabs(BaseFix): ''' For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do. ''' def match(self, node): if node.prefix.count('\t') or (isinstance(node, Leaf) and node.value.count('\t')): return True return False def transform(self, node, results): new_prefix = node.prefix.replace('\t', SPACES) new_value = node.value.replace('\t', SPACES) if node.prefix != new_prefix or node.value != new_value: node.prefix = new_prefix node.value = new_value node.changed()
... from lib2to3.fixer_base import BaseFix from lib2to3.pytree import Leaf from .utils import SPACES class FixTabs(BaseFix): ''' ...
21e91efbf9cb064f1fcd19ba7a77ba81a6c843f5
isso/db/preferences.py
isso/db/preferences.py
import os import binascii class Preferences: defaults = [ ("session-key", binascii.b2a_hex(os.urandom(24))), ] def __init__(self, db): self.db = db self.db.execute([ 'CREATE TABLE IF NOT EXISTS preferences (', ' key VARCHAR PRIMARY KEY, value VARCHAR', ');']) for (key, value) in Preferences.defaults: if self.get(key) is None: self.set(key, value) def get(self, key, default=None): rv = self.db.execute( 'SELECT value FROM preferences WHERE key=?', (key, )).fetchone() if rv is None: return default return rv[0] def set(self, key, value): self.db.execute( 'INSERT INTO preferences (key, value) VALUES (?, ?)', (key, value))
import os import binascii class Preferences: defaults = [ ("session-key", binascii.b2a_hex(os.urandom(24)).decode('utf-8')), ] def __init__(self, db): self.db = db self.db.execute([ 'CREATE TABLE IF NOT EXISTS preferences (', ' key VARCHAR PRIMARY KEY, value VARCHAR', ');']) for (key, value) in Preferences.defaults: if self.get(key) is None: self.set(key, value) def get(self, key, default=None): rv = self.db.execute( 'SELECT value FROM preferences WHERE key=?', (key, )).fetchone() if rv is None: return default return rv[0] def set(self, key, value): self.db.execute( 'INSERT INTO preferences (key, value) VALUES (?, ?)', (key, value))
Save the session-key as a unicode string in the db
Save the session-key as a unicode string in the db The session-key should be saved as a string, not a byte string.
Python
mit
posativ/isso,xuhdev/isso,Mushiyo/isso,jelmer/isso,princesuke/isso,jiumx60rus/isso,janusnic/isso,janusnic/isso,Mushiyo/isso,Mushiyo/isso,posativ/isso,mathstuf/isso,janusnic/isso,jiumx60rus/isso,WQuanfeng/isso,jelmer/isso,princesuke/isso,jelmer/isso,Mushiyo/isso,WQuanfeng/isso,xuhdev/isso,mathstuf/isso,xuhdev/isso,princesuke/isso,jelmer/isso,jiumx60rus/isso,posativ/isso,posativ/isso,mathstuf/isso,WQuanfeng/isso
python
## Code Before: import os import binascii class Preferences: defaults = [ ("session-key", binascii.b2a_hex(os.urandom(24))), ] def __init__(self, db): self.db = db self.db.execute([ 'CREATE TABLE IF NOT EXISTS preferences (', ' key VARCHAR PRIMARY KEY, value VARCHAR', ');']) for (key, value) in Preferences.defaults: if self.get(key) is None: self.set(key, value) def get(self, key, default=None): rv = self.db.execute( 'SELECT value FROM preferences WHERE key=?', (key, )).fetchone() if rv is None: return default return rv[0] def set(self, key, value): self.db.execute( 'INSERT INTO preferences (key, value) VALUES (?, ?)', (key, value)) ## Instruction: Save the session-key as a unicode string in the db The session-key should be saved as a string, not a byte string. ## Code After: import os import binascii class Preferences: defaults = [ ("session-key", binascii.b2a_hex(os.urandom(24)).decode('utf-8')), ] def __init__(self, db): self.db = db self.db.execute([ 'CREATE TABLE IF NOT EXISTS preferences (', ' key VARCHAR PRIMARY KEY, value VARCHAR', ');']) for (key, value) in Preferences.defaults: if self.get(key) is None: self.set(key, value) def get(self, key, default=None): rv = self.db.execute( 'SELECT value FROM preferences WHERE key=?', (key, )).fetchone() if rv is None: return default return rv[0] def set(self, key, value): self.db.execute( 'INSERT INTO preferences (key, value) VALUES (?, ?)', (key, value))
# ... existing code ... class Preferences: defaults = [ ("session-key", binascii.b2a_hex(os.urandom(24)).decode('utf-8')), ] def __init__(self, db): # ... rest of the code ...
4adae240524bfb8426ad65322325ebc5e3b8073f
test/unstar/CrackerTest.java
test/unstar/CrackerTest.java
package unstar; import org.junit.Test; import static org.junit.Assert.*; public class CrackerTest { @Test public void digitTest() { assertEquals(36, Cracker.DIGITS.length); } @Test public void encodeTest() { assertEquals("1", Cracker.encode(1, 1)); assertEquals("A", Cracker.encode(1, 10)); assertEquals("00RS", Cracker.encode(4, 1000)); assertEquals(1000, Cracker.decode("00RS")); } }
package unstar; import org.junit.Test; import static org.junit.Assert.*; public class CrackerTest { @Test public void digitTest() { assertEquals(36, Cracker.DIGITS.length); } @Test public void encodeTest() { assertEquals("1", Cracker.encode(1, 1)); assertEquals("A", Cracker.encode(1, 10)); assertEquals("00RS", Cracker.encode(4, 1000)); assertEquals(1000, Cracker.decode("00RS")); } @Test public void serialTest() { assertEquals(0x1009db6241eL, Cracker.decode("E2BO659A")); assertEquals(0x10120a6bad5L, Cracker.decode("E3C03B2T")); assertEquals(0x101e22fa47cL, Cracker.decode("E4TP99BW")); assertEquals(0x105d81aa6a9L, Cracker.decode("ECN101WP")); assertEquals(0x1071daf128cL, Cracker.decode("EF5D4KNG")); assertEquals(0x10f0e3321c7L, Cracker.decode("EUTBD0AV")); assertEquals(0x2042ff5da94L, Cracker.decode("SAH96KK4")); assertEquals(0x2042ff79a65L, Cracker.decode("SAH9910L")); assertEquals(0x2042ff197cbL, Cracker.decode("SAH90L3F")); } }
Add another, uh, unit test.
Add another, uh, unit test.
Java
unlicense
skeeto/unstar
java
## Code Before: package unstar; import org.junit.Test; import static org.junit.Assert.*; public class CrackerTest { @Test public void digitTest() { assertEquals(36, Cracker.DIGITS.length); } @Test public void encodeTest() { assertEquals("1", Cracker.encode(1, 1)); assertEquals("A", Cracker.encode(1, 10)); assertEquals("00RS", Cracker.encode(4, 1000)); assertEquals(1000, Cracker.decode("00RS")); } } ## Instruction: Add another, uh, unit test. ## Code After: package unstar; import org.junit.Test; import static org.junit.Assert.*; public class CrackerTest { @Test public void digitTest() { assertEquals(36, Cracker.DIGITS.length); } @Test public void encodeTest() { assertEquals("1", Cracker.encode(1, 1)); assertEquals("A", Cracker.encode(1, 10)); assertEquals("00RS", Cracker.encode(4, 1000)); assertEquals(1000, Cracker.decode("00RS")); } @Test public void serialTest() { assertEquals(0x1009db6241eL, Cracker.decode("E2BO659A")); assertEquals(0x10120a6bad5L, Cracker.decode("E3C03B2T")); assertEquals(0x101e22fa47cL, Cracker.decode("E4TP99BW")); assertEquals(0x105d81aa6a9L, Cracker.decode("ECN101WP")); assertEquals(0x1071daf128cL, Cracker.decode("EF5D4KNG")); assertEquals(0x10f0e3321c7L, Cracker.decode("EUTBD0AV")); assertEquals(0x2042ff5da94L, Cracker.decode("SAH96KK4")); assertEquals(0x2042ff79a65L, Cracker.decode("SAH9910L")); assertEquals(0x2042ff197cbL, Cracker.decode("SAH90L3F")); } }
// ... existing code ... assertEquals("00RS", Cracker.encode(4, 1000)); assertEquals(1000, Cracker.decode("00RS")); } @Test public void serialTest() { assertEquals(0x1009db6241eL, Cracker.decode("E2BO659A")); assertEquals(0x10120a6bad5L, Cracker.decode("E3C03B2T")); assertEquals(0x101e22fa47cL, Cracker.decode("E4TP99BW")); assertEquals(0x105d81aa6a9L, Cracker.decode("ECN101WP")); assertEquals(0x1071daf128cL, Cracker.decode("EF5D4KNG")); assertEquals(0x10f0e3321c7L, Cracker.decode("EUTBD0AV")); assertEquals(0x2042ff5da94L, Cracker.decode("SAH96KK4")); assertEquals(0x2042ff79a65L, Cracker.decode("SAH9910L")); assertEquals(0x2042ff197cbL, Cracker.decode("SAH90L3F")); } } // ... rest of the code ...
b4d153a179c76837e809549c173da81e13e07f1e
src/revert/Entities/EnemyFactory.java
src/revert/Entities/EnemyFactory.java
package revert.Entities; import java.awt.Point; import revert.AI.EnemyAi; import revert.MainScene.World; public class EnemyFactory { Point[] spawnPoints; World world; public EnemyFactory(World world, Point... spawns) { this.spawnPoints = spawns; this.world = world; } /** * Create a data set array * @param size * @return */ public int[][] createWave(int size) { int[][] wave = new int[size][]; for (int i = 0; i < size; i++) { Point loc = spawnPoints[(int)(Math.random()*spawnPoints.length)]; int[] n = {loc.x, loc.y, (int)(Math.random()*3)}; wave[i] = n; } return wave; } public Enemy generateEnemy(int type) { Enemy e = new Enemy(world, world.getPlayer()); EnemyAi ai = null; if (type == 0) { //ai = new PassiveAi(); } else { System.out.println("No enemy type corresponds to value: " + type + ". Instantiating basic enemy"); } e.setAI(ai); return e; } }
package revert.Entities; import java.awt.Point; import com.kgp.util.Vector2; import revert.AI.EnemyAi; import revert.MainScene.World; public class EnemyFactory { Vector2[] spawnPoints; World world; public EnemyFactory(World world, Vector2... spawns) { this.spawnPoints = spawns; this.world = world; } /** * Create a data set array * @param size * @return */ public int[][] createWave(int size) { int[][] wave = new int[size][]; for (int i = 0; i < size; i++) { Vector2 loc = spawnPoints[(int)(Math.random()*spawnPoints.length)]; int[] n = {(int)loc.x, (int)loc.y, (int)(Math.random()*3)}; wave[i] = n; } return wave; } public Enemy generateEnemy(int type) { Enemy e = new Enemy(world, world.getPlayer()); EnemyAi ai = null; if (type == 0) { //ai = new PassiveAi(); } else { System.out.println("No enemy type corresponds to value: " + type + ". Instantiating basic enemy"); } e.setAI(ai); return e; } }
Fix enemy factory since world is now using vector2
Fix enemy factory since world is now using vector2
Java
mit
nhydock/revert
java
## Code Before: package revert.Entities; import java.awt.Point; import revert.AI.EnemyAi; import revert.MainScene.World; public class EnemyFactory { Point[] spawnPoints; World world; public EnemyFactory(World world, Point... spawns) { this.spawnPoints = spawns; this.world = world; } /** * Create a data set array * @param size * @return */ public int[][] createWave(int size) { int[][] wave = new int[size][]; for (int i = 0; i < size; i++) { Point loc = spawnPoints[(int)(Math.random()*spawnPoints.length)]; int[] n = {loc.x, loc.y, (int)(Math.random()*3)}; wave[i] = n; } return wave; } public Enemy generateEnemy(int type) { Enemy e = new Enemy(world, world.getPlayer()); EnemyAi ai = null; if (type == 0) { //ai = new PassiveAi(); } else { System.out.println("No enemy type corresponds to value: " + type + ". Instantiating basic enemy"); } e.setAI(ai); return e; } } ## Instruction: Fix enemy factory since world is now using vector2 ## Code After: package revert.Entities; import java.awt.Point; import com.kgp.util.Vector2; import revert.AI.EnemyAi; import revert.MainScene.World; public class EnemyFactory { Vector2[] spawnPoints; World world; public EnemyFactory(World world, Vector2... spawns) { this.spawnPoints = spawns; this.world = world; } /** * Create a data set array * @param size * @return */ public int[][] createWave(int size) { int[][] wave = new int[size][]; for (int i = 0; i < size; i++) { Vector2 loc = spawnPoints[(int)(Math.random()*spawnPoints.length)]; int[] n = {(int)loc.x, (int)loc.y, (int)(Math.random()*3)}; wave[i] = n; } return wave; } public Enemy generateEnemy(int type) { Enemy e = new Enemy(world, world.getPlayer()); EnemyAi ai = null; if (type == 0) { //ai = new PassiveAi(); } else { System.out.println("No enemy type corresponds to value: " + type + ". Instantiating basic enemy"); } e.setAI(ai); return e; } }
// ... existing code ... package revert.Entities; import java.awt.Point; import com.kgp.util.Vector2; import revert.AI.EnemyAi; import revert.MainScene.World; // ... modified code ... public class EnemyFactory { Vector2[] spawnPoints; World world; public EnemyFactory(World world, Vector2... spawns) { this.spawnPoints = spawns; this.world = world; ... for (int i = 0; i < size; i++) { Vector2 loc = spawnPoints[(int)(Math.random()*spawnPoints.length)]; int[] n = {(int)loc.x, (int)loc.y, (int)(Math.random()*3)}; wave[i] = n; } // ... rest of the code ...
33f28ad9ba7c6eeec1f85be43863ea4c7b04128f
setup.py
setup.py
from distutils.core import setup, Extension setup ( name='PPeg', version='0.9', description="A Python port of Lua's LPeg pattern matching library", url='https://bitbucket.org/pmoore/ppeg', author='Paul Moore', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2 :: Only', 'Topic :: Text Processing :: General', ], keywords='parsing peg grammar regex', ext_modules = [Extension('_ppeg', ['_ppeg.c']), Extension('_cpeg', ['_cpeg.c'])], py_modules=[ 'PythonImpl', 'pegmatcher', ], )
from distutils.core import setup, Extension setup ( name='PPeg', version='0.9', description="A Python port of Lua's LPeg pattern matching library", url='https://bitbucket.org/pmoore/ppeg', author='Paul Moore', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2 :: Only', 'Topic :: Text Processing :: General', ], keywords='parsing peg grammar regex', ext_modules = [Extension('_ppeg', ['_ppeg.c', 'lpeg.c']), Extension('_cpeg', ['_cpeg.c'])], py_modules=[ 'PythonImpl', 'pegmatcher', ], )
Add lpeg.c to _ppeg.c dependencies
Add lpeg.c to _ppeg.c dependencies
Python
mit
moreati/ppeg,moreati/ppeg
python
## Code Before: from distutils.core import setup, Extension setup ( name='PPeg', version='0.9', description="A Python port of Lua's LPeg pattern matching library", url='https://bitbucket.org/pmoore/ppeg', author='Paul Moore', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2 :: Only', 'Topic :: Text Processing :: General', ], keywords='parsing peg grammar regex', ext_modules = [Extension('_ppeg', ['_ppeg.c']), Extension('_cpeg', ['_cpeg.c'])], py_modules=[ 'PythonImpl', 'pegmatcher', ], ) ## Instruction: Add lpeg.c to _ppeg.c dependencies ## Code After: from distutils.core import setup, Extension setup ( name='PPeg', version='0.9', description="A Python port of Lua's LPeg pattern matching library", url='https://bitbucket.org/pmoore/ppeg', author='Paul Moore', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2 :: Only', 'Topic :: Text Processing :: General', ], keywords='parsing peg grammar regex', ext_modules = [Extension('_ppeg', ['_ppeg.c', 'lpeg.c']), Extension('_cpeg', ['_cpeg.c'])], py_modules=[ 'PythonImpl', 'pegmatcher', ], )
// ... existing code ... keywords='parsing peg grammar regex', ext_modules = [Extension('_ppeg', ['_ppeg.c', 'lpeg.c']), Extension('_cpeg', ['_cpeg.c'])], py_modules=[ 'PythonImpl', // ... rest of the code ...
2706d3086eaff99538eacaafa58776393ab1f5d6
setup.py
setup.py
from setuptools import setup from storm import version # magic setup( name='tornado-storm', version=version, description='A simple ORM for Tornado', author='Craig Campbell', author_email='[email protected]', url='https://github.com/ccampbell/storm', download_url='https://github.com/ccampbell/storm/archive/0.1.0.zip#egg=tornado-storm-0.1.0', license='MIT', install_requires=['tornado >= 3.1', 'motor == 0.1.1'], py_modules=['storm'], platforms=["any"] )
from setuptools import setup, find_packages from storm import version # magic setup( name='tornado-storm', version=version, description='A simple ORM for Tornado', author='Craig Campbell', author_email='[email protected]', url='https://github.com/ccampbell/storm', download_url='https://github.com/ccampbell/storm/archive/0.1.0.zip#egg=tornado-storm-0.1.0', license='MIT', install_requires=['tornado >= 3.1', 'motor >= 0.1.1'], packages=find_packages(), py_modules=['storm'], platforms=["any"] )
Make sure installation works locally
Make sure installation works locally
Python
mit
ccampbell/storm,liujiantong/storm
python
## Code Before: from setuptools import setup from storm import version # magic setup( name='tornado-storm', version=version, description='A simple ORM for Tornado', author='Craig Campbell', author_email='[email protected]', url='https://github.com/ccampbell/storm', download_url='https://github.com/ccampbell/storm/archive/0.1.0.zip#egg=tornado-storm-0.1.0', license='MIT', install_requires=['tornado >= 3.1', 'motor == 0.1.1'], py_modules=['storm'], platforms=["any"] ) ## Instruction: Make sure installation works locally ## Code After: from setuptools import setup, find_packages from storm import version # magic setup( name='tornado-storm', version=version, description='A simple ORM for Tornado', author='Craig Campbell', author_email='[email protected]', url='https://github.com/ccampbell/storm', download_url='https://github.com/ccampbell/storm/archive/0.1.0.zip#egg=tornado-storm-0.1.0', license='MIT', install_requires=['tornado >= 3.1', 'motor >= 0.1.1'], packages=find_packages(), py_modules=['storm'], platforms=["any"] )
# ... existing code ... from setuptools import setup, find_packages from storm import version # magic # ... modified code ... url='https://github.com/ccampbell/storm', download_url='https://github.com/ccampbell/storm/archive/0.1.0.zip#egg=tornado-storm-0.1.0', license='MIT', install_requires=['tornado >= 3.1', 'motor >= 0.1.1'], packages=find_packages(), py_modules=['storm'], platforms=["any"] ) # ... rest of the code ...
eab249a092da21d47b07fd9918d4b28dcbc6089b
server/dummy/dummy_server.py
server/dummy/dummy_server.py
import BaseHTTPServer ServerClass = BaseHTTPServer.HTTPServer RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler SERVER_NAME = '' SERVER_PORT = 9000 class JsonPostResponder(RequestHandlerClass): def _get_content_from_stream(self, length, stream): return stream.read(length) def do_POST(self): content_length = int(self.headers['Content-Length']) content = self._get_content_from_stream(content_length, self.rfile) print '\n---> dummy server: got post!' print 'command:', self.command print 'path:', self.path print 'headers:\n\n', self.headers print 'content:\n\n', content, '\n' self.send_response(200) self.end_headers() server_address = (SERVER_NAME, SERVER_PORT) httpd = ServerClass(server_address, JsonPostResponder) httpd.serve_forever()
import BaseHTTPServer ServerClass = BaseHTTPServer.HTTPServer RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler SERVER_NAME = '' SERVER_PORT = 9000 class JsonPostResponder(RequestHandlerClass): def _get_content_from_stream(self, length, stream): return stream.read(length) def do_POST(self): content_length = int(self.headers['Content-Length']) content = self._get_content_from_stream(content_length, self.rfile) print('\n--- %s%s\n%s' % (self.command, self.path, self.headers)) print content, '\n' self.send_response(200) self.end_headers() server_address = (SERVER_NAME, SERVER_PORT) httpd = ServerClass(server_address, JsonPostResponder) httpd.serve_forever()
Clean up content and header output
Clean up content and header output
Python
mit
jonspeicher/Puddle,jonspeicher/Puddle,jonspeicher/Puddle
python
## Code Before: import BaseHTTPServer ServerClass = BaseHTTPServer.HTTPServer RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler SERVER_NAME = '' SERVER_PORT = 9000 class JsonPostResponder(RequestHandlerClass): def _get_content_from_stream(self, length, stream): return stream.read(length) def do_POST(self): content_length = int(self.headers['Content-Length']) content = self._get_content_from_stream(content_length, self.rfile) print '\n---> dummy server: got post!' print 'command:', self.command print 'path:', self.path print 'headers:\n\n', self.headers print 'content:\n\n', content, '\n' self.send_response(200) self.end_headers() server_address = (SERVER_NAME, SERVER_PORT) httpd = ServerClass(server_address, JsonPostResponder) httpd.serve_forever() ## Instruction: Clean up content and header output ## Code After: import BaseHTTPServer ServerClass = BaseHTTPServer.HTTPServer RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler SERVER_NAME = '' SERVER_PORT = 9000 class JsonPostResponder(RequestHandlerClass): def _get_content_from_stream(self, length, stream): return stream.read(length) def do_POST(self): content_length = int(self.headers['Content-Length']) content = self._get_content_from_stream(content_length, self.rfile) print('\n--- %s%s\n%s' % (self.command, self.path, self.headers)) print content, '\n' self.send_response(200) self.end_headers() server_address = (SERVER_NAME, SERVER_PORT) httpd = ServerClass(server_address, JsonPostResponder) httpd.serve_forever()
... content_length = int(self.headers['Content-Length']) content = self._get_content_from_stream(content_length, self.rfile) print('\n--- %s%s\n%s' % (self.command, self.path, self.headers)) print content, '\n' self.send_response(200) self.end_headers() ...
de17439cf237d073236fffd0130c883683f1ba28
tokens/models.py
tokens/models.py
from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from .conf import PHASES, TOKEN_TYPES class Token(models.Model): public_name = models.CharField(max_length=200) symbol = models.CharField(max_length=4) decimals = models.IntegerField( default=18, validators=[MaxValueValidator(20), MinValueValidator(0)] ) phase = models.CharField( max_length=8, choices=PHASES, default=PHASES[0][0], ) token_type = models.CharField( max_length=12, choices=TOKEN_TYPES, default=TOKEN_TYPES[0][0], )
from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from .conf import PHASES, TOKEN_TYPES class Token(models.Model): public_name = models.CharField(max_length=200) symbol = models.CharField(max_length=4) decimals = models.IntegerField( default=18, validators=[MaxValueValidator(20), MinValueValidator(0)] ) phase = models.CharField( max_length=8, choices=PHASES, default=PHASES[0][0], ) token_type = models.CharField( max_length=12, choices=TOKEN_TYPES, default=TOKEN_TYPES[0][0], ) @property def class_name(self): return ''.join( map(lambda s: s.title(), self.public_name.split()) )
Add class_name property to Token model
Add class_name property to Token model
Python
apache-2.0
onyb/ethane,onyb/ethane,onyb/ethane,onyb/ethane
python
## Code Before: from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from .conf import PHASES, TOKEN_TYPES class Token(models.Model): public_name = models.CharField(max_length=200) symbol = models.CharField(max_length=4) decimals = models.IntegerField( default=18, validators=[MaxValueValidator(20), MinValueValidator(0)] ) phase = models.CharField( max_length=8, choices=PHASES, default=PHASES[0][0], ) token_type = models.CharField( max_length=12, choices=TOKEN_TYPES, default=TOKEN_TYPES[0][0], ) ## Instruction: Add class_name property to Token model ## Code After: from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from .conf import PHASES, TOKEN_TYPES class Token(models.Model): public_name = models.CharField(max_length=200) symbol = models.CharField(max_length=4) decimals = models.IntegerField( default=18, validators=[MaxValueValidator(20), MinValueValidator(0)] ) phase = models.CharField( max_length=8, choices=PHASES, default=PHASES[0][0], ) token_type = models.CharField( max_length=12, choices=TOKEN_TYPES, default=TOKEN_TYPES[0][0], ) @property def class_name(self): return ''.join( map(lambda s: s.title(), self.public_name.split()) )
... choices=TOKEN_TYPES, default=TOKEN_TYPES[0][0], ) @property def class_name(self): return ''.join( map(lambda s: s.title(), self.public_name.split()) ) ...
12352c1f7c9751727b8bd98ece576f9d690b520e
corehq/apps/export/migrations/0008_auto_20190906_2008.py
corehq/apps/export/migrations/0008_auto_20190906_2008.py
from __future__ import unicode_literals from django.db import migrations from corehq.apps.es.aggregations import ( AggregationTerm, NestedTermAggregationsHelper, ) from corehq.apps.es.ledgers import LedgerES from corehq.apps.export.models.new import LedgerSectionEntry from corehq.util.django_migrations import skip_on_fresh_install @skip_on_fresh_install def initialize_ledger_combinations(apps, schema_editor): terms = [ AggregationTerm('domain', 'domain'), AggregationTerm('section_id', 'section_id'), AggregationTerm('entry_id', 'entry_id'), ] combos = [ a for a in NestedTermAggregationsHelper(base_query=LedgerES(), terms=terms).get_data() ] for combo in combos: LedgerSectionEntry.objects.get_or_create( domain=combo.domain, section_id=combo.section_id, entry_id=combo.entry_id, ) class Migration(migrations.Migration): dependencies = [ ('export', '0007_auto_20190906_0149'), ] operations = [ migrations.RunPython(initialize_ledger_combinations, elidable=True), ]
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): """ This migration used to contain some initialization for LedgerSectionEntry. At the time it was run, this model was only used by exports and only on Supply projects """ dependencies = [ ('export', '0007_auto_20190906_0149'), ] operations = [ ]
Remove data migration from migration file
Remove data migration from migration file
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
python
## Code Before: from __future__ import unicode_literals from django.db import migrations from corehq.apps.es.aggregations import ( AggregationTerm, NestedTermAggregationsHelper, ) from corehq.apps.es.ledgers import LedgerES from corehq.apps.export.models.new import LedgerSectionEntry from corehq.util.django_migrations import skip_on_fresh_install @skip_on_fresh_install def initialize_ledger_combinations(apps, schema_editor): terms = [ AggregationTerm('domain', 'domain'), AggregationTerm('section_id', 'section_id'), AggregationTerm('entry_id', 'entry_id'), ] combos = [ a for a in NestedTermAggregationsHelper(base_query=LedgerES(), terms=terms).get_data() ] for combo in combos: LedgerSectionEntry.objects.get_or_create( domain=combo.domain, section_id=combo.section_id, entry_id=combo.entry_id, ) class Migration(migrations.Migration): dependencies = [ ('export', '0007_auto_20190906_0149'), ] operations = [ migrations.RunPython(initialize_ledger_combinations, elidable=True), ] ## Instruction: Remove data migration from migration file ## Code After: from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): """ This migration used to contain some initialization for LedgerSectionEntry. At the time it was run, this model was only used by exports and only on Supply projects """ dependencies = [ ('export', '0007_auto_20190906_0149'), ] operations = [ ]
# ... existing code ... from django.db import migrations class Migration(migrations.Migration): """ This migration used to contain some initialization for LedgerSectionEntry. At the time it was run, this model was only used by exports and only on Supply projects """ dependencies = [ ('export', '0007_auto_20190906_0149'), # ... modified code ... ] operations = [ ] # ... rest of the code ...
34db881007bf0dad3b7e870d36ab4e4a68b0fd3d
emcee/run_emcee.py
emcee/run_emcee.py
from os.path import abspath, join as pathjoin from shutil import copy from subprocess import call from tempfile import mkdtemp install_dir = mkdtemp(prefix='emcee.') games_dir = abspath(pathjoin('..', 'games')) libraries_dir = abspath('libraries') infra_dir = abspath('infra') print 'Installing emcee in %s' % (install_dir,) print 'Games in %s' % (games_dir,) print 'Libraries in %s' % (libraries_dir,) print 'Infrastructure files in %s' % (infra_dir,) copy('emcee.py', install_dir) copy(pathjoin('libraries', 'pubsub.py'), install_dir) call([pathjoin(install_dir, 'emcee.py'), games_dir, libraries_dir, infra_dir], cwd=install_dir)
from os.path import abspath, join as pathjoin from shutil import copy from subprocess import Popen from tempfile import mkdtemp install_dir = mkdtemp(prefix='emcee.') games_dir = abspath(pathjoin('..', 'games')) libraries_dir = abspath('libraries') infra_dir = abspath('infra') print 'Installing emcee in %s' % (install_dir,) print 'Games in %s' % (games_dir,) print 'Libraries in %s' % (libraries_dir,) print 'Infrastructure files in %s' % (infra_dir,) copy('emcee.py', install_dir) copy('pubsub_ws.py', install_dir) copy('pubsub_ws_doc.html', install_dir) copy(pathjoin('libraries', 'pubsub.py'), install_dir) processes = [] processes.append(Popen([pathjoin(install_dir, 'emcee.py'), games_dir, libraries_dir, infra_dir], cwd=install_dir)) processes.append(Popen([pathjoin(install_dir, 'pubsub_ws.py'), infra_dir], cwd=install_dir)) print 'Now running' raw_input('Press Enter to stop') map(lambda(p): p.kill(), processes)
Deploy pubsub_ws along with emcee
Deploy pubsub_ws along with emcee
Python
mit
douglassquirrel/alexandra,douglassquirrel/alexandra,douglassquirrel/alexandra
python
## Code Before: from os.path import abspath, join as pathjoin from shutil import copy from subprocess import call from tempfile import mkdtemp install_dir = mkdtemp(prefix='emcee.') games_dir = abspath(pathjoin('..', 'games')) libraries_dir = abspath('libraries') infra_dir = abspath('infra') print 'Installing emcee in %s' % (install_dir,) print 'Games in %s' % (games_dir,) print 'Libraries in %s' % (libraries_dir,) print 'Infrastructure files in %s' % (infra_dir,) copy('emcee.py', install_dir) copy(pathjoin('libraries', 'pubsub.py'), install_dir) call([pathjoin(install_dir, 'emcee.py'), games_dir, libraries_dir, infra_dir], cwd=install_dir) ## Instruction: Deploy pubsub_ws along with emcee ## Code After: from os.path import abspath, join as pathjoin from shutil import copy from subprocess import Popen from tempfile import mkdtemp install_dir = mkdtemp(prefix='emcee.') games_dir = abspath(pathjoin('..', 'games')) libraries_dir = abspath('libraries') infra_dir = abspath('infra') print 'Installing emcee in %s' % (install_dir,) print 'Games in %s' % (games_dir,) print 'Libraries in %s' % (libraries_dir,) print 'Infrastructure files in %s' % (infra_dir,) copy('emcee.py', install_dir) copy('pubsub_ws.py', install_dir) copy('pubsub_ws_doc.html', install_dir) copy(pathjoin('libraries', 'pubsub.py'), install_dir) processes = [] processes.append(Popen([pathjoin(install_dir, 'emcee.py'), games_dir, libraries_dir, infra_dir], cwd=install_dir)) processes.append(Popen([pathjoin(install_dir, 'pubsub_ws.py'), infra_dir], cwd=install_dir)) print 'Now running' raw_input('Press Enter to stop') map(lambda(p): p.kill(), processes)
... from os.path import abspath, join as pathjoin from shutil import copy from subprocess import Popen from tempfile import mkdtemp install_dir = mkdtemp(prefix='emcee.') ... print 'Infrastructure files in %s' % (infra_dir,) copy('emcee.py', install_dir) copy('pubsub_ws.py', install_dir) copy('pubsub_ws_doc.html', install_dir) copy(pathjoin('libraries', 'pubsub.py'), install_dir) processes = [] processes.append(Popen([pathjoin(install_dir, 'emcee.py'), games_dir, libraries_dir, infra_dir], cwd=install_dir)) processes.append(Popen([pathjoin(install_dir, 'pubsub_ws.py'), infra_dir], cwd=install_dir)) print 'Now running' raw_input('Press Enter to stop') map(lambda(p): p.kill(), processes) ...
4bd2eb02d1c69eb5716281df2a4b977db3f325fd
gws-core/src/main/java/au/gov/ga/geodesy/domain/service/SiteLogReceivedNotificationService.java
gws-core/src/main/java/au/gov/ga/geodesy/domain/service/SiteLogReceivedNotificationService.java
package au.gov.ga.geodesy.domain.service; import org.springframework.stereotype.Component; import au.gov.ga.geodesy.domain.model.event.Event; import au.gov.ga.geodesy.domain.model.event.SiteLogReceived; @Component public class SiteLogReceivedNotificationService extends EventNotificationService<SiteLogReceived> { @Override public boolean canHandle(Event e) { return e instanceof SiteLogReceived; } }
package au.gov.ga.geodesy.domain.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import au.gov.ga.geodesy.domain.model.event.Event; import au.gov.ga.geodesy.domain.model.event.SiteLogReceived; import au.gov.ga.geodesy.port.Notification; @Component public class SiteLogReceivedNotificationService extends EventNotificationService<SiteLogReceived> { private static final Logger log = LoggerFactory.getLogger(SiteLogReceivedNotificationService.class); private ObjectMapper filteredJson; @Override public boolean canHandle(Event e) { return e instanceof SiteLogReceived; } @JsonFilter("excludeSiteLogText") public static class SiteLogReceivedFiltered {} public SiteLogReceivedNotificationService() { super(); this.filteredJson = json.copy(); FilterProvider filterProvider = new SimpleFilterProvider() .addFilter("excludeSiteLogText", SimpleBeanPropertyFilter.serializeAllExcept("siteLogText")); filteredJson.addMixIn(SiteLogReceived.class, SiteLogReceivedFiltered.class); filteredJson.setFilterProvider(filterProvider); } @Override protected Notification toNotification(SiteLogReceived event) { return new Notification() { public String getSubject() { return event.getName(); } public String getBody() { try { StringBuilder body = new StringBuilder(); body.append(filteredJson.writeValueAsString(event)); return body.toString(); } catch (JsonProcessingException e) { String errorMessage = "Failed to serialise event with id " + event.getId(); log.error(errorMessage, e); return errorMessage; } } }; } }
Drop siteLogText from SiteLogReceived SNS msg
Drop siteLogText from SiteLogReceived SNS msg
Java
bsd-3-clause
GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/Geodesy-Web-Services,GeoscienceAustralia/geodesy-domain-model,GeoscienceAustralia/Geodesy-Web-Services
java
## Code Before: package au.gov.ga.geodesy.domain.service; import org.springframework.stereotype.Component; import au.gov.ga.geodesy.domain.model.event.Event; import au.gov.ga.geodesy.domain.model.event.SiteLogReceived; @Component public class SiteLogReceivedNotificationService extends EventNotificationService<SiteLogReceived> { @Override public boolean canHandle(Event e) { return e instanceof SiteLogReceived; } } ## Instruction: Drop siteLogText from SiteLogReceived SNS msg ## Code After: package au.gov.ga.geodesy.domain.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import au.gov.ga.geodesy.domain.model.event.Event; import au.gov.ga.geodesy.domain.model.event.SiteLogReceived; import au.gov.ga.geodesy.port.Notification; @Component public class SiteLogReceivedNotificationService extends EventNotificationService<SiteLogReceived> { private static final Logger log = LoggerFactory.getLogger(SiteLogReceivedNotificationService.class); private ObjectMapper filteredJson; @Override public boolean canHandle(Event e) { return e instanceof SiteLogReceived; } @JsonFilter("excludeSiteLogText") public static class SiteLogReceivedFiltered {} public SiteLogReceivedNotificationService() { super(); this.filteredJson = json.copy(); FilterProvider filterProvider = new SimpleFilterProvider() .addFilter("excludeSiteLogText", SimpleBeanPropertyFilter.serializeAllExcept("siteLogText")); filteredJson.addMixIn(SiteLogReceived.class, SiteLogReceivedFiltered.class); filteredJson.setFilterProvider(filterProvider); } @Override protected Notification toNotification(SiteLogReceived event) { return new Notification() { public String getSubject() { return event.getName(); } public String getBody() { try { StringBuilder body = new StringBuilder(); body.append(filteredJson.writeValueAsString(event)); return body.toString(); } catch (JsonProcessingException e) { String errorMessage = "Failed to serialise event with id " + event.getId(); log.error(errorMessage, e); return errorMessage; } } }; } }
... package au.gov.ga.geodesy.domain.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; import au.gov.ga.geodesy.domain.model.event.Event; import au.gov.ga.geodesy.domain.model.event.SiteLogReceived; import au.gov.ga.geodesy.port.Notification; @Component public class SiteLogReceivedNotificationService extends EventNotificationService<SiteLogReceived> { private static final Logger log = LoggerFactory.getLogger(SiteLogReceivedNotificationService.class); private ObjectMapper filteredJson; @Override public boolean canHandle(Event e) { return e instanceof SiteLogReceived; } @JsonFilter("excludeSiteLogText") public static class SiteLogReceivedFiltered {} public SiteLogReceivedNotificationService() { super(); this.filteredJson = json.copy(); FilterProvider filterProvider = new SimpleFilterProvider() .addFilter("excludeSiteLogText", SimpleBeanPropertyFilter.serializeAllExcept("siteLogText")); filteredJson.addMixIn(SiteLogReceived.class, SiteLogReceivedFiltered.class); filteredJson.setFilterProvider(filterProvider); } @Override protected Notification toNotification(SiteLogReceived event) { return new Notification() { public String getSubject() { return event.getName(); } public String getBody() { try { StringBuilder body = new StringBuilder(); body.append(filteredJson.writeValueAsString(event)); return body.toString(); } catch (JsonProcessingException e) { String errorMessage = "Failed to serialise event with id " + event.getId(); log.error(errorMessage, e); return errorMessage; } } }; } } ...
5911058ed7b2dffeee623df99eb4a9abf4de675f
axelor-base/src/main/java/com/axelor/apps/base/web/YearController.java
axelor-base/src/main/java/com/axelor/apps/base/web/YearController.java
package com.axelor.apps.base.web; import com.axelor.apps.base.db.Year; import com.axelor.apps.base.service.YearService; import com.axelor.exception.AxelorException; import com.axelor.exception.service.TraceBackService; import com.axelor.inject.Beans; import com.axelor.rpc.ActionRequest; import com.axelor.rpc.ActionResponse; import com.google.inject.Inject; public class YearController { public void generatePeriods(ActionRequest request, ActionResponse response) throws AxelorException { try { Year year = request.getContext().asType(Year.class); response.setValue("periodList", Beans.get(YearService.class).generatePeriods(year)); } catch (Exception e) { TraceBackService.trace(response, e); } } }
package com.axelor.apps.base.web; import com.axelor.apps.base.db.Year; import com.axelor.apps.base.service.YearService; import com.axelor.exception.AxelorException; import com.axelor.exception.service.TraceBackService; import com.axelor.inject.Beans; import com.axelor.rpc.ActionRequest; import com.axelor.rpc.ActionResponse; public class YearController { public void generatePeriods(ActionRequest request, ActionResponse response) throws AxelorException { try { Year year = request.getContext().asType(Year.class); response.setValue("periodList", Beans.get(YearService.class).generatePeriods(year)); } catch (Exception e) { TraceBackService.trace(response, e); } } }
Apply spotless java google code format
Apply spotless java google code format
Java
agpl-3.0
axelor/axelor-business-suite,axelor/axelor-business-suite,axelor/axelor-business-suite
java
## Code Before: package com.axelor.apps.base.web; import com.axelor.apps.base.db.Year; import com.axelor.apps.base.service.YearService; import com.axelor.exception.AxelorException; import com.axelor.exception.service.TraceBackService; import com.axelor.inject.Beans; import com.axelor.rpc.ActionRequest; import com.axelor.rpc.ActionResponse; import com.google.inject.Inject; public class YearController { public void generatePeriods(ActionRequest request, ActionResponse response) throws AxelorException { try { Year year = request.getContext().asType(Year.class); response.setValue("periodList", Beans.get(YearService.class).generatePeriods(year)); } catch (Exception e) { TraceBackService.trace(response, e); } } } ## Instruction: Apply spotless java google code format ## Code After: package com.axelor.apps.base.web; import com.axelor.apps.base.db.Year; import com.axelor.apps.base.service.YearService; import com.axelor.exception.AxelorException; import com.axelor.exception.service.TraceBackService; import com.axelor.inject.Beans; import com.axelor.rpc.ActionRequest; import com.axelor.rpc.ActionResponse; public class YearController { public void generatePeriods(ActionRequest request, ActionResponse response) throws AxelorException { try { Year year = request.getContext().asType(Year.class); response.setValue("periodList", Beans.get(YearService.class).generatePeriods(year)); } catch (Exception e) { TraceBackService.trace(response, e); } } }
// ... existing code ... import com.axelor.inject.Beans; import com.axelor.rpc.ActionRequest; import com.axelor.rpc.ActionResponse; public class YearController { public void generatePeriods(ActionRequest request, ActionResponse response) throws AxelorException { try { Year year = request.getContext().asType(Year.class); response.setValue("periodList", Beans.get(YearService.class).generatePeriods(year)); } catch (Exception e) { TraceBackService.trace(response, e); // ... rest of the code ...
de0bb4886b9a6ecd2fb4e5c4272167911141c71c
apic_ml2/neutron/plugins/ml2/drivers/cisco/apic/nova_client.py
apic_ml2/neutron/plugins/ml2/drivers/cisco/apic/nova_client.py
from neutron._i18n import _LW from neutron.notifiers import nova as n_nova from novaclient import exceptions as nova_exceptions from oslo_log import log as logging LOG = logging.getLogger(__name__) class NovaClient(object): def __init__(self): self.nclient = n_nova.Notifier().nclient def get_server(self, server_id): try: return self.nclient.servers.get(server_id) except nova_exceptions.NotFound: LOG.warning(_LW("Nova returned NotFound for server: %s"), server_id) except Exception as e: LOG.exception(e)
from neutron._i18n import _LW from neutron.notifiers import nova as n_nova from novaclient import exceptions as nova_exceptions from oslo_log import log as logging LOG = logging.getLogger(__name__) client = None def _get_client(): global client if client is None: client = n_nova.Notifier().nclient return client class NovaClient(object): def __init__(self): self.client = n_nova.Notifier().nclient def get_server(self, server_id): try: return self.client.servers.get(server_id) except nova_exceptions.NotFound: LOG.warning(_LW("Nova returned NotFound for server: %s"), server_id) except Exception as e: LOG.exception(e)
Load Nova Client only once to avoid reconnecting
Load Nova Client only once to avoid reconnecting
Python
apache-2.0
noironetworks/apic-ml2-driver,noironetworks/apic-ml2-driver
python
## Code Before: from neutron._i18n import _LW from neutron.notifiers import nova as n_nova from novaclient import exceptions as nova_exceptions from oslo_log import log as logging LOG = logging.getLogger(__name__) class NovaClient(object): def __init__(self): self.nclient = n_nova.Notifier().nclient def get_server(self, server_id): try: return self.nclient.servers.get(server_id) except nova_exceptions.NotFound: LOG.warning(_LW("Nova returned NotFound for server: %s"), server_id) except Exception as e: LOG.exception(e) ## Instruction: Load Nova Client only once to avoid reconnecting ## Code After: from neutron._i18n import _LW from neutron.notifiers import nova as n_nova from novaclient import exceptions as nova_exceptions from oslo_log import log as logging LOG = logging.getLogger(__name__) client = None def _get_client(): global client if client is None: client = n_nova.Notifier().nclient return client class NovaClient(object): def __init__(self): self.client = n_nova.Notifier().nclient def get_server(self, server_id): try: return self.client.servers.get(server_id) except nova_exceptions.NotFound: LOG.warning(_LW("Nova returned NotFound for server: %s"), server_id) except Exception as e: LOG.exception(e)
// ... existing code ... from novaclient import exceptions as nova_exceptions from oslo_log import log as logging LOG = logging.getLogger(__name__) client = None def _get_client(): global client if client is None: client = n_nova.Notifier().nclient return client class NovaClient(object): def __init__(self): self.client = n_nova.Notifier().nclient def get_server(self, server_id): try: return self.client.servers.get(server_id) except nova_exceptions.NotFound: LOG.warning(_LW("Nova returned NotFound for server: %s"), server_id) // ... rest of the code ...
05c3775c589b5afdb9f3d7d3e347615d699669c7
catwatch/blueprints/issue/views.py
catwatch/blueprints/issue/views.py
from flask import ( Blueprint, flash, redirect, url_for, render_template) from flask_login import current_user from flask_babel import gettext as _ from catwatch.blueprints.issue.models import Issue from catwatch.blueprints.issue.forms import SupportForm issue = Blueprint('issue', __name__, template_folder='templates') @issue.route('/support', methods=['GET', 'POST']) def support(): # Pre-populate the email field if the user is signed in. form = SupportForm(obj=current_user) if form.validate_on_submit(): i = Issue() form.populate_obj(i) i.save() flash(_('Help is on the way, expect a response shortly.'), 'success') return redirect(url_for('issue.support')) return render_template('issue/support.jinja2', form=form)
from flask import ( Blueprint, flash, redirect, url_for, render_template) from flask_login import current_user from flask_babel import gettext as _ from catwatch.blueprints.issue.models import Issue from catwatch.blueprints.issue.forms import SupportForm issue = Blueprint('issue', __name__, template_folder='templates') @issue.route('/support', methods=['GET', 'POST']) def support(): form = SupportForm(obj=current_user) if form.validate_on_submit(): i = Issue() form.populate_obj(i) i.save() flash(_('Help is on the way, expect a response shortly.'), 'success') return redirect(url_for('issue.support')) return render_template('issue/support.jinja2', form=form)
Normalize the issue blueprint's code base
Normalize the issue blueprint's code base
Python
mit
nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask
python
## Code Before: from flask import ( Blueprint, flash, redirect, url_for, render_template) from flask_login import current_user from flask_babel import gettext as _ from catwatch.blueprints.issue.models import Issue from catwatch.blueprints.issue.forms import SupportForm issue = Blueprint('issue', __name__, template_folder='templates') @issue.route('/support', methods=['GET', 'POST']) def support(): # Pre-populate the email field if the user is signed in. form = SupportForm(obj=current_user) if form.validate_on_submit(): i = Issue() form.populate_obj(i) i.save() flash(_('Help is on the way, expect a response shortly.'), 'success') return redirect(url_for('issue.support')) return render_template('issue/support.jinja2', form=form) ## Instruction: Normalize the issue blueprint's code base ## Code After: from flask import ( Blueprint, flash, redirect, url_for, render_template) from flask_login import current_user from flask_babel import gettext as _ from catwatch.blueprints.issue.models import Issue from catwatch.blueprints.issue.forms import SupportForm issue = Blueprint('issue', __name__, template_folder='templates') @issue.route('/support', methods=['GET', 'POST']) def support(): form = SupportForm(obj=current_user) if form.validate_on_submit(): i = Issue() form.populate_obj(i) i.save() flash(_('Help is on the way, expect a response shortly.'), 'success') return redirect(url_for('issue.support')) return render_template('issue/support.jinja2', form=form)
// ... existing code ... @issue.route('/support', methods=['GET', 'POST']) def support(): form = SupportForm(obj=current_user) if form.validate_on_submit(): // ... rest of the code ...
80215a593c2fdcf0a0ae8b1c61c4342faffd6dac
run.py
run.py
import bb2gh import time config_yaml = 'config.yaml' for issue_id in range(1, 500): while True: try: bb2gh.migrate(config_yaml, verbose=True, issue_ids=[issue_id]) except Exception as inst: print 'issue_id',issue_id print type(inst) print inst.data['message'] print 'waiting for 60 seconds' print time.sleep(60) else: break
import bb2gh import time config_yaml = 'config.yaml' for issue_id in range(190, 500): while True: try: bb2gh.migrate(config_yaml, verbose=True, issue_ids=[issue_id]) except Exception as inst: print 'issue_id',issue_id print type(inst) print inst print 'waiting for 60 seconds' print time.sleep(60) else: break
Fix bug, 'message' key throwing error.
Fix bug, 'message' key throwing error.
Python
mit
wd15/bb2gh
python
## Code Before: import bb2gh import time config_yaml = 'config.yaml' for issue_id in range(1, 500): while True: try: bb2gh.migrate(config_yaml, verbose=True, issue_ids=[issue_id]) except Exception as inst: print 'issue_id',issue_id print type(inst) print inst.data['message'] print 'waiting for 60 seconds' print time.sleep(60) else: break ## Instruction: Fix bug, 'message' key throwing error. ## Code After: import bb2gh import time config_yaml = 'config.yaml' for issue_id in range(190, 500): while True: try: bb2gh.migrate(config_yaml, verbose=True, issue_ids=[issue_id]) except Exception as inst: print 'issue_id',issue_id print type(inst) print inst print 'waiting for 60 seconds' print time.sleep(60) else: break
... config_yaml = 'config.yaml' for issue_id in range(190, 500): while True: try: bb2gh.migrate(config_yaml, verbose=True, issue_ids=[issue_id]) ... except Exception as inst: print 'issue_id',issue_id print type(inst) print inst print 'waiting for 60 seconds' print time.sleep(60) ...
f6cd6b3377769af524377979438b9e662bb9175a
tangled/site/model/base.py
tangled/site/model/base.py
import datetime from sqlalchemy.schema import Column from sqlalchemy.types import DateTime, Integer from sqlalchemy.ext.declarative import declarative_base, declared_attr Base = declarative_base() class BaseMixin: id = Column(Integer, primary_key=True) @declared_attr def __tablename__(cls): return cls.__name__.lower() class TimestampMixin: created_at = Column( DateTime, nullable=False, default=datetime.datetime.now) updated_at = Column(DateTime)
from datetime import datetime from sqlalchemy.schema import Column from sqlalchemy.types import DateTime, Integer from sqlalchemy.ext.declarative import declarative_base, declared_attr Base = declarative_base() class BaseMixin: id = Column(Integer, primary_key=True) @declared_attr def __tablename__(cls): return cls.__name__.lower() class TimestampMixin: created_at = Column(DateTime, nullable=False, default=datetime.now) updated_at = Column(DateTime, onupdate=datetime.now)
Update updated time on update
Update updated time on update I.e., added onupdate=datetime.now to TimestampMixin.updated_at so that it will be automatically updated whenever a record is edited.
Python
mit
TangledWeb/tangled.site
python
## Code Before: import datetime from sqlalchemy.schema import Column from sqlalchemy.types import DateTime, Integer from sqlalchemy.ext.declarative import declarative_base, declared_attr Base = declarative_base() class BaseMixin: id = Column(Integer, primary_key=True) @declared_attr def __tablename__(cls): return cls.__name__.lower() class TimestampMixin: created_at = Column( DateTime, nullable=False, default=datetime.datetime.now) updated_at = Column(DateTime) ## Instruction: Update updated time on update I.e., added onupdate=datetime.now to TimestampMixin.updated_at so that it will be automatically updated whenever a record is edited. ## Code After: from datetime import datetime from sqlalchemy.schema import Column from sqlalchemy.types import DateTime, Integer from sqlalchemy.ext.declarative import declarative_base, declared_attr Base = declarative_base() class BaseMixin: id = Column(Integer, primary_key=True) @declared_attr def __tablename__(cls): return cls.__name__.lower() class TimestampMixin: created_at = Column(DateTime, nullable=False, default=datetime.now) updated_at = Column(DateTime, onupdate=datetime.now)
# ... existing code ... from datetime import datetime from sqlalchemy.schema import Column from sqlalchemy.types import DateTime, Integer # ... modified code ... class TimestampMixin: created_at = Column(DateTime, nullable=False, default=datetime.now) updated_at = Column(DateTime, onupdate=datetime.now) # ... rest of the code ...
4261aad86b40d052906b8162263e00aa7b12b5e7
pritunl_node/call_buffer.py
pritunl_node/call_buffer.py
from constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiter = None self.queue = collections.deque(maxlen=CALL_QUEUE_MAX) self.call_waiters = {} def wait_for_calls(self, callback): if self.waiter: self.waiter([]) self.waiter = None calls = [] while True: try: calls.append(self.queue.popleft()) except IndexError: break if calls: callback(calls) return self.waiter = callback def cancel_waiter(self): self.waiter = None def return_call(self, id, response): callback = self.call_waiters.pop(id, None) if callback: callback(response) def create_call(self, command, args, callback=None): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } if callback: self.call_waiters[call_id] = callback if self.waiter: self.waiter([call]) self.waiter = None else: self.queue.append(call)
from constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiter = None self.queue = collections.deque(maxlen=CALL_QUEUE_MAX) self.call_waiters = {} def wait_for_calls(self, callback): self.stop_waiter() calls = [] while True: try: calls.append(self.queue.popleft()) except IndexError: break if calls: callback(calls) return self.waiter = callback def cancel_waiter(self): self.waiter = None def stop_waiter(self): if self.waiter: self.waiter(None) self.waiter = None def return_call(self, id, response): callback = self.call_waiters.pop(id, None) if callback: callback(response) def create_call(self, command, args, callback=None): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } if callback: self.call_waiters[call_id] = callback if self.waiter: self.waiter([call]) self.waiter = None else: self.queue.append(call)
Add stop waiter to call buffer
Add stop waiter to call buffer
Python
agpl-3.0
pritunl/pritunl-node,pritunl/pritunl-node
python
## Code Before: from constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiter = None self.queue = collections.deque(maxlen=CALL_QUEUE_MAX) self.call_waiters = {} def wait_for_calls(self, callback): if self.waiter: self.waiter([]) self.waiter = None calls = [] while True: try: calls.append(self.queue.popleft()) except IndexError: break if calls: callback(calls) return self.waiter = callback def cancel_waiter(self): self.waiter = None def return_call(self, id, response): callback = self.call_waiters.pop(id, None) if callback: callback(response) def create_call(self, command, args, callback=None): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } if callback: self.call_waiters[call_id] = callback if self.waiter: self.waiter([call]) self.waiter = None else: self.queue.append(call) ## Instruction: Add stop waiter to call buffer ## Code After: from constants import * import collections import uuid class CallBuffer(): def __init__(self): self.waiter = None self.queue = collections.deque(maxlen=CALL_QUEUE_MAX) self.call_waiters = {} def wait_for_calls(self, callback): self.stop_waiter() calls = [] while True: try: calls.append(self.queue.popleft()) except IndexError: break if calls: callback(calls) return self.waiter = callback def cancel_waiter(self): self.waiter = None def stop_waiter(self): if self.waiter: self.waiter(None) self.waiter = None def return_call(self, id, response): callback = self.call_waiters.pop(id, None) if callback: callback(response) def create_call(self, command, args, callback=None): call_id = uuid.uuid4().hex call = { 'id': call_id, 'command': command, 'args': args, } if callback: self.call_waiters[call_id] = callback if self.waiter: self.waiter([call]) self.waiter = None else: self.queue.append(call)
... self.call_waiters = {} def wait_for_calls(self, callback): self.stop_waiter() calls = [] while True: try: ... def cancel_waiter(self): self.waiter = None def stop_waiter(self): if self.waiter: self.waiter(None) self.waiter = None def return_call(self, id, response): callback = self.call_waiters.pop(id, None) ...
2af5c49a60b2d69b7b8178003560cd641e1b5c22
monitor/src/main/java/de/graeuler/garden/config/StaticAppConfig.java
monitor/src/main/java/de/graeuler/garden/config/StaticAppConfig.java
package de.graeuler.garden.config; import java.util.EnumMap; public class StaticAppConfig implements AppConfig { private EnumMap<AppConfig.Key, Object> config = new EnumMap<>(Key.class); public StaticAppConfig() { this.config.put(AppConfig.Key.TF_DAEMON_HOST, "192.168.1.10"); this.config.put(AppConfig.Key.TF_DAEMON_PORT, Integer.valueOf(4223)); this.config.put(AppConfig.Key.UPLINK_ADRESS, "http://localhost:8081/datafeed/collect/garden"); // this.config.put(AppConfig.Key.API_TOKEN, "non-working-token"); } @Override public Object get(Key key) { if (config.containsKey(key)) return config.get(key); else return key.getDefaultValue(); } @Override public Object get(Key key, Object defaultValue) { return this.config.getOrDefault(key, defaultValue); } }
package de.graeuler.garden.config; import java.util.EnumMap; public class StaticAppConfig implements AppConfig { private EnumMap<AppConfig.Key, Object> config = new EnumMap<>(Key.class); public StaticAppConfig() { this.config.put(AppConfig.Key.TF_DAEMON_HOST, "localhost"); this.config.put(AppConfig.Key.TF_DAEMON_PORT, Integer.valueOf(4223)); this.config.put(AppConfig.Key.UPLINK_ADRESS, "http://localhost:8081/datafeed/collect/garden"); // this.config.put(AppConfig.Key.API_TOKEN, "non-working-token"); } @Override public Object get(Key key) { if (config.containsKey(key)) return config.get(key); else return key.getDefaultValue(); } @Override public Object get(Key key, Object defaultValue) { return this.config.getOrDefault(key, defaultValue); } }
Connect to localhost brick daemon.
Connect to localhost brick daemon.
Java
apache-2.0
de-graeuler/my-garden,de-graeuler/my-garden,de-graeuler/my-garden,de-graeuler/my-garden
java
## Code Before: package de.graeuler.garden.config; import java.util.EnumMap; public class StaticAppConfig implements AppConfig { private EnumMap<AppConfig.Key, Object> config = new EnumMap<>(Key.class); public StaticAppConfig() { this.config.put(AppConfig.Key.TF_DAEMON_HOST, "192.168.1.10"); this.config.put(AppConfig.Key.TF_DAEMON_PORT, Integer.valueOf(4223)); this.config.put(AppConfig.Key.UPLINK_ADRESS, "http://localhost:8081/datafeed/collect/garden"); // this.config.put(AppConfig.Key.API_TOKEN, "non-working-token"); } @Override public Object get(Key key) { if (config.containsKey(key)) return config.get(key); else return key.getDefaultValue(); } @Override public Object get(Key key, Object defaultValue) { return this.config.getOrDefault(key, defaultValue); } } ## Instruction: Connect to localhost brick daemon. ## Code After: package de.graeuler.garden.config; import java.util.EnumMap; public class StaticAppConfig implements AppConfig { private EnumMap<AppConfig.Key, Object> config = new EnumMap<>(Key.class); public StaticAppConfig() { this.config.put(AppConfig.Key.TF_DAEMON_HOST, "localhost"); this.config.put(AppConfig.Key.TF_DAEMON_PORT, Integer.valueOf(4223)); this.config.put(AppConfig.Key.UPLINK_ADRESS, "http://localhost:8081/datafeed/collect/garden"); // this.config.put(AppConfig.Key.API_TOKEN, "non-working-token"); } @Override public Object get(Key key) { if (config.containsKey(key)) return config.get(key); else return key.getDefaultValue(); } @Override public Object get(Key key, Object defaultValue) { return this.config.getOrDefault(key, defaultValue); } }
# ... existing code ... public StaticAppConfig() { this.config.put(AppConfig.Key.TF_DAEMON_HOST, "localhost"); this.config.put(AppConfig.Key.TF_DAEMON_PORT, Integer.valueOf(4223)); this.config.put(AppConfig.Key.UPLINK_ADRESS, "http://localhost:8081/datafeed/collect/garden"); // this.config.put(AppConfig.Key.API_TOKEN, "non-working-token"); # ... rest of the code ...
841cb6e54c40ee745e69f8e0d538024a40e113c2
setup.py
setup.py
from setuptools import setup, find_packages setup( name='django-template-tests', url="https://chris-lamb.co.uk/projects/django-template-tests", version='1.0.0', description="Performs some quick static analysis on your templates", author="Chris Lamb", author_email="[email protected]", license="BSD", packages=find_packages(), include_package_data=True, )
from setuptools import setup, find_packages setup( name='django-template-tests', url="https://chris-lamb.co.uk/projects/django-template-tests", version='1.0.0', description="Performs some quick static analysis on your templates", author="Chris Lamb", author_email="[email protected]", license="BSD", packages=find_packages(), include_package_data=True, install_requires=( 'Django>=1.8', ), )
Update Django requirement to latest LTS
Update Django requirement to latest LTS
Python
bsd-3-clause
lamby/django-template-tests
python
## Code Before: from setuptools import setup, find_packages setup( name='django-template-tests', url="https://chris-lamb.co.uk/projects/django-template-tests", version='1.0.0', description="Performs some quick static analysis on your templates", author="Chris Lamb", author_email="[email protected]", license="BSD", packages=find_packages(), include_package_data=True, ) ## Instruction: Update Django requirement to latest LTS ## Code After: from setuptools import setup, find_packages setup( name='django-template-tests', url="https://chris-lamb.co.uk/projects/django-template-tests", version='1.0.0', description="Performs some quick static analysis on your templates", author="Chris Lamb", author_email="[email protected]", license="BSD", packages=find_packages(), include_package_data=True, install_requires=( 'Django>=1.8', ), )
// ... existing code ... packages=find_packages(), include_package_data=True, install_requires=( 'Django>=1.8', ), ) // ... rest of the code ...
94fcbe5084cc1361b42983077d8373c66b00c3f3
src/test/java/net/wizardsoflua/testenv/net/AbstractMessage.java
src/test/java/net/wizardsoflua/testenv/net/AbstractMessage.java
package net.wizardsoflua.testenv.net; import java.io.IOException; import com.google.common.base.Throwables; import io.netty.buffer.ByteBuf; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; @RequiresMainThread public abstract class AbstractMessage implements IMessage { protected abstract void read(PacketBuffer buffer) throws IOException; protected abstract void write(PacketBuffer buffer) throws IOException; protected void writeString(ByteBuf buffer, String string) { if (string == null) { buffer.writeInt(-1); } else { buffer.writeInt(string.length()); buffer.writeBytes(string.getBytes()); } } protected String readString(ByteBuf buffer) { int len = buffer.readInt(); if (len == -1) { return null; } else { byte[] bytes = new byte[len]; buffer.readBytes(bytes); return new String(bytes); } } @Override public void fromBytes(ByteBuf buffer) { try { read(new PacketBuffer(buffer)); } catch (IOException e) { throw Throwables.propagate(e); } } @Override public void toBytes(ByteBuf buffer) { try { write(new PacketBuffer(buffer)); } catch (IOException e) { throw Throwables.propagate(e); } } }
package net.wizardsoflua.testenv.net; import java.io.IOException; import io.netty.buffer.ByteBuf; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; @RequiresMainThread public abstract class AbstractMessage implements IMessage { protected abstract void read(PacketBuffer buffer) throws IOException; protected abstract void write(PacketBuffer buffer) throws IOException; protected void writeString(ByteBuf buffer, String string) { if (string == null) { buffer.writeInt(-1); } else { buffer.writeInt(string.length()); buffer.writeBytes(string.getBytes()); } } protected String readString(ByteBuf buffer) { int len = buffer.readInt(); if (len == -1) { return null; } else { byte[] bytes = new byte[len]; buffer.readBytes(bytes); return new String(bytes); } } @Override public void fromBytes(ByteBuf buffer) { try { read(new PacketBuffer(buffer)); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void toBytes(ByteBuf buffer) { try { write(new PacketBuffer(buffer)); } catch (IOException e) { throw new RuntimeException(e); } } }
Remove use of the deprecated method Throwables.propagate
Remove use of the deprecated method Throwables.propagate
Java
apache-2.0
mkarneim/luamod
java
## Code Before: package net.wizardsoflua.testenv.net; import java.io.IOException; import com.google.common.base.Throwables; import io.netty.buffer.ByteBuf; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; @RequiresMainThread public abstract class AbstractMessage implements IMessage { protected abstract void read(PacketBuffer buffer) throws IOException; protected abstract void write(PacketBuffer buffer) throws IOException; protected void writeString(ByteBuf buffer, String string) { if (string == null) { buffer.writeInt(-1); } else { buffer.writeInt(string.length()); buffer.writeBytes(string.getBytes()); } } protected String readString(ByteBuf buffer) { int len = buffer.readInt(); if (len == -1) { return null; } else { byte[] bytes = new byte[len]; buffer.readBytes(bytes); return new String(bytes); } } @Override public void fromBytes(ByteBuf buffer) { try { read(new PacketBuffer(buffer)); } catch (IOException e) { throw Throwables.propagate(e); } } @Override public void toBytes(ByteBuf buffer) { try { write(new PacketBuffer(buffer)); } catch (IOException e) { throw Throwables.propagate(e); } } } ## Instruction: Remove use of the deprecated method Throwables.propagate ## Code After: package net.wizardsoflua.testenv.net; import java.io.IOException; import io.netty.buffer.ByteBuf; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; @RequiresMainThread public abstract class AbstractMessage implements IMessage { protected abstract void read(PacketBuffer buffer) throws IOException; protected abstract void write(PacketBuffer buffer) throws IOException; protected void writeString(ByteBuf buffer, String string) { if (string == null) { buffer.writeInt(-1); } else { buffer.writeInt(string.length()); buffer.writeBytes(string.getBytes()); } } protected String readString(ByteBuf buffer) { int len = buffer.readInt(); if (len == -1) { return null; } else { byte[] bytes = new byte[len]; buffer.readBytes(bytes); return new String(bytes); } } @Override public void fromBytes(ByteBuf buffer) { try { read(new PacketBuffer(buffer)); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void toBytes(ByteBuf buffer) { try { write(new PacketBuffer(buffer)); } catch (IOException e) { throw new RuntimeException(e); } } }
// ... existing code ... package net.wizardsoflua.testenv.net; import java.io.IOException; import io.netty.buffer.ByteBuf; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; // ... modified code ... try { read(new PacketBuffer(buffer)); } catch (IOException e) { throw new RuntimeException(e); } } ... try { write(new PacketBuffer(buffer)); } catch (IOException e) { throw new RuntimeException(e); } } // ... rest of the code ...
9633f3ee1a3431cb373a4652afbfc2cd8b3b4c23
test_utils/anki/__init__.py
test_utils/anki/__init__.py
import sys from unittest.mock import MagicMock class MockAnkiModules: """ I'd like to get rid of the situation when this is required, but for now this helps with the situation that anki modules are not available during test runtime. """ modules_list = ['anki', 'anki.hooks', 'anki.exporting', 'anki.decks', 'anki.utils', 'anki.cards', 'anki.models', 'anki.notes', 'aqt', 'aqt.qt', 'aqt.exporting', 'aqt.utils'] def __init__(self): self.shadowed_modules = {} for module in self.modules_list: self.shadowed_modules[module] = sys.modules.get(module) sys.modules[module] = MagicMock() def unmock(self): for module in self.modules_list: shadowed_module = self.shadowed_modules[module] if shadowed_module is not None: sys.modules[module] = shadowed_module else: if module in sys.modules: del sys.modules[module]
from typing import List from typing import Optional import sys from unittest.mock import MagicMock class MockAnkiModules: """ I'd like to get rid of the situation when this is required, but for now this helps with the situation that anki modules are not available during test runtime. """ module_names_list = ['anki', 'anki.hooks', 'anki.exporting', 'anki.decks', 'anki.utils', 'anki.cards', 'anki.models', 'anki.notes', 'aqt', 'aqt.qt', 'aqt.exporting', 'aqt.utils'] def __init__(self, module_names_list: Optional[List[str]] = None): if module_names_list is None: module_names_list = self.module_names_list self.shadowed_modules = {} for module_name in module_names_list: self.shadowed_modules[module_name] = sys.modules.get(module_name) sys.modules[module_name] = MagicMock() def unmock(self): for module_name, module in self.shadowed_modules.items(): if module is not None: sys.modules[module_name] = module else: if module_name in sys.modules: del sys.modules[module_name]
Allow specifying modules to be mocked
Allow specifying modules to be mocked
Python
mit
Stvad/CrowdAnki,Stvad/CrowdAnki,Stvad/CrowdAnki
python
## Code Before: import sys from unittest.mock import MagicMock class MockAnkiModules: """ I'd like to get rid of the situation when this is required, but for now this helps with the situation that anki modules are not available during test runtime. """ modules_list = ['anki', 'anki.hooks', 'anki.exporting', 'anki.decks', 'anki.utils', 'anki.cards', 'anki.models', 'anki.notes', 'aqt', 'aqt.qt', 'aqt.exporting', 'aqt.utils'] def __init__(self): self.shadowed_modules = {} for module in self.modules_list: self.shadowed_modules[module] = sys.modules.get(module) sys.modules[module] = MagicMock() def unmock(self): for module in self.modules_list: shadowed_module = self.shadowed_modules[module] if shadowed_module is not None: sys.modules[module] = shadowed_module else: if module in sys.modules: del sys.modules[module] ## Instruction: Allow specifying modules to be mocked ## Code After: from typing import List from typing import Optional import sys from unittest.mock import MagicMock class MockAnkiModules: """ I'd like to get rid of the situation when this is required, but for now this helps with the situation that anki modules are not available during test runtime. """ module_names_list = ['anki', 'anki.hooks', 'anki.exporting', 'anki.decks', 'anki.utils', 'anki.cards', 'anki.models', 'anki.notes', 'aqt', 'aqt.qt', 'aqt.exporting', 'aqt.utils'] def __init__(self, module_names_list: Optional[List[str]] = None): if module_names_list is None: module_names_list = self.module_names_list self.shadowed_modules = {} for module_name in module_names_list: self.shadowed_modules[module_name] = sys.modules.get(module_name) sys.modules[module_name] = MagicMock() def unmock(self): for module_name, module in self.shadowed_modules.items(): if module is not None: sys.modules[module_name] = module else: if module_name in sys.modules: del sys.modules[module_name]
... from typing import List from typing import Optional import sys from unittest.mock import MagicMock ... I'd like to get rid of the situation when this is required, but for now this helps with the situation that anki modules are not available during test runtime. """ module_names_list = ['anki', 'anki.hooks', 'anki.exporting', 'anki.decks', 'anki.utils', 'anki.cards', 'anki.models', 'anki.notes', 'aqt', 'aqt.qt', 'aqt.exporting', 'aqt.utils'] def __init__(self, module_names_list: Optional[List[str]] = None): if module_names_list is None: module_names_list = self.module_names_list self.shadowed_modules = {} for module_name in module_names_list: self.shadowed_modules[module_name] = sys.modules.get(module_name) sys.modules[module_name] = MagicMock() def unmock(self): for module_name, module in self.shadowed_modules.items(): if module is not None: sys.modules[module_name] = module else: if module_name in sys.modules: del sys.modules[module_name] ...
06ef7333ea7c584166b1a7361e1d41143a0c85c8
moveon/managers.py
moveon/managers.py
from django.db import models class CompanyManager(models.Manager): def get_by_code(self, company_code): return self.get(code=company_code) class TransportManager(models.Manager): def get_by_name(self, transport_name): return self.get(name=transport_name) class StationManager(models.Manager): def get_by_id(self, station_id): return self.get(osmid=station_id) class NodeManager(models.Manager): def get_by_id(self, station_id): return self.get(osmid=station_id)
from django.db import models from django.db.models import Q class CompanyManager(models.Manager): def get_by_code(self, company_code): return self.get(code=company_code) class TransportManager(models.Manager): def get_by_name(self, transport_name): return self.get(name=transport_name) class StationManager(models.Manager): def get_by_id(self, station_id): return self.get(osmid=station_id) def get_near_stations(self, left, bottom, right, top): stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) & Q(latitude__lte=right) & Q(longitude__lte=top)) return stations class NodeManager(models.Manager): def get_by_id(self, station_id): return self.get(osmid=station_id)
Add the query to get the near stations
Add the query to get the near stations This query takes four parameters that define a coordinates bounding box. This allows to get the stations that fir into the area defined by the box.
Python
agpl-3.0
SeGarVi/moveon-web,SeGarVi/moveon-web,SeGarVi/moveon-web
python
## Code Before: from django.db import models class CompanyManager(models.Manager): def get_by_code(self, company_code): return self.get(code=company_code) class TransportManager(models.Manager): def get_by_name(self, transport_name): return self.get(name=transport_name) class StationManager(models.Manager): def get_by_id(self, station_id): return self.get(osmid=station_id) class NodeManager(models.Manager): def get_by_id(self, station_id): return self.get(osmid=station_id) ## Instruction: Add the query to get the near stations This query takes four parameters that define a coordinates bounding box. This allows to get the stations that fir into the area defined by the box. ## Code After: from django.db import models from django.db.models import Q class CompanyManager(models.Manager): def get_by_code(self, company_code): return self.get(code=company_code) class TransportManager(models.Manager): def get_by_name(self, transport_name): return self.get(name=transport_name) class StationManager(models.Manager): def get_by_id(self, station_id): return self.get(osmid=station_id) def get_near_stations(self, left, bottom, right, top): stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) & Q(latitude__lte=right) & Q(longitude__lte=top)) return stations class NodeManager(models.Manager): def get_by_id(self, station_id): return self.get(osmid=station_id)
# ... existing code ... from django.db import models from django.db.models import Q class CompanyManager(models.Manager): def get_by_code(self, company_code): # ... modified code ... class StationManager(models.Manager): def get_by_id(self, station_id): return self.get(osmid=station_id) def get_near_stations(self, left, bottom, right, top): stations = self.filter(Q(latitude__gte=left) & Q(longitude__gte=bottom) & Q(latitude__lte=right) & Q(longitude__lte=top)) return stations class NodeManager(models.Manager): def get_by_id(self, station_id): # ... rest of the code ...
c62b42eb528babebf96e56738031dcda97868e80
flowfairy/app.py
flowfairy/app.py
import tensorflow as tf import numpy as np import itertools as it import importlib from flowfairy.conf import settings from flowfairy.utils import take from flowfairy import data from flowfairy.feature import FeatureManager from flowfairy.core.queue import FlowQueue from flowfairy.core.stage import stage def load_net(): net = importlib.import_module(settings.NET).Net() return net def run(*args, **options): coord = tf.train.Coordinator() net = load_net() queues = [] with tf.variable_scope('network') as scope: for data_loader in data.provider: fts = FeatureManager(data_loader) queue = FlowQueue(fts, coord) queues.append(queue) X = queue.dequeue() func = getattr(net, data_loader.name) func(**dict(zip(fts.fields, X))) scope.reuse_variables() with tf.Session() as sess: stage.before(sess, net) for queue in queues: queue.start(sess) sess.run(tf.global_variables_initializer()) try: step = 1 while not coord.should_stop() and not net.should_stop(): stage.run(sess, step) step += 1 except KeyboardInterrupt: pass coord.request_stop() queue.stop() coord.join(stop_grace_period_secs=5)
import tensorflow as tf import numpy as np import itertools as it import importlib from flowfairy.conf import settings from flowfairy.utils import take from flowfairy import data from flowfairy.feature import FeatureManager from flowfairy.core.queue import FlowQueue from flowfairy.core.stage import stage def load_net(): net = importlib.import_module(settings.NET).Net() return net def run(*args, **options): coord = tf.train.Coordinator() net = load_net() queues = [] for data_loader in data.provider: with tf.variable_scope(data_loader.name) as scope: fts = FeatureManager(data_loader) queue = FlowQueue(fts, coord) queues.append(queue) X = queue.dequeue() func = getattr(net, data_loader.name) func(**dict(zip(fts.fields, X))) scope.reuse_variables() with tf.Session() as sess: stage.before(sess, net) for queue in queues: queue.start(sess) sess.run(tf.global_variables_initializer()) try: step = 1 while not coord.should_stop() and not net.should_stop(): stage.run(sess, step) step += 1 except KeyboardInterrupt: pass coord.request_stop() queue.stop() coord.join(stop_grace_period_secs=5)
Set name_scope of entire network to the dataset it handles
Set name_scope of entire network to the dataset it handles
Python
mit
WhatDo/FlowFairy
python
## Code Before: import tensorflow as tf import numpy as np import itertools as it import importlib from flowfairy.conf import settings from flowfairy.utils import take from flowfairy import data from flowfairy.feature import FeatureManager from flowfairy.core.queue import FlowQueue from flowfairy.core.stage import stage def load_net(): net = importlib.import_module(settings.NET).Net() return net def run(*args, **options): coord = tf.train.Coordinator() net = load_net() queues = [] with tf.variable_scope('network') as scope: for data_loader in data.provider: fts = FeatureManager(data_loader) queue = FlowQueue(fts, coord) queues.append(queue) X = queue.dequeue() func = getattr(net, data_loader.name) func(**dict(zip(fts.fields, X))) scope.reuse_variables() with tf.Session() as sess: stage.before(sess, net) for queue in queues: queue.start(sess) sess.run(tf.global_variables_initializer()) try: step = 1 while not coord.should_stop() and not net.should_stop(): stage.run(sess, step) step += 1 except KeyboardInterrupt: pass coord.request_stop() queue.stop() coord.join(stop_grace_period_secs=5) ## Instruction: Set name_scope of entire network to the dataset it handles ## Code After: import tensorflow as tf import numpy as np import itertools as it import importlib from flowfairy.conf import settings from flowfairy.utils import take from flowfairy import data from flowfairy.feature import FeatureManager from flowfairy.core.queue import FlowQueue from flowfairy.core.stage import stage def load_net(): net = importlib.import_module(settings.NET).Net() return net def run(*args, **options): coord = tf.train.Coordinator() net = load_net() queues = [] for data_loader in data.provider: with tf.variable_scope(data_loader.name) as scope: fts = FeatureManager(data_loader) queue = FlowQueue(fts, coord) queues.append(queue) X = queue.dequeue() func = getattr(net, data_loader.name) func(**dict(zip(fts.fields, X))) scope.reuse_variables() with tf.Session() as sess: stage.before(sess, net) for queue in queues: queue.start(sess) sess.run(tf.global_variables_initializer()) try: step = 1 while not coord.should_stop() and not net.should_stop(): stage.run(sess, step) step += 1 except KeyboardInterrupt: pass coord.request_stop() queue.stop() coord.join(stop_grace_period_secs=5)
... net = load_net() queues = [] for data_loader in data.provider: with tf.variable_scope(data_loader.name) as scope: fts = FeatureManager(data_loader) queue = FlowQueue(fts, coord) queues.append(queue) ...
70ddff2c618a75d976c892d54ba79ff6cb6607af
chronos-aws/src/main/java/org/ds/chronos/aws/S3ParitionedChronicle.java
chronos-aws/src/main/java/org/ds/chronos/aws/S3ParitionedChronicle.java
package org.ds.chronos.aws; import org.ds.chronos.api.Chronicle; import org.ds.chronos.api.PartitionPeriod; import org.ds.chronos.api.PartitionedChronicle; import com.amazonaws.services.s3.AmazonS3Client; public class S3ParitionedChronicle extends PartitionedChronicle { final AmazonS3Client client; final String bucket; public S3ParitionedChronicle(AmazonS3Client client, String bucket, String keyPrefix, PartitionPeriod period) { super(keyPrefix, period); this.client = client; this.bucket = bucket; } @Override protected Chronicle getPartition(String key) { return new S3Chronicle(client, bucket, key); } }
package org.ds.chronos.aws; import org.ds.chronos.api.Chronicle; import org.ds.chronos.api.PartitionPeriod; import org.ds.chronos.api.PartitionedChronicle; import com.amazonaws.services.s3.AmazonS3Client; public class S3ParitionedChronicle extends PartitionedChronicle { final AmazonS3Client client; final String bucket; final boolean gzip; public S3ParitionedChronicle(AmazonS3Client client, String bucket, String keyPrefix, PartitionPeriod period) { this(client, bucket, keyPrefix, period, false); } public S3ParitionedChronicle(AmazonS3Client client, String bucket, String keyPrefix, PartitionPeriod period, boolean gzip) { super(keyPrefix, period); this.client = client; this.bucket = bucket; this.gzip = gzip; } @Override protected Chronicle getPartition(String key) { return new S3Chronicle(client, bucket, key, gzip); } }
Add gzip constructor arg to partitioned s3 chronicle
Add gzip constructor arg to partitioned s3 chronicle
Java
mit
dansimpson/chronos
java
## Code Before: package org.ds.chronos.aws; import org.ds.chronos.api.Chronicle; import org.ds.chronos.api.PartitionPeriod; import org.ds.chronos.api.PartitionedChronicle; import com.amazonaws.services.s3.AmazonS3Client; public class S3ParitionedChronicle extends PartitionedChronicle { final AmazonS3Client client; final String bucket; public S3ParitionedChronicle(AmazonS3Client client, String bucket, String keyPrefix, PartitionPeriod period) { super(keyPrefix, period); this.client = client; this.bucket = bucket; } @Override protected Chronicle getPartition(String key) { return new S3Chronicle(client, bucket, key); } } ## Instruction: Add gzip constructor arg to partitioned s3 chronicle ## Code After: package org.ds.chronos.aws; import org.ds.chronos.api.Chronicle; import org.ds.chronos.api.PartitionPeriod; import org.ds.chronos.api.PartitionedChronicle; import com.amazonaws.services.s3.AmazonS3Client; public class S3ParitionedChronicle extends PartitionedChronicle { final AmazonS3Client client; final String bucket; final boolean gzip; public S3ParitionedChronicle(AmazonS3Client client, String bucket, String keyPrefix, PartitionPeriod period) { this(client, bucket, keyPrefix, period, false); } public S3ParitionedChronicle(AmazonS3Client client, String bucket, String keyPrefix, PartitionPeriod period, boolean gzip) { super(keyPrefix, period); this.client = client; this.bucket = bucket; this.gzip = gzip; } @Override protected Chronicle getPartition(String key) { return new S3Chronicle(client, bucket, key, gzip); } }
# ... existing code ... final AmazonS3Client client; final String bucket; final boolean gzip; public S3ParitionedChronicle(AmazonS3Client client, String bucket, String keyPrefix, PartitionPeriod period) { this(client, bucket, keyPrefix, period, false); } public S3ParitionedChronicle(AmazonS3Client client, String bucket, String keyPrefix, PartitionPeriod period, boolean gzip) { super(keyPrefix, period); this.client = client; this.bucket = bucket; this.gzip = gzip; } @Override protected Chronicle getPartition(String key) { return new S3Chronicle(client, bucket, key, gzip); } } # ... rest of the code ...
c4fc5f2902ca6efe8b16a2dd35e6f3b9d0279fe5
ktor-client/ktor-client-core/src/io/ktor/client/HttpClientFactory.kt
ktor-client/ktor-client-core/src/io/ktor/client/HttpClientFactory.kt
package io.ktor.client import io.ktor.client.backend.* import io.ktor.client.call.* import io.ktor.client.features.* import io.ktor.client.request.* import io.ktor.client.response.* import io.ktor.client.utils.* object HttpClientFactory { fun createDefault(backendFactory: HttpClientBackendFactory, block: ClientConfig.() -> Unit = {}): HttpClient { val backend = backendFactory {} return ClientConfig(backend).apply { install("backend") { requestPipeline.intercept(HttpRequestPipeline.Send) { builder -> val request = (builder as? HttpRequestBuilder)?.build() ?: return@intercept if (request.body !is HttpMessageBody) error("Body can't be processed: ${request.body}") val response = backend.makeRequest(request) proceedWith(HttpClientCall(request, response, context)) } responsePipeline.intercept(HttpResponsePipeline.After) { container -> container.response.close() } } install(HttpPlainText) install(HttpIgnoreBody) block() }.build() } }
package io.ktor.client import io.ktor.client.backend.* import io.ktor.client.call.* import io.ktor.client.features.* import io.ktor.client.request.* import io.ktor.client.response.* import io.ktor.client.utils.* object HttpClientFactory { fun createDefault(backendFactory: HttpClientBackendFactory, block: ClientConfig.() -> Unit = {}): HttpClient { val backend = backendFactory {} return ClientConfig(backend).apply { install("backend") { requestPipeline.intercept(HttpRequestPipeline.Send) { builder -> val request = (builder as? HttpRequestBuilder)?.build() ?: return@intercept if (request.body !is HttpMessageBody) error("Body can't be processed: ${request.body}") val response = backend.makeRequest(request) if (response.body !is HttpMessageBody) error("Client backend response has wrong format: ${request.body}") proceedWith(HttpClientCall(request, response, context)) } responsePipeline.intercept(HttpResponsePipeline.After) { container -> container.response.close() } } install(HttpPlainText) install(HttpIgnoreBody) block() }.build() } }
Check body type in backend response
Check body type in backend response
Kotlin
apache-2.0
ktorio/ktor,ktorio/ktor,ktorio/ktor,ktorio/ktor
kotlin
## Code Before: package io.ktor.client import io.ktor.client.backend.* import io.ktor.client.call.* import io.ktor.client.features.* import io.ktor.client.request.* import io.ktor.client.response.* import io.ktor.client.utils.* object HttpClientFactory { fun createDefault(backendFactory: HttpClientBackendFactory, block: ClientConfig.() -> Unit = {}): HttpClient { val backend = backendFactory {} return ClientConfig(backend).apply { install("backend") { requestPipeline.intercept(HttpRequestPipeline.Send) { builder -> val request = (builder as? HttpRequestBuilder)?.build() ?: return@intercept if (request.body !is HttpMessageBody) error("Body can't be processed: ${request.body}") val response = backend.makeRequest(request) proceedWith(HttpClientCall(request, response, context)) } responsePipeline.intercept(HttpResponsePipeline.After) { container -> container.response.close() } } install(HttpPlainText) install(HttpIgnoreBody) block() }.build() } } ## Instruction: Check body type in backend response ## Code After: package io.ktor.client import io.ktor.client.backend.* import io.ktor.client.call.* import io.ktor.client.features.* import io.ktor.client.request.* import io.ktor.client.response.* import io.ktor.client.utils.* object HttpClientFactory { fun createDefault(backendFactory: HttpClientBackendFactory, block: ClientConfig.() -> Unit = {}): HttpClient { val backend = backendFactory {} return ClientConfig(backend).apply { install("backend") { requestPipeline.intercept(HttpRequestPipeline.Send) { builder -> val request = (builder as? HttpRequestBuilder)?.build() ?: return@intercept if (request.body !is HttpMessageBody) error("Body can't be processed: ${request.body}") val response = backend.makeRequest(request) if (response.body !is HttpMessageBody) error("Client backend response has wrong format: ${request.body}") proceedWith(HttpClientCall(request, response, context)) } responsePipeline.intercept(HttpResponsePipeline.After) { container -> container.response.close() } } install(HttpPlainText) install(HttpIgnoreBody) block() }.build() } }
# ... existing code ... install("backend") { requestPipeline.intercept(HttpRequestPipeline.Send) { builder -> val request = (builder as? HttpRequestBuilder)?.build() ?: return@intercept if (request.body !is HttpMessageBody) error("Body can't be processed: ${request.body}") val response = backend.makeRequest(request) if (response.body !is HttpMessageBody) error("Client backend response has wrong format: ${request.body}") proceedWith(HttpClientCall(request, response, context)) } # ... rest of the code ...
cde02a3129d276d02054e04c1b0a0b605b837d32
eodatasets3/__init__.py
eodatasets3/__init__.py
from __future__ import absolute_import from ._version import get_versions REPO_URL = "https://github.com/GeoscienceAustralia/eo-datasets.git" __version__ = get_versions()["version"] del get_versions
from __future__ import absolute_import from ._version import get_versions from .assemble import DatasetAssembler REPO_URL = "https://github.com/GeoscienceAustralia/eo-datasets.git" __version__ = get_versions()["version"] del get_versions __all__ = (DatasetAssembler, REPO_URL, __version__)
Allow assembler to be imported from eodatasets3 root
Allow assembler to be imported from eodatasets3 root
Python
apache-2.0
GeoscienceAustralia/eo-datasets,jeremyh/eo-datasets,jeremyh/eo-datasets,GeoscienceAustralia/eo-datasets
python
## Code Before: from __future__ import absolute_import from ._version import get_versions REPO_URL = "https://github.com/GeoscienceAustralia/eo-datasets.git" __version__ = get_versions()["version"] del get_versions ## Instruction: Allow assembler to be imported from eodatasets3 root ## Code After: from __future__ import absolute_import from ._version import get_versions from .assemble import DatasetAssembler REPO_URL = "https://github.com/GeoscienceAustralia/eo-datasets.git" __version__ = get_versions()["version"] del get_versions __all__ = (DatasetAssembler, REPO_URL, __version__)
# ... existing code ... from __future__ import absolute_import from ._version import get_versions from .assemble import DatasetAssembler REPO_URL = "https://github.com/GeoscienceAustralia/eo-datasets.git" __version__ = get_versions()["version"] del get_versions __all__ = (DatasetAssembler, REPO_URL, __version__) # ... rest of the code ...
10f48f8a8d71a237b97f7952cf8164d0c5138886
budget_proj/budget_app/urls.py
budget_proj/budget_app/urls.py
from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ]
from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^ocrb-prod/$', views.OcrbList.as_view()), url(r'^kpm-prod/$', views.KpmList.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ]
Add endpoints for AWS production feeds
Add endpoints for AWS production feeds Added endpoints for pulling the data from AWS (vs pulling from CSV)
Python
mit
hackoregon/team-budget,jimtyhurst/team-budget,hackoregon/team-budget,hackoregon/team-budget,jimtyhurst/team-budget,jimtyhurst/team-budget
python
## Code Before: from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ] ## Instruction: Add endpoints for AWS production feeds Added endpoints for pulling the data from AWS (vs pulling from CSV) ## Code After: from django.conf.urls import url from . import views from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='hackoregon_budget') # Listed in alphabetical order. urlpatterns = [ url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^ocrb-prod/$', views.OcrbList.as_view()), url(r'^kpm-prod/$', views.KpmList.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ]
... url(r'^$', schema_view), url(r'^kpm/$', views.ListKpm.as_view()), url(r'^ocrb/$', views.ListOcrb.as_view()), url(r'^ocrb-prod/$', views.OcrbList.as_view()), url(r'^kpm-prod/$', views.KpmList.as_view()), url(r'^summary/', views.FindOperatingAndCapitalRequirements.as_view()), ] ...
b096c2bf19203e69dfe9c7d54123a3bc8725679a
src/com/fsck/k9/helper/NotificationBuilder.java
src/com/fsck/k9/helper/NotificationBuilder.java
package com.fsck.k9.helper; import android.app.Notification; import android.content.Context; import android.os.Build; import android.support.v4.app.NotificationCompat; /** * Notification builder that will set {@link Notification#number} on pre-Honeycomb devices. * * @see <a href="http://code.google.com/p/android/issues/detail?id=38028">android - Issue 38028</a> */ public class NotificationBuilder extends NotificationCompat.Builder { protected int mNumber; public NotificationBuilder(Context context) { super(context); } @Override public NotificationCompat.Builder setNumber(int number) { mNumber = number; return this; } @Override public Notification build() { Notification notification = super.build(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { notification.number = mNumber; } return notification; } }
package com.fsck.k9.helper; import android.app.Notification; import android.content.Context; import android.os.Build; import android.support.v4.app.NotificationCompat; /** * Notification builder that will set {@link Notification#number} on pre-Honeycomb devices. * * @see <a href="http://code.google.com/p/android/issues/detail?id=38028">android - Issue 38028</a> */ public class NotificationBuilder extends NotificationCompat.Builder { protected int mNumber; public NotificationBuilder(Context context) { super(context); } @Override public NotificationCompat.Builder setNumber(int number) { super.setNumber(number); mNumber = number; return this; } @Override public Notification build() { Notification notification = super.build(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { notification.number = mNumber; } return notification; } }
Fix unread count in notifications (again)
Fix unread count in notifications (again)
Java
apache-2.0
sedrubal/k-9,k9mail/k-9,rollbrettler/k-9,rollbrettler/k-9,sonork/k-9,sanderbaas/k-9,sanderbaas/k-9,439teamwork/k-9,github201407/k-9,indus1/k-9,vasyl-khomko/k-9,icedman21/k-9,huhu/k-9,thuanpq/k-9,sonork/k-9,msdgwzhy6/k-9,moparisthebest/k-9,moparisthebest/k-9,GuillaumeSmaha/k-9,cliniome/pki,suzp1984/k-9,gilbertw1/k-9,cooperpellaton/k-9,roscrazy/k-9,Eagles2F/k-9,herpiko/k-9,dgger/k-9,XiveZ/k-9,sebkur/k-9,rishabhbitsg/k-9,thuanpq/k-9,Valodim/k-9,XiveZ/k-9,suzp1984/k-9,rtreffer/openpgp-k-9,gilbertw1/k-9,ndew623/k-9,leixinstar/k-9,suzp1984/k-9,tsunli/k-9,gnebsy/k-9,GuillaumeSmaha/k-9,sedrubal/k-9,tonytamsf/k-9,nilsbraden/k-9,dhootha/k-9,jberkel/k-9,ndew623/k-9,KitAway/k-9,farmboy0/k-9,439teamwork/k-9,cketti/k-9,gaionim/k-9,dhootha/k-9,WenduanMou1/k-9,dgger/k-9,vatsalsura/k-9,dgger/k-9,jca02266/k-9,msdgwzhy6/k-9,icedman21/k-9,vatsalsura/k-9,msdgwzhy6/k-9,jberkel/k-9,konfer/k-9,CodingRmy/k-9,denim2x/k-9,imaeses/k-9,bashrc/k-9,bashrc/k-9,ndew623/k-9,gaionim/k-9,github201407/k-9,gaionim/k-9,mawiegand/k-9,sonork/k-9,gilbertw1/k-9,imaeses/k-9,philipwhiuk/k-9,torte71/k-9,huhu/k-9,G00fY2/k-9_material_design,vt0r/k-9,sebkur/k-9,WenduanMou1/k-9,deepworks/k-9,herpiko/k-9,WenduanMou1/k-9,leixinstar/k-9,dpereira411/k-9,CodingRmy/k-9,imaeses/k-9,mawiegand/k-9,nilsbraden/k-9,KitAway/k-9,tsunli/k-9,dhootha/k-9,denim2x/k-9,vasyl-khomko/k-9,rtreffer/openpgp-k-9,farmboy0/k-9,tonytamsf/k-9,cooperpellaton/k-9,sebkur/k-9,k9mail/k-9,philipwhiuk/q-mail,philipwhiuk/k-9,cketti/k-9,deepworks/k-9,crr0004/k-9,jca02266/k-9,cketti/k-9,torte71/k-9,tonytamsf/k-9,crr0004/k-9,cketti/k-9,bashrc/k-9,Eagles2F/k-9,dpereira411/k-9,Eagles2F/k-9,herpiko/k-9,k9mail/k-9,deepworks/k-9,huhu/k-9,nilsbraden/k-9,rollbrettler/k-9,KitAway/k-9,gnebsy/k-9,leixinstar/k-9,dpereira411/k-9,torte71/k-9,mawiegand/k-9,cliniome/pki,philipwhiuk/q-mail,konfer/k-9,sanderbaas/k-9,icedman21/k-9,vasyl-khomko/k-9,XiveZ/k-9,cooperpellaton/k-9,GuillaumeSmaha/k-9,philipwhiuk/q-mail,gnebsy/k-9,crr0004/k-9,farmboy0/k-9,cliniome/pki,vt0r/k-9,439teamwork/k-9,thuanpq/k-9,indus1/k-9,jca02266/k-9,konfer/k-9,moparisthebest/k-9,denim2x/k-9,github201407/k-9,G00fY2/k-9_material_design,rishabhbitsg/k-9,roscrazy/k-9,tsunli/k-9
java
## Code Before: package com.fsck.k9.helper; import android.app.Notification; import android.content.Context; import android.os.Build; import android.support.v4.app.NotificationCompat; /** * Notification builder that will set {@link Notification#number} on pre-Honeycomb devices. * * @see <a href="http://code.google.com/p/android/issues/detail?id=38028">android - Issue 38028</a> */ public class NotificationBuilder extends NotificationCompat.Builder { protected int mNumber; public NotificationBuilder(Context context) { super(context); } @Override public NotificationCompat.Builder setNumber(int number) { mNumber = number; return this; } @Override public Notification build() { Notification notification = super.build(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { notification.number = mNumber; } return notification; } } ## Instruction: Fix unread count in notifications (again) ## Code After: package com.fsck.k9.helper; import android.app.Notification; import android.content.Context; import android.os.Build; import android.support.v4.app.NotificationCompat; /** * Notification builder that will set {@link Notification#number} on pre-Honeycomb devices. * * @see <a href="http://code.google.com/p/android/issues/detail?id=38028">android - Issue 38028</a> */ public class NotificationBuilder extends NotificationCompat.Builder { protected int mNumber; public NotificationBuilder(Context context) { super(context); } @Override public NotificationCompat.Builder setNumber(int number) { super.setNumber(number); mNumber = number; return this; } @Override public Notification build() { Notification notification = super.build(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { notification.number = mNumber; } return notification; } }
... @Override public NotificationCompat.Builder setNumber(int number) { super.setNumber(number); mNumber = number; return this; } ...
c86d5c928cdefd09aca102b2a5c37f662e1426a6
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/users/tests/factories.py
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/users/tests/factories.py
from feder.users import models import factory class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user-{0}'.format(n)) email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) password = factory.PosteGnerationMethodCall('set_password', 'password') class Meta: model = models.User django_get_or_create = ('username', )
import factory class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user-{0}'.format(n)) email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) password = factory.PostGenerationMethodCall('set_password', 'password') class Meta: model = 'users.User' django_get_or_create = ('username', )
Fix typo & import in UserFactory
Fix typo & import in UserFactory
Python
bsd-3-clause
andresgz/cookiecutter-django,gappsexperts/cookiecutter-django,asyncee/cookiecutter-django,gappsexperts/cookiecutter-django,calculuscowboy/cookiecutter-django,aleprovencio/cookiecutter-django,ddiazpinto/cookiecutter-django,asyncee/cookiecutter-django,drxos/cookiecutter-django-dokku,thisjustin/cookiecutter-django,aleprovencio/cookiecutter-django,mjhea0/cookiecutter-django,schacki/cookiecutter-django,aeikenberry/cookiecutter-django-rest-babel,ovidner/cookiecutter-django,thisjustin/cookiecutter-django,schacki/cookiecutter-django,Parbhat/cookiecutter-django-foundation,aleprovencio/cookiecutter-django,nunchaks/cookiecutter-django,Parbhat/cookiecutter-django-foundation,ad-m/cookiecutter-django,hairychris/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,pydanny/cookiecutter-django,gappsexperts/cookiecutter-django,kappataumu/cookiecutter-django,calculuscowboy/cookiecutter-django,ryankanno/cookiecutter-django,hairychris/cookiecutter-django,hairychris/cookiecutter-django,kappataumu/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,kappataumu/cookiecutter-django,HandyCodeJob/hcj-django-temp,Parbhat/cookiecutter-django-foundation,ryankanno/cookiecutter-django,bopo/cookiecutter-django,HandyCodeJob/hcj-django-temp,aeikenberry/cookiecutter-django-rest-babel,schacki/cookiecutter-django,nunchaks/cookiecutter-django,webyneter/cookiecutter-django,crdoconnor/cookiecutter-django,webspired/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,drxos/cookiecutter-django-dokku,crdoconnor/cookiecutter-django,luzfcb/cookiecutter-django,pydanny/cookiecutter-django,jondelmil/cookiecutter-django,ad-m/cookiecutter-django,kappataumu/cookiecutter-django,hackebrot/cookiecutter-django,pydanny/cookiecutter-django,ad-m/cookiecutter-django,topwebmaster/cookiecutter-django,ryankanno/cookiecutter-django,gappsexperts/cookiecutter-django,HandyCodeJob/hcj-django-temp,hairychris/cookiecutter-django,webspired/cookiecutter-django,hackebrot/cookiecutter-django,topwebmaster/cookiecutter-django,calculuscowboy/cookiecutter-django,jondelmil/cookiecutter-django,mistalaba/cookiecutter-django,trungdong/cookiecutter-django,ovidner/cookiecutter-django,Parbhat/cookiecutter-django-foundation,aeikenberry/cookiecutter-django-rest-babel,jondelmil/cookiecutter-django,ddiazpinto/cookiecutter-django,mjhea0/cookiecutter-django,webspired/cookiecutter-django,nunchaks/cookiecutter-django,andresgz/cookiecutter-django,ad-m/cookiecutter-django,ovidner/cookiecutter-django,mistalaba/cookiecutter-django,bopo/cookiecutter-django,bopo/cookiecutter-django,HandyCodeJob/hcj-django-temp,ddiazpinto/cookiecutter-django,calculuscowboy/cookiecutter-django,ovidner/cookiecutter-django,thisjustin/cookiecutter-django,schacki/cookiecutter-django,webyneter/cookiecutter-django,pydanny/cookiecutter-django,trungdong/cookiecutter-django,asyncee/cookiecutter-django,ingenioustechie/cookiecutter-django-openshift,crdoconnor/cookiecutter-django,nunchaks/cookiecutter-django,aeikenberry/cookiecutter-django-rest-babel,hackebrot/cookiecutter-django,asyncee/cookiecutter-django,aleprovencio/cookiecutter-django,crdoconnor/cookiecutter-django,luzfcb/cookiecutter-django,mistalaba/cookiecutter-django,luzfcb/cookiecutter-django,topwebmaster/cookiecutter-django,drxos/cookiecutter-django-dokku,ddiazpinto/cookiecutter-django,mjhea0/cookiecutter-django,hackebrot/cookiecutter-django,trungdong/cookiecutter-django,topwebmaster/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,luzfcb/cookiecutter-django,mistalaba/cookiecutter-django,andresgz/cookiecutter-django,webyneter/cookiecutter-django,webyneter/cookiecutter-django,andresgz/cookiecutter-django,thisjustin/cookiecutter-django,mjhea0/cookiecutter-django,drxos/cookiecutter-django-dokku,jondelmil/cookiecutter-django,bopo/cookiecutter-django,webspired/cookiecutter-django
python
## Code Before: from feder.users import models import factory class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user-{0}'.format(n)) email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) password = factory.PosteGnerationMethodCall('set_password', 'password') class Meta: model = models.User django_get_or_create = ('username', ) ## Instruction: Fix typo & import in UserFactory ## Code After: import factory class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user-{0}'.format(n)) email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) password = factory.PostGenerationMethodCall('set_password', 'password') class Meta: model = 'users.User' django_get_or_create = ('username', )
... import factory ... class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user-{0}'.format(n)) email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) password = factory.PostGenerationMethodCall('set_password', 'password') class Meta: model = 'users.User' django_get_or_create = ('username', ) ...
4a4cb336839d42cee872e52399e17249b948492a
rackattack/common/globallock.py
rackattack/common/globallock.py
import threading import contextlib import time import traceback import logging _lock = threading.Lock() @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) yield released = time.time() took = released - acquired if took > 0.3: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) def assertLocked(): assert not _lock.acquire(False) return True
import threading import contextlib import time import traceback import logging _lock = threading.Lock() def prettyStack(): return "\n".join([line.strip() for line in traceback.format_stack()]) @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=prettyStack())) yield released = time.time() took = released - acquired if took > 0.3: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=prettyStack())) def assertLocked(): assert not _lock.acquire(False) return True
Print the stack info more clearly, when holding the global lock for too long
Print the stack info more clearly, when holding the global lock for too long
Python
apache-2.0
Stratoscale/rackattack-virtual,eliran-stratoscale/rackattack-virtual,Stratoscale/rackattack-virtual,eliran-stratoscale/rackattack-virtual
python
## Code Before: import threading import contextlib import time import traceback import logging _lock = threading.Lock() @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) yield released = time.time() took = released - acquired if took > 0.3: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=traceback.format_stack())) def assertLocked(): assert not _lock.acquire(False) return True ## Instruction: Print the stack info more clearly, when holding the global lock for too long ## Code After: import threading import contextlib import time import traceback import logging _lock = threading.Lock() def prettyStack(): return "\n".join([line.strip() for line in traceback.format_stack()]) @contextlib.contextmanager def lock(): before = time.time() with _lock: acquired = time.time() took = acquired - before if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=prettyStack())) yield released = time.time() took = released - acquired if took > 0.3: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=prettyStack())) def assertLocked(): assert not _lock.acquire(False) return True
# ... existing code ... _lock = threading.Lock() def prettyStack(): return "\n".join([line.strip() for line in traceback.format_stack()]) @contextlib.contextmanager # ... modified code ... if took > 0.1: logging.error( "Acquiring the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=prettyStack())) yield released = time.time() took = released - acquired ... if took > 0.3: logging.error( "Holding the global lock took more than 0.1s: %(took)ss. Stack:\n%(stack)s", dict( took=took, stack=prettyStack())) def assertLocked(): # ... rest of the code ...
66122432b36ed35ec40499d2d93fc51fa02c20e0
STRUCT/STRUCTLinkDef.h
STRUCT/STRUCTLinkDef.h
/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ /* $Id$ */ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; #pragma link C++ class AliBODY; #pragma link C++ class AliMAG; #pragma link C++ class AliABSO; #pragma link C++ class AliDIPO; #pragma link C++ class AliDIPOv1; #pragma link C++ class AliDIPOv2; #pragma link C++ class AliFRAME; #pragma link C++ class AliFRAMEv0; #pragma link C++ class AliFRAMEv1; #pragma link C++ class AliHALL; #pragma link C++ class AliPIPE; #pragma link C++ class AliPIPEv0; #pragma link C++ class AliPIPEv1; #pragma link C++ class AliPIPEv3; #pragma link C++ class AliSHIL; #endif
/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ /* $Id$ */ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; #pragma link C++ class AliBODY; #pragma link C++ class AliMAG; #pragma link C++ class AliABSO; #pragma link C++ class AliABSOv0; #pragma link C++ class AliDIPO; #pragma link C++ class AliDIPOv1; #pragma link C++ class AliDIPOv2; #pragma link C++ class AliFRAME; #pragma link C++ class AliFRAMEv0; #pragma link C++ class AliFRAMEv1; #pragma link C++ class AliHALL; #pragma link C++ class AliPIPE; #pragma link C++ class AliPIPEv0; #pragma link C++ class AliPIPEv1; #pragma link C++ class AliPIPEv3; #pragma link C++ class AliSHIL; #pragma link C++ class AliSHILv0; #endif
Add new classes to LinkDef
Add new classes to LinkDef
C
bsd-3-clause
coppedis/AliRoot,ALICEHLT/AliRoot,coppedis/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,alisw/AliRoot,miranov25/AliRoot,miranov25/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,shahor02/AliRoot,coppedis/AliRoot,miranov25/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,sebaleh/AliRoot,mkrzewic/AliRoot,miranov25/AliRoot,coppedis/AliRoot,shahor02/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,ALICEHLT/AliRoot,ALICEHLT/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,shahor02/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,jgrosseo/AliRoot,coppedis/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,mkrzewic/AliRoot,miranov25/AliRoot,sebaleh/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot
c
## Code Before: /* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ /* $Id$ */ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; #pragma link C++ class AliBODY; #pragma link C++ class AliMAG; #pragma link C++ class AliABSO; #pragma link C++ class AliDIPO; #pragma link C++ class AliDIPOv1; #pragma link C++ class AliDIPOv2; #pragma link C++ class AliFRAME; #pragma link C++ class AliFRAMEv0; #pragma link C++ class AliFRAMEv1; #pragma link C++ class AliHALL; #pragma link C++ class AliPIPE; #pragma link C++ class AliPIPEv0; #pragma link C++ class AliPIPEv1; #pragma link C++ class AliPIPEv3; #pragma link C++ class AliSHIL; #endif ## Instruction: Add new classes to LinkDef ## Code After: /* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ /* $Id$ */ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; #pragma link C++ class AliBODY; #pragma link C++ class AliMAG; #pragma link C++ class AliABSO; #pragma link C++ class AliABSOv0; #pragma link C++ class AliDIPO; #pragma link C++ class AliDIPOv1; #pragma link C++ class AliDIPOv2; #pragma link C++ class AliFRAME; #pragma link C++ class AliFRAMEv0; #pragma link C++ class AliFRAMEv1; #pragma link C++ class AliHALL; #pragma link C++ class AliPIPE; #pragma link C++ class AliPIPEv0; #pragma link C++ class AliPIPEv1; #pragma link C++ class AliPIPEv3; #pragma link C++ class AliSHIL; #pragma link C++ class AliSHILv0; #endif
// ... existing code ... #pragma link C++ class AliBODY; #pragma link C++ class AliMAG; #pragma link C++ class AliABSO; #pragma link C++ class AliABSOv0; #pragma link C++ class AliDIPO; #pragma link C++ class AliDIPOv1; #pragma link C++ class AliDIPOv2; // ... modified code ... #pragma link C++ class AliPIPEv1; #pragma link C++ class AliPIPEv3; #pragma link C++ class AliSHIL; #pragma link C++ class AliSHILv0; #endif // ... rest of the code ...
f41fefad188e8606036a394f28b7b8cc34be76fc
src/main/java/edu/virginia/psyc/pi/persistence/ParticipantExportDAO.java
src/main/java/edu/virginia/psyc/pi/persistence/ParticipantExportDAO.java
package edu.virginia.psyc.pi.persistence; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import edu.virginia.psyc.pi.domain.DoNotDelete; import edu.virginia.psyc.pi.domain.Exportable; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.util.Date; /** * Created by dan on 3/24/16. * Data about a Participant that can be exported. */ @Data @Entity @Table(name="participant") @Exportable @DoNotDelete public class ParticipantExportDAO { @JsonProperty("participantId") @Id private long id; private String theme; private String study; private String cbmCondition; private String prime; private boolean admin; private boolean emailOptout; private boolean active; private boolean increase30; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="EEE, dd MMM yyyy HH:mm:ss Z", timezone="EST") private Date lastLogin; private String currentSession; }
package edu.virginia.psyc.pi.persistence; import com.fasterxml.jackson.annotation.JsonFormat; import edu.virginia.psyc.pi.domain.DoNotDelete; import edu.virginia.psyc.pi.domain.Exportable; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.util.Date; /** * Created by dan on 3/24/16. * Data about a Participant that can be exported. */ @Data @Entity @Table(name="participant") @Exportable @DoNotDelete public class ParticipantExportDAO { @Id private long id; private String theme; private String study; private String cbmCondition; private String prime; private boolean admin; private boolean emailOptout; private boolean active; private boolean increase30; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="EEE, dd MMM yyyy HH:mm:ss Z", timezone="EST") private Date lastLogin; private String currentSession; }
Change ParticipantDAO back to id
Change ParticipantDAO back to id
Java
mit
danfunk/MindTrails,Diheng/mindtrails,danfunk/MindTrails,Diheng/PIServer,rango1900/MindTrails,Diheng/PIServer,rango1900/MindTrails,Diheng/PIServer,Diheng/PIServer,rango1900/MindTrails,Diheng/mindtrails,rango1900/MindTrails,danfunk/MindTrails,danfunk/MindTrails
java
## Code Before: package edu.virginia.psyc.pi.persistence; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import edu.virginia.psyc.pi.domain.DoNotDelete; import edu.virginia.psyc.pi.domain.Exportable; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.util.Date; /** * Created by dan on 3/24/16. * Data about a Participant that can be exported. */ @Data @Entity @Table(name="participant") @Exportable @DoNotDelete public class ParticipantExportDAO { @JsonProperty("participantId") @Id private long id; private String theme; private String study; private String cbmCondition; private String prime; private boolean admin; private boolean emailOptout; private boolean active; private boolean increase30; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="EEE, dd MMM yyyy HH:mm:ss Z", timezone="EST") private Date lastLogin; private String currentSession; } ## Instruction: Change ParticipantDAO back to id ## Code After: package edu.virginia.psyc.pi.persistence; import com.fasterxml.jackson.annotation.JsonFormat; import edu.virginia.psyc.pi.domain.DoNotDelete; import edu.virginia.psyc.pi.domain.Exportable; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.util.Date; /** * Created by dan on 3/24/16. * Data about a Participant that can be exported. */ @Data @Entity @Table(name="participant") @Exportable @DoNotDelete public class ParticipantExportDAO { @Id private long id; private String theme; private String study; private String cbmCondition; private String prime; private boolean admin; private boolean emailOptout; private boolean active; private boolean increase30; @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="EEE, dd MMM yyyy HH:mm:ss Z", timezone="EST") private Date lastLogin; private String currentSession; }
// ... existing code ... package edu.virginia.psyc.pi.persistence; import com.fasterxml.jackson.annotation.JsonFormat; import edu.virginia.psyc.pi.domain.DoNotDelete; import edu.virginia.psyc.pi.domain.Exportable; import lombok.Data; // ... modified code ... @DoNotDelete public class ParticipantExportDAO { @Id private long id; private String theme; private String study; // ... rest of the code ...
36d98f499316d4695c20544701dd1d4300aca600
corehq/ex-submodules/dimagi/utils/couch/cache/cache_core/lib.py
corehq/ex-submodules/dimagi/utils/couch/cache/cache_core/lib.py
from __future__ import absolute_import from __future__ import unicode_literals import simplejson from django_redis.cache import RedisCache from . import CACHE_DOCS, key_doc_id, rcache from corehq.util.soft_assert import soft_assert def invalidate_doc_generation(doc): from .gen import GenerationCache doc_type = doc.get('doc_type', None) generation_mgr = GenerationCache.doc_type_generation_map() if doc_type in generation_mgr: generation_mgr[doc_type].invalidate_all() def _get_cached_doc_only(doc_id): """ helper cache retrieval method for open_doc - for use by views in retrieving their docs. """ doc = rcache().get(key_doc_id(doc_id), None) if doc and CACHE_DOCS: return simplejson.loads(doc) else: return None class HQRedisCache(RedisCache): def _track_call(self): hq_assert = soft_assert(['sreddy+redis' + '@' + 'dimagi.com']) hq_assert(False, msg="Detected Redis multikey operation") def set_many(self, *args, **kwargs): self._track_call() super(HQRedisCache, self).set_many(*args, **kwargs) def get_many(self, *args, **kwargs): self._track_call() return super(HQRedisCache, self).get_many(*args, **kwargs) def delete_many(self, *args, **kwargs): self._track_call() return super(HQRedisCache, self).delete_many(*args, **kwargs)
from __future__ import absolute_import from __future__ import unicode_literals import simplejson from . import CACHE_DOCS, key_doc_id, rcache def invalidate_doc_generation(doc): from .gen import GenerationCache doc_type = doc.get('doc_type', None) generation_mgr = GenerationCache.doc_type_generation_map() if doc_type in generation_mgr: generation_mgr[doc_type].invalidate_all() def _get_cached_doc_only(doc_id): """ helper cache retrieval method for open_doc - for use by views in retrieving their docs. """ doc = rcache().get(key_doc_id(doc_id), None) if doc and CACHE_DOCS: return simplejson.loads(doc) else: return None
Revert "track multi key ops in Redis"
Revert "track multi key ops in Redis"
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
python
## Code Before: from __future__ import absolute_import from __future__ import unicode_literals import simplejson from django_redis.cache import RedisCache from . import CACHE_DOCS, key_doc_id, rcache from corehq.util.soft_assert import soft_assert def invalidate_doc_generation(doc): from .gen import GenerationCache doc_type = doc.get('doc_type', None) generation_mgr = GenerationCache.doc_type_generation_map() if doc_type in generation_mgr: generation_mgr[doc_type].invalidate_all() def _get_cached_doc_only(doc_id): """ helper cache retrieval method for open_doc - for use by views in retrieving their docs. """ doc = rcache().get(key_doc_id(doc_id), None) if doc and CACHE_DOCS: return simplejson.loads(doc) else: return None class HQRedisCache(RedisCache): def _track_call(self): hq_assert = soft_assert(['sreddy+redis' + '@' + 'dimagi.com']) hq_assert(False, msg="Detected Redis multikey operation") def set_many(self, *args, **kwargs): self._track_call() super(HQRedisCache, self).set_many(*args, **kwargs) def get_many(self, *args, **kwargs): self._track_call() return super(HQRedisCache, self).get_many(*args, **kwargs) def delete_many(self, *args, **kwargs): self._track_call() return super(HQRedisCache, self).delete_many(*args, **kwargs) ## Instruction: Revert "track multi key ops in Redis" ## Code After: from __future__ import absolute_import from __future__ import unicode_literals import simplejson from . import CACHE_DOCS, key_doc_id, rcache def invalidate_doc_generation(doc): from .gen import GenerationCache doc_type = doc.get('doc_type', None) generation_mgr = GenerationCache.doc_type_generation_map() if doc_type in generation_mgr: generation_mgr[doc_type].invalidate_all() def _get_cached_doc_only(doc_id): """ helper cache retrieval method for open_doc - for use by views in retrieving their docs. """ doc = rcache().get(key_doc_id(doc_id), None) if doc and CACHE_DOCS: return simplejson.loads(doc) else: return None
# ... existing code ... from __future__ import absolute_import from __future__ import unicode_literals import simplejson from . import CACHE_DOCS, key_doc_id, rcache def invalidate_doc_generation(doc): # ... modified code ... return simplejson.loads(doc) else: return None # ... rest of the code ...
38677e5e344ce780d0b82c319da647efc9a95cf5
src/main/java/com/bol/cd/stash/StashClient.java
src/main/java/com/bol/cd/stash/StashClient.java
package com.bol.cd.stash; import feign.Feign; import feign.RequestInterceptor; import feign.auth.BasicAuthRequestInterceptor; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.jaxrs.JAXRSModule; import java.util.Arrays; import com.bol.cd.stash.model.JsonApplicationMediaTypeInterceptor; import com.bol.cd.stash.request.DeleteBranch; public class StashClient { private static String projectKey = "TPT"; private static String repositorySlug = "testrepository"; public static StashApi createClient() { return Feign.builder().contract(new JAXRSModule.JAXRSContract()).decoder(new JacksonDecoder()).encoder(new JacksonEncoder()) .requestInterceptors(getRequestInterceptors()).target(StashApi.class, "http://localhost:7990"); } private static Iterable<RequestInterceptor> getRequestInterceptors() { return Arrays.asList(new BasicAuthRequestInterceptor("admin", "password"), new JsonApplicationMediaTypeInterceptor()); } }
package com.bol.cd.stash; import feign.Feign; import feign.RequestInterceptor; import feign.auth.BasicAuthRequestInterceptor; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.jaxrs.JAXRSModule; import java.util.Arrays; import com.bol.cd.stash.model.JsonApplicationMediaTypeInterceptor; import com.bol.cd.stash.request.DeleteBranch; public class StashClient { public static StashApi createClient() { return Feign.builder().contract(new JAXRSModule.JAXRSContract()).decoder(new JacksonDecoder()).encoder(new JacksonEncoder()) .requestInterceptors(getRequestInterceptors()).target(StashApi.class, "http://localhost:7990"); } private static Iterable<RequestInterceptor> getRequestInterceptors() { return Arrays.asList(new BasicAuthRequestInterceptor("admin", "password"), new JsonApplicationMediaTypeInterceptor()); } }
Refactor in progress - cleaning...
Refactor in progress - cleaning...
Java
apache-2.0
bolcom/stash-java-client-cd
java
## Code Before: package com.bol.cd.stash; import feign.Feign; import feign.RequestInterceptor; import feign.auth.BasicAuthRequestInterceptor; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.jaxrs.JAXRSModule; import java.util.Arrays; import com.bol.cd.stash.model.JsonApplicationMediaTypeInterceptor; import com.bol.cd.stash.request.DeleteBranch; public class StashClient { private static String projectKey = "TPT"; private static String repositorySlug = "testrepository"; public static StashApi createClient() { return Feign.builder().contract(new JAXRSModule.JAXRSContract()).decoder(new JacksonDecoder()).encoder(new JacksonEncoder()) .requestInterceptors(getRequestInterceptors()).target(StashApi.class, "http://localhost:7990"); } private static Iterable<RequestInterceptor> getRequestInterceptors() { return Arrays.asList(new BasicAuthRequestInterceptor("admin", "password"), new JsonApplicationMediaTypeInterceptor()); } } ## Instruction: Refactor in progress - cleaning... ## Code After: package com.bol.cd.stash; import feign.Feign; import feign.RequestInterceptor; import feign.auth.BasicAuthRequestInterceptor; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.jaxrs.JAXRSModule; import java.util.Arrays; import com.bol.cd.stash.model.JsonApplicationMediaTypeInterceptor; import com.bol.cd.stash.request.DeleteBranch; public class StashClient { public static StashApi createClient() { return Feign.builder().contract(new JAXRSModule.JAXRSContract()).decoder(new JacksonDecoder()).encoder(new JacksonEncoder()) .requestInterceptors(getRequestInterceptors()).target(StashApi.class, "http://localhost:7990"); } private static Iterable<RequestInterceptor> getRequestInterceptors() { return Arrays.asList(new BasicAuthRequestInterceptor("admin", "password"), new JsonApplicationMediaTypeInterceptor()); } }
... public class StashClient { public static StashApi createClient() { return Feign.builder().contract(new JAXRSModule.JAXRSContract()).decoder(new JacksonDecoder()).encoder(new JacksonEncoder()) ...
13301dfe93bcdd44218166bdab1c7aeacd4e4a7c
winthrop/annotation/models.py
winthrop/annotation/models.py
from urllib.parse import urlparse from django.db import models from django.urls import resolve, Resolver404 from annotator_store.models import BaseAnnotation from djiffy.models import Canvas from winthrop.people.models import Person class Annotation(BaseAnnotation): # NOTE: do we want to associate explicitly with canvas in the db? # could just use uri, but faster lookup if we associate... canvas = models.ForeignKey(Canvas, null=True, blank=True) author = models.ForeignKey(Person, null=True, blank=True) def info(self): info = super(Annotation, self).info() info['extra_data'] = 'foo' return info def save(self, *args, **kwargs): # NOTE: could set the canvas uri in javascript instead # of using page uri, but for now determine canvas id # based on the page uri try: match = resolve(urlparse(self.uri).path) if match.url_name == 'page' and 'djiffy' in match.namespaces: self.canvas = Canvas.objects.get( short_id=match.kwargs['id'], book__short_id=match.kwargs['book_id'] ) except Resolver404: pass super(Annotation, self).save()
from urllib.parse import urlparse from django.db import models from django.urls import resolve, Resolver404 from annotator_store.models import BaseAnnotation from djiffy.models import Canvas from winthrop.people.models import Person class Annotation(BaseAnnotation): # NOTE: do we want to associate explicitly with canvas in the db? # could just use uri, but faster lookup if we associate... canvas = models.ForeignKey(Canvas, null=True, blank=True) author = models.ForeignKey(Person, null=True, blank=True) def info(self): info = super(Annotation, self).info() info['extra_data'] = 'foo' return info def save(self, *args, **kwargs): # for image annotation, URI should be set to canvas URI; look up # canvas by URI and associate with the record self.canvas = None try: self.canvas = Canvas.objects.get(uri=self.uri) except Canvas.DoesNotExist: pass super(Annotation, self).save() def handle_extra_data(self, data, request): '''Handle any "extra" data that is not part of the stock annotation data model. Use this method to customize the logic for updating an annotation from request data.''' if 'author' in data: self.author = Person.objects.get(id=data['author']['id']) del data['author'] return data def info(self): # extend the default info impleentation (used to generate json) # to include local database fields in the output info = super(Annotation, self).info() if self.author: info['author'] = { 'name': self.author.authorized_name, 'id': self.author.id } return info
Add author field & autocomplete to annotation model+interface
Add author field & autocomplete to annotation model+interface
Python
apache-2.0
Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django
python
## Code Before: from urllib.parse import urlparse from django.db import models from django.urls import resolve, Resolver404 from annotator_store.models import BaseAnnotation from djiffy.models import Canvas from winthrop.people.models import Person class Annotation(BaseAnnotation): # NOTE: do we want to associate explicitly with canvas in the db? # could just use uri, but faster lookup if we associate... canvas = models.ForeignKey(Canvas, null=True, blank=True) author = models.ForeignKey(Person, null=True, blank=True) def info(self): info = super(Annotation, self).info() info['extra_data'] = 'foo' return info def save(self, *args, **kwargs): # NOTE: could set the canvas uri in javascript instead # of using page uri, but for now determine canvas id # based on the page uri try: match = resolve(urlparse(self.uri).path) if match.url_name == 'page' and 'djiffy' in match.namespaces: self.canvas = Canvas.objects.get( short_id=match.kwargs['id'], book__short_id=match.kwargs['book_id'] ) except Resolver404: pass super(Annotation, self).save() ## Instruction: Add author field & autocomplete to annotation model+interface ## Code After: from urllib.parse import urlparse from django.db import models from django.urls import resolve, Resolver404 from annotator_store.models import BaseAnnotation from djiffy.models import Canvas from winthrop.people.models import Person class Annotation(BaseAnnotation): # NOTE: do we want to associate explicitly with canvas in the db? # could just use uri, but faster lookup if we associate... canvas = models.ForeignKey(Canvas, null=True, blank=True) author = models.ForeignKey(Person, null=True, blank=True) def info(self): info = super(Annotation, self).info() info['extra_data'] = 'foo' return info def save(self, *args, **kwargs): # for image annotation, URI should be set to canvas URI; look up # canvas by URI and associate with the record self.canvas = None try: self.canvas = Canvas.objects.get(uri=self.uri) except Canvas.DoesNotExist: pass super(Annotation, self).save() def handle_extra_data(self, data, request): '''Handle any "extra" data that is not part of the stock annotation data model. Use this method to customize the logic for updating an annotation from request data.''' if 'author' in data: self.author = Person.objects.get(id=data['author']['id']) del data['author'] return data def info(self): # extend the default info impleentation (used to generate json) # to include local database fields in the output info = super(Annotation, self).info() if self.author: info['author'] = { 'name': self.author.authorized_name, 'id': self.author.id } return info
# ... existing code ... return info def save(self, *args, **kwargs): # for image annotation, URI should be set to canvas URI; look up # canvas by URI and associate with the record self.canvas = None try: self.canvas = Canvas.objects.get(uri=self.uri) except Canvas.DoesNotExist: pass super(Annotation, self).save() def handle_extra_data(self, data, request): '''Handle any "extra" data that is not part of the stock annotation data model. Use this method to customize the logic for updating an annotation from request data.''' if 'author' in data: self.author = Person.objects.get(id=data['author']['id']) del data['author'] return data def info(self): # extend the default info impleentation (used to generate json) # to include local database fields in the output info = super(Annotation, self).info() if self.author: info['author'] = { 'name': self.author.authorized_name, 'id': self.author.id } return info # ... rest of the code ...
8931025d53f472c3f1cb9c320eb796f0ea14274e
dddp/msg.py
dddp/msg.py
"""Django DDP utils for DDP messaging.""" from dddp import THREAD_LOCAL as this def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg type.""" serializer = this.serializer data = serializer.serialize([obj])[0] # collection name is <app>.<model> name = data['model'] # cast ID as string if not isinstance(data['pk'], basestring): data['pk'] = '%d' % data['pk'] payload = { 'msg': msg, 'collection': name, 'id': data['pk'], } if msg != 'removed': payload['fields'] = data['fields'] return (name, payload)
"""Django DDP utils for DDP messaging.""" from copy import deepcopy from dddp import THREAD_LOCAL as this from django.db.models.expressions import ExpressionNode def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg type.""" # check for F expressions exps = [ name for name, val in vars(obj).items() if isinstance(val, ExpressionNode) ] if exps: # clone and update obj with values but only for the expression fields obj = deepcopy(obj) # Django 1.8 makes obj._meta public --> pylint: disable=W0212 for name, val in obj._meta.model.objects.values(*exps).get(pk=obj.pk): setattr(obj, name, val) # run serialization now that all fields are "concrete" (not F expressions) serializer = this.serializer data = serializer.serialize([obj])[0] # collection name is <app>.<model> name = data['model'] # cast ID as string if not isinstance(data['pk'], basestring): data['pk'] = '%d' % data['pk'] payload = { 'msg': msg, 'collection': name, 'id': data['pk'], } if msg != 'removed': payload['fields'] = data['fields'] return (name, payload)
Support serializing objects that are saved with F expressions by reading field values for F expressions from database explicitly before serializing.
Support serializing objects that are saved with F expressions by reading field values for F expressions from database explicitly before serializing.
Python
mit
django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,commoncode/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,django-ddp/django-ddp
python
## Code Before: """Django DDP utils for DDP messaging.""" from dddp import THREAD_LOCAL as this def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg type.""" serializer = this.serializer data = serializer.serialize([obj])[0] # collection name is <app>.<model> name = data['model'] # cast ID as string if not isinstance(data['pk'], basestring): data['pk'] = '%d' % data['pk'] payload = { 'msg': msg, 'collection': name, 'id': data['pk'], } if msg != 'removed': payload['fields'] = data['fields'] return (name, payload) ## Instruction: Support serializing objects that are saved with F expressions by reading field values for F expressions from database explicitly before serializing. ## Code After: """Django DDP utils for DDP messaging.""" from copy import deepcopy from dddp import THREAD_LOCAL as this from django.db.models.expressions import ExpressionNode def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg type.""" # check for F expressions exps = [ name for name, val in vars(obj).items() if isinstance(val, ExpressionNode) ] if exps: # clone and update obj with values but only for the expression fields obj = deepcopy(obj) # Django 1.8 makes obj._meta public --> pylint: disable=W0212 for name, val in obj._meta.model.objects.values(*exps).get(pk=obj.pk): setattr(obj, name, val) # run serialization now that all fields are "concrete" (not F expressions) serializer = this.serializer data = serializer.serialize([obj])[0] # collection name is <app>.<model> name = data['model'] # cast ID as string if not isinstance(data['pk'], basestring): data['pk'] = '%d' % data['pk'] payload = { 'msg': msg, 'collection': name, 'id': data['pk'], } if msg != 'removed': payload['fields'] = data['fields'] return (name, payload)
// ... existing code ... """Django DDP utils for DDP messaging.""" from copy import deepcopy from dddp import THREAD_LOCAL as this from django.db.models.expressions import ExpressionNode def obj_change_as_msg(obj, msg): """Generate a DDP msg for obj with specified msg type.""" # check for F expressions exps = [ name for name, val in vars(obj).items() if isinstance(val, ExpressionNode) ] if exps: # clone and update obj with values but only for the expression fields obj = deepcopy(obj) # Django 1.8 makes obj._meta public --> pylint: disable=W0212 for name, val in obj._meta.model.objects.values(*exps).get(pk=obj.pk): setattr(obj, name, val) # run serialization now that all fields are "concrete" (not F expressions) serializer = this.serializer data = serializer.serialize([obj])[0] // ... rest of the code ...
320214ca1636415bc4d677ba9e3b40f0bf24c8f9
openprescribing/frontend/migrations/0008_create_searchbookmark.py
openprescribing/frontend/migrations/0008_create_searchbookmark.py
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('frontend', '0007_auto_20160908_0811'), ] operations = [ migrations.CreateModel( name='SearchBookmark', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('low_is_good', models.NullBooleanField()), ('url', models.CharField(max_length=200)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ] ) ]
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('frontend', '0007_add_cost_per_fields'), ] operations = [ migrations.CreateModel( name='SearchBookmark', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('low_is_good', models.NullBooleanField()), ('url', models.CharField(max_length=200)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ] ) ]
Fix multiple leaf nodes in migrations
Fix multiple leaf nodes in migrations
Python
mit
ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc
python
## Code Before: from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('frontend', '0007_auto_20160908_0811'), ] operations = [ migrations.CreateModel( name='SearchBookmark', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('low_is_good', models.NullBooleanField()), ('url', models.CharField(max_length=200)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ] ) ] ## Instruction: Fix multiple leaf nodes in migrations ## Code After: from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('frontend', '0007_add_cost_per_fields'), ] operations = [ migrations.CreateModel( name='SearchBookmark', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=200)), ('low_is_good', models.NullBooleanField()), ('url', models.CharField(max_length=200)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ] ) ]
# ... existing code ... dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('frontend', '0007_add_cost_per_fields'), ] operations = [ # ... rest of the code ...
dd63ef92e14a3111fd0914e9994aaea9ebd4e668
hcalendar/hcalendar.py
hcalendar/hcalendar.py
import bs4 from vcalendar import vCalendar class hCalendar(object): def __init__(self, markup, value=None, key='id'): self._soup = bs4.BeautifulSoup(markup) if value: self._soup = self._soup.find(**{key: value}) self._cals = self._soup.findAll(attrs='vcalendar') if self._cals: self._cals = map(vCalendar, self._cals) else: self._cals = [vCalendar(self._soup)] def __len__(self): return len(self._cals) def __iter__(self): return iter(self._cals) def __getitem__(self, key): return self._cals[key] def getCalendar(self): return self._cals
from vcalendar import vCalendar from bs4 import BeautifulSoup class hCalendar(object): def __init__(self, markup, value=None, key='id'): if isinstance(markup, BeautifulSoup): self._soup = markup else: self._soup = BeautifulSoup(markup) if value: self._soup = self._soup.find(**{key: value}) self._cals = self._soup.findAll(attrs='vcalendar') if self._cals: self._cals = map(vCalendar, self._cals) else: self._cals = [vCalendar(self._soup)] def __len__(self): return len(self._cals) def __iter__(self): return iter(self._cals) def __getitem__(self, key): return self._cals[key] def getCalendar(self): return self._cals
Allow BeautifulSoup object being passed into hCalendar
Allow BeautifulSoup object being passed into hCalendar
Python
mit
mback2k/python-hcalendar
python
## Code Before: import bs4 from vcalendar import vCalendar class hCalendar(object): def __init__(self, markup, value=None, key='id'): self._soup = bs4.BeautifulSoup(markup) if value: self._soup = self._soup.find(**{key: value}) self._cals = self._soup.findAll(attrs='vcalendar') if self._cals: self._cals = map(vCalendar, self._cals) else: self._cals = [vCalendar(self._soup)] def __len__(self): return len(self._cals) def __iter__(self): return iter(self._cals) def __getitem__(self, key): return self._cals[key] def getCalendar(self): return self._cals ## Instruction: Allow BeautifulSoup object being passed into hCalendar ## Code After: from vcalendar import vCalendar from bs4 import BeautifulSoup class hCalendar(object): def __init__(self, markup, value=None, key='id'): if isinstance(markup, BeautifulSoup): self._soup = markup else: self._soup = BeautifulSoup(markup) if value: self._soup = self._soup.find(**{key: value}) self._cals = self._soup.findAll(attrs='vcalendar') if self._cals: self._cals = map(vCalendar, self._cals) else: self._cals = [vCalendar(self._soup)] def __len__(self): return len(self._cals) def __iter__(self): return iter(self._cals) def __getitem__(self, key): return self._cals[key] def getCalendar(self): return self._cals
# ... existing code ... from vcalendar import vCalendar from bs4 import BeautifulSoup class hCalendar(object): def __init__(self, markup, value=None, key='id'): if isinstance(markup, BeautifulSoup): self._soup = markup else: self._soup = BeautifulSoup(markup) if value: self._soup = self._soup.find(**{key: value}) self._cals = self._soup.findAll(attrs='vcalendar') # ... rest of the code ...
844a165267e50d92b59c7c8fea97edcb1c8acf79
judge/views/status.py
judge/views/status.py
from django.shortcuts import render_to_response from django.template import RequestContext from judge.models import Judge __all__ = ['status', 'status_table'] def status(request): return render_to_response('judge_status.jade', { 'judges': Judge.objects.all(), 'title': 'Status', }, context_instance=RequestContext(request)) def status_table(request): return render_to_response('judge_status_table.jade', { 'judges': Judge.objects.all(), }, context_instance=RequestContext(request))
from django.shortcuts import render_to_response from django.template import RequestContext from judge.models import Judge __all__ = ['status', 'status_table'] def status(request): return render_to_response('judge_status.jade', { 'judges': Judge.objects.all(), 'title': 'Status', }, context_instance=RequestContext(request)) def status_table(request): return render_to_response('judge_status_table.jade', { 'judges': Judge.objects.all().order_by('load'), }, context_instance=RequestContext(request))
Order judge list by load
Order judge list by load
Python
agpl-3.0
Phoenix1369/site,Phoenix1369/site,DMOJ/site,Minkov/site,DMOJ/site,Phoenix1369/site,monouno/site,monouno/site,DMOJ/site,Minkov/site,monouno/site,Minkov/site,Minkov/site,monouno/site,Phoenix1369/site,DMOJ/site,monouno/site
python
## Code Before: from django.shortcuts import render_to_response from django.template import RequestContext from judge.models import Judge __all__ = ['status', 'status_table'] def status(request): return render_to_response('judge_status.jade', { 'judges': Judge.objects.all(), 'title': 'Status', }, context_instance=RequestContext(request)) def status_table(request): return render_to_response('judge_status_table.jade', { 'judges': Judge.objects.all(), }, context_instance=RequestContext(request)) ## Instruction: Order judge list by load ## Code After: from django.shortcuts import render_to_response from django.template import RequestContext from judge.models import Judge __all__ = ['status', 'status_table'] def status(request): return render_to_response('judge_status.jade', { 'judges': Judge.objects.all(), 'title': 'Status', }, context_instance=RequestContext(request)) def status_table(request): return render_to_response('judge_status_table.jade', { 'judges': Judge.objects.all().order_by('load'), }, context_instance=RequestContext(request))
... def status_table(request): return render_to_response('judge_status_table.jade', { 'judges': Judge.objects.all().order_by('load'), }, context_instance=RequestContext(request)) ...
cad4e7e9feaf7fefe9ef91dea18594b095861204
content_editor/models.py
content_editor/models.py
from types import SimpleNamespace from django.db import models __all__ = ("Region", "Template", "create_plugin_base") class Region(SimpleNamespace): key = "" title = "unnamed" inherited = False class Template(SimpleNamespace): key = "" template_name = None title = "" regions = [] def create_plugin_base(content_base): """ This is purely an internal method. Here, we create a base class for the concrete content types, which are built in ``create_plugin``. The three fields added to build a concrete content type class/model are ``parent``, ``region`` and ``ordering``. """ class PluginBase(models.Model): parent = models.ForeignKey( content_base, related_name="%(app_label)s_%(class)s_set", on_delete=models.CASCADE, ) region = models.CharField(max_length=255) ordering = models.IntegerField(default=0) class Meta: abstract = True app_label = content_base._meta.app_label ordering = ["ordering"] def __str__(self): return "%s<region=%s ordering=%s pk=%s>" % ( self._meta.label, self.region, self.ordering, self.pk, ) @classmethod def get_queryset(cls): return cls.objects.all() return PluginBase
from types import SimpleNamespace from django.db import models __all__ = ("Region", "Template", "create_plugin_base") class Region(SimpleNamespace): key = "" title = "unnamed" inherited = False class Template(SimpleNamespace): key = "" template_name = None title = "" regions = [] def create_plugin_base(content_base): """ Create and return a base class for plugins The base class contains a ``parent`` foreign key and the required ``region`` and ``ordering`` fields. """ class PluginBase(models.Model): parent = models.ForeignKey( content_base, related_name="%(app_label)s_%(class)s_set", on_delete=models.CASCADE, ) region = models.CharField(max_length=255) ordering = models.IntegerField(default=0) class Meta: abstract = True app_label = content_base._meta.app_label ordering = ["ordering"] def __str__(self): return "%s<region=%s ordering=%s pk=%s>" % ( self._meta.label, self.region, self.ordering, self.pk, ) @classmethod def get_queryset(cls): return cls.objects.all() return PluginBase
Fix the docstring of create_plugin_base: Not internal, it's the main API
Fix the docstring of create_plugin_base: Not internal, it's the main API
Python
bsd-3-clause
matthiask/django-content-editor,matthiask/django-content-editor,matthiask/django-content-editor,matthiask/django-content-editor
python
## Code Before: from types import SimpleNamespace from django.db import models __all__ = ("Region", "Template", "create_plugin_base") class Region(SimpleNamespace): key = "" title = "unnamed" inherited = False class Template(SimpleNamespace): key = "" template_name = None title = "" regions = [] def create_plugin_base(content_base): """ This is purely an internal method. Here, we create a base class for the concrete content types, which are built in ``create_plugin``. The three fields added to build a concrete content type class/model are ``parent``, ``region`` and ``ordering``. """ class PluginBase(models.Model): parent = models.ForeignKey( content_base, related_name="%(app_label)s_%(class)s_set", on_delete=models.CASCADE, ) region = models.CharField(max_length=255) ordering = models.IntegerField(default=0) class Meta: abstract = True app_label = content_base._meta.app_label ordering = ["ordering"] def __str__(self): return "%s<region=%s ordering=%s pk=%s>" % ( self._meta.label, self.region, self.ordering, self.pk, ) @classmethod def get_queryset(cls): return cls.objects.all() return PluginBase ## Instruction: Fix the docstring of create_plugin_base: Not internal, it's the main API ## Code After: from types import SimpleNamespace from django.db import models __all__ = ("Region", "Template", "create_plugin_base") class Region(SimpleNamespace): key = "" title = "unnamed" inherited = False class Template(SimpleNamespace): key = "" template_name = None title = "" regions = [] def create_plugin_base(content_base): """ Create and return a base class for plugins The base class contains a ``parent`` foreign key and the required ``region`` and ``ordering`` fields. """ class PluginBase(models.Model): parent = models.ForeignKey( content_base, related_name="%(app_label)s_%(class)s_set", on_delete=models.CASCADE, ) region = models.CharField(max_length=255) ordering = models.IntegerField(default=0) class Meta: abstract = True app_label = content_base._meta.app_label ordering = ["ordering"] def __str__(self): return "%s<region=%s ordering=%s pk=%s>" % ( self._meta.label, self.region, self.ordering, self.pk, ) @classmethod def get_queryset(cls): return cls.objects.all() return PluginBase
... def create_plugin_base(content_base): """ Create and return a base class for plugins The base class contains a ``parent`` foreign key and the required ``region`` and ``ordering`` fields. """ class PluginBase(models.Model): ...
d84323ce8cd37c5b88a84e8a8ca2e80dc2b51acc
WordPressCom-Stats-iOS/StatsSection.h
WordPressCom-Stats-iOS/StatsSection.h
typedef NS_ENUM(NSInteger, StatsSection) { StatsSectionGraph, StatsSectionPeriodHeader, StatsSectionEvents, StatsSectionPosts, StatsSectionReferrers, StatsSectionClicks, StatsSectionCountry, StatsSectionVideos, StatsSectionAuthors, StatsSectionSearchTerms, StatsSectionComments, StatsSectionTagsCategories, StatsSectionFollowers, StatsSectionPublicize, StatsSectionWebVersion }; typedef NS_ENUM(NSInteger, StatsSubSection) { StatsSubSectionCommentsByAuthor = 100, StatsSubSectionCommentsByPosts, StatsSubSectionFollowersDotCom, StatsSubSectionFollowersEmail, StatsSubSectionNone };
typedef NS_ENUM(NSInteger, StatsSection) { StatsSectionGraph, StatsSectionPeriodHeader, StatsSectionEvents, StatsSectionPosts, StatsSectionReferrers, StatsSectionClicks, StatsSectionCountry, StatsSectionVideos, StatsSectionAuthors, StatsSectionSearchTerms, StatsSectionComments, StatsSectionTagsCategories, StatsSectionFollowers, StatsSectionPublicize, StatsSectionWebVersion, StatsSectionPostDetailsGraph, StatsSectionPostDetailsMonthsYears, StatsSectionPostDetailsAveragePerDay, StatsSectionPostDetailsRecentWeeks }; typedef NS_ENUM(NSInteger, StatsSubSection) { StatsSubSectionCommentsByAuthor = 100, StatsSubSectionCommentsByPosts, StatsSubSectionFollowersDotCom, StatsSubSectionFollowersEmail, StatsSubSectionNone };
Add new sections for post details
Add new sections for post details
C
mit
wordpress-mobile/WordPressCom-Stats-iOS,wordpress-mobile/WordPressCom-Stats-iOS
c
## Code Before: typedef NS_ENUM(NSInteger, StatsSection) { StatsSectionGraph, StatsSectionPeriodHeader, StatsSectionEvents, StatsSectionPosts, StatsSectionReferrers, StatsSectionClicks, StatsSectionCountry, StatsSectionVideos, StatsSectionAuthors, StatsSectionSearchTerms, StatsSectionComments, StatsSectionTagsCategories, StatsSectionFollowers, StatsSectionPublicize, StatsSectionWebVersion }; typedef NS_ENUM(NSInteger, StatsSubSection) { StatsSubSectionCommentsByAuthor = 100, StatsSubSectionCommentsByPosts, StatsSubSectionFollowersDotCom, StatsSubSectionFollowersEmail, StatsSubSectionNone }; ## Instruction: Add new sections for post details ## Code After: typedef NS_ENUM(NSInteger, StatsSection) { StatsSectionGraph, StatsSectionPeriodHeader, StatsSectionEvents, StatsSectionPosts, StatsSectionReferrers, StatsSectionClicks, StatsSectionCountry, StatsSectionVideos, StatsSectionAuthors, StatsSectionSearchTerms, StatsSectionComments, StatsSectionTagsCategories, StatsSectionFollowers, StatsSectionPublicize, StatsSectionWebVersion, StatsSectionPostDetailsGraph, StatsSectionPostDetailsMonthsYears, StatsSectionPostDetailsAveragePerDay, StatsSectionPostDetailsRecentWeeks }; typedef NS_ENUM(NSInteger, StatsSubSection) { StatsSubSectionCommentsByAuthor = 100, StatsSubSectionCommentsByPosts, StatsSubSectionFollowersDotCom, StatsSubSectionFollowersEmail, StatsSubSectionNone };
# ... existing code ... StatsSectionTagsCategories, StatsSectionFollowers, StatsSectionPublicize, StatsSectionWebVersion, StatsSectionPostDetailsGraph, StatsSectionPostDetailsMonthsYears, StatsSectionPostDetailsAveragePerDay, StatsSectionPostDetailsRecentWeeks }; typedef NS_ENUM(NSInteger, StatsSubSection) { # ... rest of the code ...
f54e7d2da0ba321bdd5900c9893f6fe76adad12f
telegramschoolbot/database.py
telegramschoolbot/database.py
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session import threading # Temporary logging """ import logging logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) """ threadLocal = threading.local() class Database: def __init__(self, config): self.config = config def Session(self): engine = getattr(threadLocal, "engine", None) if engine is None: threadLocal.engine = create_engine(self.config["database_url"]) session = getattr(threadLocal, "session", None) if session is None: session_factory = sessionmaker(bind=threadLocal.engine) threadLocal.session = scoped_session(session_factory) return threadLocal.session()
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session import threading # Temporary logging """ import logging logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) """ threadLocal = threading.local() class Database: def __init__(self, config): self.config = config def Session(self): engine = getattr(threadLocal, "engine", None) if engine is None: threadLocal.engine = create_engine(self.config["database_url"]) session_factory = getattr(threadLocal, "session_factory", None) if session_factory is None: session_factory = sessionmaker(bind=threadLocal.engine) threadLocal.session_factory = session_factory return session_factory()
Put the session factory in threadLocal, not the session
Put the session factory in threadLocal, not the session
Python
mit
paolobarbolini/TelegramSchoolBot
python
## Code Before: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session import threading # Temporary logging """ import logging logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) """ threadLocal = threading.local() class Database: def __init__(self, config): self.config = config def Session(self): engine = getattr(threadLocal, "engine", None) if engine is None: threadLocal.engine = create_engine(self.config["database_url"]) session = getattr(threadLocal, "session", None) if session is None: session_factory = sessionmaker(bind=threadLocal.engine) threadLocal.session = scoped_session(session_factory) return threadLocal.session() ## Instruction: Put the session factory in threadLocal, not the session ## Code After: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session import threading # Temporary logging """ import logging logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) """ threadLocal = threading.local() class Database: def __init__(self, config): self.config = config def Session(self): engine = getattr(threadLocal, "engine", None) if engine is None: threadLocal.engine = create_engine(self.config["database_url"]) session_factory = getattr(threadLocal, "session_factory", None) if session_factory is None: session_factory = sessionmaker(bind=threadLocal.engine) threadLocal.session_factory = session_factory return session_factory()
# ... existing code ... if engine is None: threadLocal.engine = create_engine(self.config["database_url"]) session_factory = getattr(threadLocal, "session_factory", None) if session_factory is None: session_factory = sessionmaker(bind=threadLocal.engine) threadLocal.session_factory = session_factory return session_factory() # ... rest of the code ...
2e3119b5f45a65f585e34b1239764d73b41c65fd
misp_modules/modules/expansion/__init__.py
misp_modules/modules/expansion/__init__.py
from . import _vmray __all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl', 'countrycode', 'cve', 'dns', 'eupi', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
from . import _vmray __all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl', 'countrycode', 'cve', 'dns', 'domaintools', 'eupi', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
Add domaintools to the import list
Add domaintools to the import list
Python
agpl-3.0
Rafiot/misp-modules,MISP/misp-modules,Rafiot/misp-modules,amuehlem/misp-modules,Rafiot/misp-modules,amuehlem/misp-modules,VirusTotal/misp-modules,VirusTotal/misp-modules,MISP/misp-modules,amuehlem/misp-modules,VirusTotal/misp-modules,MISP/misp-modules
python
## Code Before: from . import _vmray __all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl', 'countrycode', 'cve', 'dns', 'eupi', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal', 'whois', 'shodan', 'reversedns', 'wiki'] ## Instruction: Add domaintools to the import list ## Code After: from . import _vmray __all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl', 'countrycode', 'cve', 'dns', 'domaintools', 'eupi', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
... from . import _vmray __all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl', 'countrycode', 'cve', 'dns', 'domaintools', 'eupi', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal', 'whois', 'shodan', 'reversedns', 'wiki'] ...
3de1b3c8538a473c29189ef4df02f93e67e221ac
migrations/versions/420_dos_is_coming.py
migrations/versions/420_dos_is_coming.py
# revision identifiers, used by Alembic. revision = '420' down_revision = '410_remove_empty_drafts' from alembic import op import sqlalchemy as sa from app.models import Framework def upgrade(): op.execute("COMMIT") op.execute("ALTER TYPE framework_enum ADD VALUE IF NOT EXISTS 'dos' after 'gcloud'") framework = Framework.query.filter(Framework.slug == 'digital-outcomes-and-specialists').first() if not framework: op.execute(""" INSERT INTO frameworks (name, framework, status, slug) values('Digital Outcomes and Specialists', 'dos', 'coming', 'digital-outcomes-and-specialists') """) def downgrade(): op.execute(""" DELETE FROM frameworks where slug='digital-outcomes-and-specialists' """)
# revision identifiers, used by Alembic. revision = '420' down_revision = '410_remove_empty_drafts' from alembic import op def upgrade(): op.execute("COMMIT") op.execute("ALTER TYPE framework_enum ADD VALUE IF NOT EXISTS 'dos' after 'gcloud'") conn = op.get_bind() res = conn.execute("SELECT * FROM frameworks WHERE slug = 'digital-outcomes-and-specialists'") results = res.fetchall() if not results: op.execute(""" INSERT INTO frameworks (name, framework, status, slug) values('Digital Outcomes and Specialists', 'dos', 'coming', 'digital-outcomes-and-specialists') """) def downgrade(): op.execute(""" DELETE FROM frameworks where slug='digital-outcomes-and-specialists' """)
Use `op` instead of `app` so that `list_migrations` still works
Use `op` instead of `app` so that `list_migrations` still works By importing `app` the `list_migrations.py` script broke because it doesn't have the `app` context.
Python
mit
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
python
## Code Before: # revision identifiers, used by Alembic. revision = '420' down_revision = '410_remove_empty_drafts' from alembic import op import sqlalchemy as sa from app.models import Framework def upgrade(): op.execute("COMMIT") op.execute("ALTER TYPE framework_enum ADD VALUE IF NOT EXISTS 'dos' after 'gcloud'") framework = Framework.query.filter(Framework.slug == 'digital-outcomes-and-specialists').first() if not framework: op.execute(""" INSERT INTO frameworks (name, framework, status, slug) values('Digital Outcomes and Specialists', 'dos', 'coming', 'digital-outcomes-and-specialists') """) def downgrade(): op.execute(""" DELETE FROM frameworks where slug='digital-outcomes-and-specialists' """) ## Instruction: Use `op` instead of `app` so that `list_migrations` still works By importing `app` the `list_migrations.py` script broke because it doesn't have the `app` context. ## Code After: # revision identifiers, used by Alembic. revision = '420' down_revision = '410_remove_empty_drafts' from alembic import op def upgrade(): op.execute("COMMIT") op.execute("ALTER TYPE framework_enum ADD VALUE IF NOT EXISTS 'dos' after 'gcloud'") conn = op.get_bind() res = conn.execute("SELECT * FROM frameworks WHERE slug = 'digital-outcomes-and-specialists'") results = res.fetchall() if not results: op.execute(""" INSERT INTO frameworks (name, framework, status, slug) values('Digital Outcomes and Specialists', 'dos', 'coming', 'digital-outcomes-and-specialists') """) def downgrade(): op.execute(""" DELETE FROM frameworks where slug='digital-outcomes-and-specialists' """)
// ... existing code ... down_revision = '410_remove_empty_drafts' from alembic import op def upgrade(): // ... modified code ... op.execute("COMMIT") op.execute("ALTER TYPE framework_enum ADD VALUE IF NOT EXISTS 'dos' after 'gcloud'") conn = op.get_bind() res = conn.execute("SELECT * FROM frameworks WHERE slug = 'digital-outcomes-and-specialists'") results = res.fetchall() if not results: op.execute(""" INSERT INTO frameworks (name, framework, status, slug) values('Digital Outcomes and Specialists', 'dos', 'coming', 'digital-outcomes-and-specialists') // ... rest of the code ...
ea48d59c4e4073de940b394d2bc99e411cfbd3fb
example_of_usage.py
example_of_usage.py
import urllib.request from pprint import pprint from html_table_parser import HTMLTableParser def url_get_contents(url): """ Opens a website and read its binary contents (HTTP Response Body) """ req = urllib.request.Request(url=url) f = urllib.request.urlopen(req) return f.read() def main(): url = 'http://www.twitter.com' xhtml = url_get_contents(url).decode('utf-8') p = HTMLTableParser() p.feed(xhtml) pprint(p.tables) if __name__ == '__main__': main()
import urllib.request from pprint import pprint from html_table_parser import HTMLTableParser def url_get_contents(url): """ Opens a website and read its binary contents (HTTP Response Body) """ req = urllib.request.Request(url=url) f = urllib.request.urlopen(req) return f.read() def main(): url = 'https://w3schools.com/html/html_tables.asp' xhtml = url_get_contents(url).decode('utf-8') p = HTMLTableParser() p.feed(xhtml) # Get all tables pprint(p.tables) # Get tables with id attribute pprint(p.named_tables) if __name__ == '__main__': main()
Add named tables to the examples
Add named tables to the examples
Python
agpl-3.0
schmijos/html-table-parser-python3,schmijos/html-table-parser-python3
python
## Code Before: import urllib.request from pprint import pprint from html_table_parser import HTMLTableParser def url_get_contents(url): """ Opens a website and read its binary contents (HTTP Response Body) """ req = urllib.request.Request(url=url) f = urllib.request.urlopen(req) return f.read() def main(): url = 'http://www.twitter.com' xhtml = url_get_contents(url).decode('utf-8') p = HTMLTableParser() p.feed(xhtml) pprint(p.tables) if __name__ == '__main__': main() ## Instruction: Add named tables to the examples ## Code After: import urllib.request from pprint import pprint from html_table_parser import HTMLTableParser def url_get_contents(url): """ Opens a website and read its binary contents (HTTP Response Body) """ req = urllib.request.Request(url=url) f = urllib.request.urlopen(req) return f.read() def main(): url = 'https://w3schools.com/html/html_tables.asp' xhtml = url_get_contents(url).decode('utf-8') p = HTMLTableParser() p.feed(xhtml) # Get all tables pprint(p.tables) # Get tables with id attribute pprint(p.named_tables) if __name__ == '__main__': main()
... def main(): url = 'https://w3schools.com/html/html_tables.asp' xhtml = url_get_contents(url).decode('utf-8') p = HTMLTableParser() p.feed(xhtml) # Get all tables pprint(p.tables) # Get tables with id attribute pprint(p.named_tables) if __name__ == '__main__': ...
e6b24f6e8bfca6f8e22bd63c893a228cc2a694f1
starter_project/normalize_breton_test.py
starter_project/normalize_breton_test.py
import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') if __name__ == '__main__': unittest.main()
import unittest import normalize_breton_lib class TestStringMethods(unittest.TestCase): def test_normalize_breton(self): 'Test the output of NormalizeBreton.' test_cases = [(('a--bc', 'a-bc'), ('ccb--a', 'ccb-a'), ('ba--aa', 'ba-aa'))] for test in test_cases: for test_case, expected in test: test_fst = normalize_breton_lib.NormalizeBreton(test_case) self.assertEqual(test_fst, expected) if __name__ == '__main__': unittest.main()
Add basic test for example Pynini FST.
Add basic test for example Pynini FST.
Python
apache-2.0
googleinterns/text-norm-for-low-resource-languages,googleinterns/text-norm-for-low-resource-languages
python
## Code Before: import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') if __name__ == '__main__': unittest.main() ## Instruction: Add basic test for example Pynini FST. ## Code After: import unittest import normalize_breton_lib class TestStringMethods(unittest.TestCase): def test_normalize_breton(self): 'Test the output of NormalizeBreton.' test_cases = [(('a--bc', 'a-bc'), ('ccb--a', 'ccb-a'), ('ba--aa', 'ba-aa'))] for test in test_cases: for test_case, expected in test: test_fst = normalize_breton_lib.NormalizeBreton(test_case) self.assertEqual(test_fst, expected) if __name__ == '__main__': unittest.main()
# ... existing code ... import unittest import normalize_breton_lib class TestStringMethods(unittest.TestCase): def test_normalize_breton(self): 'Test the output of NormalizeBreton.' test_cases = [(('a--bc', 'a-bc'), ('ccb--a', 'ccb-a'), ('ba--aa', 'ba-aa'))] for test in test_cases: for test_case, expected in test: test_fst = normalize_breton_lib.NormalizeBreton(test_case) self.assertEqual(test_fst, expected) if __name__ == '__main__': unittest.main() # ... rest of the code ...
476b66510cd7b84233ad02ccfcde3ecd33604c57
simple_es/event/domain_event.py
simple_es/event/domain_event.py
from simple_es.identifier.identifies import Identifies class DomainEvent(): """ Base class for all domain driven events """ identifier = None def __init__(self, identifier=None): if not isinstance(identifier, Identifies): raise TypeError('Event identifier must be an instance of the Identifies class', identifier) self.identifier = identifier
from simple_es.identifier.identifies import Identifies class DomainEvent(): """ Base class for all domain driven events """ identifier = None _recorded = False def __init__(self, identifier=None): if not isinstance(identifier, Identifies): raise TypeError('Event identifier must be an instance of the Identifies class', identifier) self.identifier = identifier
Add a _recorded bool to events
Add a _recorded bool to events
Python
apache-2.0
OnShift/simple-es
python
## Code Before: from simple_es.identifier.identifies import Identifies class DomainEvent(): """ Base class for all domain driven events """ identifier = None def __init__(self, identifier=None): if not isinstance(identifier, Identifies): raise TypeError('Event identifier must be an instance of the Identifies class', identifier) self.identifier = identifier ## Instruction: Add a _recorded bool to events ## Code After: from simple_es.identifier.identifies import Identifies class DomainEvent(): """ Base class for all domain driven events """ identifier = None _recorded = False def __init__(self, identifier=None): if not isinstance(identifier, Identifies): raise TypeError('Event identifier must be an instance of the Identifies class', identifier) self.identifier = identifier
// ... existing code ... Base class for all domain driven events """ identifier = None _recorded = False def __init__(self, identifier=None): if not isinstance(identifier, Identifies): // ... rest of the code ...
e8422ac65a4557257d9697b8dfcb538a02e5f6f0
pixelated/common/__init__.py
pixelated/common/__init__.py
import ssl import logging from logging.handlers import SysLogHandler from threading import Timer logger = logging.getLogger('pixelated.startup') def init_logging(name, level=logging.INFO, config_file=None): global logger logger_name = 'pixelated.%s' % name logging.basicConfig(level=level) if config_file: logging.config.fileConfig(config_file) else: formatter = logging.Formatter('%(asctime)s %(name)s: %(levelname)s %(message)s', '%b %e %H:%M:%S') syslog = SysLogHandler(address='/dev/log', facility=SysLogHandler.LOG_DAEMON) syslog.setFormatter(formatter) logger.addHandler(syslog) logger.name = logger_name logger.info('Initialized logging') def latest_available_ssl_version(): return ssl.PROTOCOL_TLSv1 class Watchdog: def __init__(self, timeout, userHandler=None, args=[]): self.timeout = timeout self.handler = userHandler if userHandler is not None else self.defaultHandler self.timer = Timer(self.timeout, self.handler, args=args) self.timer.daemon = True self.timer.start() def reset(self): self.timer.cancel() self.timer = Timer(self.timeout, self.handler) def stop(self): self.timer.cancel() def defaultHandler(self): raise self
import ssl import logging from logging.handlers import SysLogHandler from threading import Timer logger = logging.getLogger('pixelated.startup') def init_logging(name, level=logging.INFO, config_file=None): global logger logger_name = 'pixelated.%s' % name logging.basicConfig(level=level) if config_file: logging.config.fileConfig(config_file) else: formatter = logging.Formatter('%(asctime)s %(name)s: %(levelname)s %(message)s', '%b %e %H:%M:%S') syslog = SysLogHandler(address='/dev/log', facility=SysLogHandler.LOG_DAEMON) syslog.setFormatter(formatter) logger.addHandler(syslog) logger.name = logger_name logger.info('Initialized logging') def latest_available_ssl_version(): try: return ssl.PROTOCOL_TLSv1_2 except AttributeError: return ssl.PROTOCOL_TLSv1 class Watchdog: def __init__(self, timeout, userHandler=None, args=[]): self.timeout = timeout self.handler = userHandler if userHandler is not None else self.defaultHandler self.timer = Timer(self.timeout, self.handler, args=args) self.timer.daemon = True self.timer.start() def reset(self): self.timer.cancel() self.timer = Timer(self.timeout, self.handler) def stop(self): self.timer.cancel() def defaultHandler(self): raise self
Revert "Downgraded SSL version to TLS 1 until we have the requests library fixed"
Revert "Downgraded SSL version to TLS 1 until we have the requests library fixed" - TLS1.2 does not work on older pythons (like on MacOSX) but it works as intended on current linux versions so enable it if possible This reverts commit 666630f2a01bdeb7becc3cd3b324c076eaf1567d. Conflicts: pixelated/common/__init__.py
Python
agpl-3.0
pixelated-project/pixelated-dispatcher,pixelated-project/pixelated-dispatcher,pixelated/pixelated-dispatcher,pixelated/pixelated-dispatcher,pixelated/pixelated-dispatcher,pixelated-project/pixelated-dispatcher
python
## Code Before: import ssl import logging from logging.handlers import SysLogHandler from threading import Timer logger = logging.getLogger('pixelated.startup') def init_logging(name, level=logging.INFO, config_file=None): global logger logger_name = 'pixelated.%s' % name logging.basicConfig(level=level) if config_file: logging.config.fileConfig(config_file) else: formatter = logging.Formatter('%(asctime)s %(name)s: %(levelname)s %(message)s', '%b %e %H:%M:%S') syslog = SysLogHandler(address='/dev/log', facility=SysLogHandler.LOG_DAEMON) syslog.setFormatter(formatter) logger.addHandler(syslog) logger.name = logger_name logger.info('Initialized logging') def latest_available_ssl_version(): return ssl.PROTOCOL_TLSv1 class Watchdog: def __init__(self, timeout, userHandler=None, args=[]): self.timeout = timeout self.handler = userHandler if userHandler is not None else self.defaultHandler self.timer = Timer(self.timeout, self.handler, args=args) self.timer.daemon = True self.timer.start() def reset(self): self.timer.cancel() self.timer = Timer(self.timeout, self.handler) def stop(self): self.timer.cancel() def defaultHandler(self): raise self ## Instruction: Revert "Downgraded SSL version to TLS 1 until we have the requests library fixed" - TLS1.2 does not work on older pythons (like on MacOSX) but it works as intended on current linux versions so enable it if possible This reverts commit 666630f2a01bdeb7becc3cd3b324c076eaf1567d. Conflicts: pixelated/common/__init__.py ## Code After: import ssl import logging from logging.handlers import SysLogHandler from threading import Timer logger = logging.getLogger('pixelated.startup') def init_logging(name, level=logging.INFO, config_file=None): global logger logger_name = 'pixelated.%s' % name logging.basicConfig(level=level) if config_file: logging.config.fileConfig(config_file) else: formatter = logging.Formatter('%(asctime)s %(name)s: %(levelname)s %(message)s', '%b %e %H:%M:%S') syslog = SysLogHandler(address='/dev/log', facility=SysLogHandler.LOG_DAEMON) syslog.setFormatter(formatter) logger.addHandler(syslog) logger.name = logger_name logger.info('Initialized logging') def latest_available_ssl_version(): try: return ssl.PROTOCOL_TLSv1_2 except AttributeError: return ssl.PROTOCOL_TLSv1 class Watchdog: def __init__(self, timeout, userHandler=None, args=[]): self.timeout = timeout self.handler = userHandler if userHandler is not None else self.defaultHandler self.timer = Timer(self.timeout, self.handler, args=args) self.timer.daemon = True self.timer.start() def reset(self): self.timer.cancel() self.timer = Timer(self.timeout, self.handler) def stop(self): self.timer.cancel() def defaultHandler(self): raise self
// ... existing code ... def latest_available_ssl_version(): try: return ssl.PROTOCOL_TLSv1_2 except AttributeError: return ssl.PROTOCOL_TLSv1 class Watchdog: // ... rest of the code ...
c0c59a9c5d3aa2d7ed50e8e895f1a3e02a4ae380
Basic-Number-Guessing-Game-Challenge.py
Basic-Number-Guessing-Game-Challenge.py
import random attempts = 1 number = str(random.randint(1, 100)) while True: print number if raw_input("Guess (1 - 100): ") == number: print "Correct!" print "It Only Took You", attempts, "Attempts!" if attempts > 1 else "Attempt!" break else: print "Incorrect, Guess Again!" attempts += 1
import random attempts = 1 number = random.randint(1, 100) while True: guess = raw_input("Guess (1 - 100): ") if guess.isdigit(): guess = int(guess) if 1 <= guess and guess <= 100: if guess == number: print "Correct!" print "It Only Took You", attempts, "Attempts!" if attempts > 1 else "Attempt!" break elif guess > number: print "That Guess Is Too High!" elif guess < number: print "That Guess Is Too Low!" else: print "Guesses Must Be Between 1 And 100!" else: print "That's Not A Number!" attempts += 1
Verify that the guess is a number, that it is between 1 and 100, and tells the user if the guessed number is too high or low.
Verify that the guess is a number, that it is between 1 and 100, and tells the user if the guessed number is too high or low.
Python
mit
RascalTwo/Basic-Number-Guessing-Game-Challenge
python
## Code Before: import random attempts = 1 number = str(random.randint(1, 100)) while True: print number if raw_input("Guess (1 - 100): ") == number: print "Correct!" print "It Only Took You", attempts, "Attempts!" if attempts > 1 else "Attempt!" break else: print "Incorrect, Guess Again!" attempts += 1 ## Instruction: Verify that the guess is a number, that it is between 1 and 100, and tells the user if the guessed number is too high or low. ## Code After: import random attempts = 1 number = random.randint(1, 100) while True: guess = raw_input("Guess (1 - 100): ") if guess.isdigit(): guess = int(guess) if 1 <= guess and guess <= 100: if guess == number: print "Correct!" print "It Only Took You", attempts, "Attempts!" if attempts > 1 else "Attempt!" break elif guess > number: print "That Guess Is Too High!" elif guess < number: print "That Guess Is Too Low!" else: print "Guesses Must Be Between 1 And 100!" else: print "That's Not A Number!" attempts += 1
// ... existing code ... import random attempts = 1 number = random.randint(1, 100) while True: guess = raw_input("Guess (1 - 100): ") if guess.isdigit(): guess = int(guess) if 1 <= guess and guess <= 100: if guess == number: print "Correct!" print "It Only Took You", attempts, "Attempts!" if attempts > 1 else "Attempt!" break elif guess > number: print "That Guess Is Too High!" elif guess < number: print "That Guess Is Too Low!" else: print "Guesses Must Be Between 1 And 100!" else: print "That's Not A Number!" attempts += 1 // ... rest of the code ...
0ab7d60f02abe3bd4509c3377ebc6cb11f0a5e0f
ydf/templating.py
ydf/templating.py
import jinja2 import os from ydf import instructions, __version__ DEFAULT_TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates') def render_vars(yaml_vars): """ Build a dict containing all variables accessible to a template during the rendering process. This is a merge of the YAML variables parsed from the file + build variables defined by :mod:`~ydf` itself. :param yaml_vars: Parsed from the parsed YAML file. :return: Dict of all variables available to template. """ return dict(ydf=dict(version=__version__), **yaml_vars) def environ(path=DEFAULT_TEMPLATE_PATH, **kwargs): """ Build a Jinja2 environment for the given template directory path and options. :param path: Path to search for Jinja2 template files :param kwargs: Options to configure the environment :return: :class:`~jinja2.Environment` instance """ kwargs.setdefault('trim_blocks', True) kwargs.setdefault('lstrip_blocks', True) env = jinja2.Environment(loader=jinja2.FileSystemLoader(path), **kwargs) env.globals[instructions.convert_instruction.__name__] = instructions.convert_instruction return env
import jinja2 import os from ydf import instructions, __version__ DEFAULT_TEMPLATE_NAME = 'default.tpl' DEFAULT_TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates') def render_vars(yaml_vars): """ Build a dict containing all variables accessible to a template during the rendering process. This is a merge of the YAML variables parsed from the file + build variables defined by :mod:`~ydf` itself. :param yaml_vars: Parsed from the parsed YAML file. :return: Dict of all variables available to template. """ return dict(ydf=dict(version=__version__), **yaml_vars) def environ(path=DEFAULT_TEMPLATE_PATH, **kwargs): """ Build a Jinja2 environment for the given template directory path and options. :param path: Path to search for Jinja2 template files :param kwargs: Options to configure the environment :return: :class:`~jinja2.Environment` instance """ kwargs.setdefault('trim_blocks', True) kwargs.setdefault('lstrip_blocks', True) env = jinja2.Environment(loader=jinja2.FileSystemLoader(path), **kwargs) env.globals[instructions.convert_instruction.__name__] = instructions.convert_instruction return env
Add global for default template name.
Add global for default template name.
Python
apache-2.0
ahawker/ydf
python
## Code Before: import jinja2 import os from ydf import instructions, __version__ DEFAULT_TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates') def render_vars(yaml_vars): """ Build a dict containing all variables accessible to a template during the rendering process. This is a merge of the YAML variables parsed from the file + build variables defined by :mod:`~ydf` itself. :param yaml_vars: Parsed from the parsed YAML file. :return: Dict of all variables available to template. """ return dict(ydf=dict(version=__version__), **yaml_vars) def environ(path=DEFAULT_TEMPLATE_PATH, **kwargs): """ Build a Jinja2 environment for the given template directory path and options. :param path: Path to search for Jinja2 template files :param kwargs: Options to configure the environment :return: :class:`~jinja2.Environment` instance """ kwargs.setdefault('trim_blocks', True) kwargs.setdefault('lstrip_blocks', True) env = jinja2.Environment(loader=jinja2.FileSystemLoader(path), **kwargs) env.globals[instructions.convert_instruction.__name__] = instructions.convert_instruction return env ## Instruction: Add global for default template name. ## Code After: import jinja2 import os from ydf import instructions, __version__ DEFAULT_TEMPLATE_NAME = 'default.tpl' DEFAULT_TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates') def render_vars(yaml_vars): """ Build a dict containing all variables accessible to a template during the rendering process. This is a merge of the YAML variables parsed from the file + build variables defined by :mod:`~ydf` itself. :param yaml_vars: Parsed from the parsed YAML file. :return: Dict of all variables available to template. """ return dict(ydf=dict(version=__version__), **yaml_vars) def environ(path=DEFAULT_TEMPLATE_PATH, **kwargs): """ Build a Jinja2 environment for the given template directory path and options. :param path: Path to search for Jinja2 template files :param kwargs: Options to configure the environment :return: :class:`~jinja2.Environment` instance """ kwargs.setdefault('trim_blocks', True) kwargs.setdefault('lstrip_blocks', True) env = jinja2.Environment(loader=jinja2.FileSystemLoader(path), **kwargs) env.globals[instructions.convert_instruction.__name__] = instructions.convert_instruction return env
// ... existing code ... from ydf import instructions, __version__ DEFAULT_TEMPLATE_NAME = 'default.tpl' DEFAULT_TEMPLATE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'templates') // ... rest of the code ...
bc0022c32ef912eba9cc3d9683c1649443d6aa35
pyfibot/modules/module_btc.py
pyfibot/modules/module_btc.py
from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox. Usage: btc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") rates = [] for currency in currencies: rate = gen_string(bot, currency) if rate: rates.append(rate) if rates: return bot.say(channel, "1 BTC = %s" % " | ".join(rates)) def gen_string(bot, currency): r = bot.get_url("http://data.mtgox.com/api/1/BTC%s/ticker" % currency) if r.json()['result'] != 'success': return None data = r.json()['return'] avg = data['avg']['display_short'] low = data['low']['display_short'] high = data['high']['display_short'] vol = data['vol']['display_short'] return "%s avg:%s low:%s high:%s vol:%s" % (currency.upper(), avg, low, high, vol)
from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox. Usage: btc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") return bot.say(channel, get_coin_value(bot, "BTC", currencies)) def command_ltc(bot, user, channel, args): """Display current LTC exchange rates from mtgox. Usage: ltc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") return bot.say(channel, get_coin_value(bot, "LTC", currencies)) def get_coin_value(bot, coin, currencies): rates = [] for currency in currencies: rate = gen_string(bot, coin, currency) if rate: rates.append(rate) if rates: return "1 %s = %s" % (coin, " | ".join(rates)) else: return None def gen_string(bot, coin="BTC", currency="EUR"): r = bot.get_url("http://data.mtgox.com/api/1/%s%s/ticker" % (coin, currency)) if r.json()['result'] != 'success': return None data = r.json()['return'] avg = data['avg']['display_short'] low = data['low']['display_short'] high = data['high']['display_short'] vol = data['vol']['display_short'] return "%s avg:%s low:%s high:%s vol:%s" % (currency.upper(), avg, low, high, vol)
Add support for LTC in mtgox
Add support for LTC in mtgox
Python
bsd-3-clause
rnyberg/pyfibot,EArmour/pyfibot,EArmour/pyfibot,aapa/pyfibot,lepinkainen/pyfibot,huqa/pyfibot,rnyberg/pyfibot,huqa/pyfibot,aapa/pyfibot,lepinkainen/pyfibot
python
## Code Before: from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox. Usage: btc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") rates = [] for currency in currencies: rate = gen_string(bot, currency) if rate: rates.append(rate) if rates: return bot.say(channel, "1 BTC = %s" % " | ".join(rates)) def gen_string(bot, currency): r = bot.get_url("http://data.mtgox.com/api/1/BTC%s/ticker" % currency) if r.json()['result'] != 'success': return None data = r.json()['return'] avg = data['avg']['display_short'] low = data['low']['display_short'] high = data['high']['display_short'] vol = data['vol']['display_short'] return "%s avg:%s low:%s high:%s vol:%s" % (currency.upper(), avg, low, high, vol) ## Instruction: Add support for LTC in mtgox ## Code After: from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox. Usage: btc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") return bot.say(channel, get_coin_value(bot, "BTC", currencies)) def command_ltc(bot, user, channel, args): """Display current LTC exchange rates from mtgox. Usage: ltc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") return bot.say(channel, get_coin_value(bot, "LTC", currencies)) def get_coin_value(bot, coin, currencies): rates = [] for currency in currencies: rate = gen_string(bot, coin, currency) if rate: rates.append(rate) if rates: return "1 %s = %s" % (coin, " | ".join(rates)) else: return None def gen_string(bot, coin="BTC", currency="EUR"): r = bot.get_url("http://data.mtgox.com/api/1/%s%s/ticker" % (coin, currency)) if r.json()['result'] != 'success': return None data = r.json()['return'] avg = data['avg']['display_short'] low = data['low']['display_short'] high = data['high']['display_short'] vol = data['vol']['display_short'] return "%s avg:%s low:%s high:%s vol:%s" % (currency.upper(), avg, low, high, vol)
... if args: currencies = args.split(" ") return bot.say(channel, get_coin_value(bot, "BTC", currencies)) def command_ltc(bot, user, channel, args): """Display current LTC exchange rates from mtgox. Usage: ltc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.split(" ") return bot.say(channel, get_coin_value(bot, "LTC", currencies)) def get_coin_value(bot, coin, currencies): rates = [] for currency in currencies: rate = gen_string(bot, coin, currency) if rate: rates.append(rate) if rates: return "1 %s = %s" % (coin, " | ".join(rates)) else: return None def gen_string(bot, coin="BTC", currency="EUR"): r = bot.get_url("http://data.mtgox.com/api/1/%s%s/ticker" % (coin, currency)) if r.json()['result'] != 'success': return None ...
06d648d44c685677144988211e35c3d822fd6e57
app/src/main/java/edu/rutgers/css/Rutgers/fragments/MainScreen.java
app/src/main/java/edu/rutgers/css/Rutgers/fragments/MainScreen.java
package edu.rutgers.css.Rutgers.fragments; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import edu.rutgers.css.Rutgers2.R; public class MainScreen extends Fragment { public MainScreen() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_main_screen, container, false); getActivity().setTitle(R.string.app_name); int bgResource; if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) bgResource = R.drawable.bgland; else bgResource = R.drawable.bgportrait; Bitmap bg = BitmapFactory.decodeResource(getResources(), bgResource, new BitmapFactory.Options()); Drawable bgDraw = new BitmapDrawable(bg); v.setBackground(bgDraw); return v; } }
package edu.rutgers.css.Rutgers.fragments; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import edu.rutgers.css.Rutgers2.R; public class MainScreen extends Fragment { public MainScreen() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_main_screen, container, false); getActivity().setTitle(R.string.app_name); int bgResource; if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) bgResource = R.drawable.bgland; else bgResource = R.drawable.bgportrait; Bitmap bg = BitmapFactory.decodeResource(getResources(), bgResource, new BitmapFactory.Options()); Drawable bgDraw = new BitmapDrawable(bg); if(android.os.Build.VERSION.SDK_INT >= 16) { v.setBackground(bgDraw); } else { v.setBackgroundDrawable(bgDraw); } return v; } }
Choose set background method by API
Choose set background method by API
Java
bsd-3-clause
rutgersmobile/android-client,rutgersmobile/android-client
java
## Code Before: package edu.rutgers.css.Rutgers.fragments; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import edu.rutgers.css.Rutgers2.R; public class MainScreen extends Fragment { public MainScreen() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_main_screen, container, false); getActivity().setTitle(R.string.app_name); int bgResource; if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) bgResource = R.drawable.bgland; else bgResource = R.drawable.bgportrait; Bitmap bg = BitmapFactory.decodeResource(getResources(), bgResource, new BitmapFactory.Options()); Drawable bgDraw = new BitmapDrawable(bg); v.setBackground(bgDraw); return v; } } ## Instruction: Choose set background method by API ## Code After: package edu.rutgers.css.Rutgers.fragments; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import edu.rutgers.css.Rutgers2.R; public class MainScreen extends Fragment { public MainScreen() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_main_screen, container, false); getActivity().setTitle(R.string.app_name); int bgResource; if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) bgResource = R.drawable.bgland; else bgResource = R.drawable.bgportrait; Bitmap bg = BitmapFactory.decodeResource(getResources(), bgResource, new BitmapFactory.Options()); Drawable bgDraw = new BitmapDrawable(bg); if(android.os.Build.VERSION.SDK_INT >= 16) { v.setBackground(bgDraw); } else { v.setBackgroundDrawable(bgDraw); } return v; } }
... else bgResource = R.drawable.bgportrait; Bitmap bg = BitmapFactory.decodeResource(getResources(), bgResource, new BitmapFactory.Options()); Drawable bgDraw = new BitmapDrawable(bg); if(android.os.Build.VERSION.SDK_INT >= 16) { v.setBackground(bgDraw); } else { v.setBackgroundDrawable(bgDraw); } return v; } } ...
020c13f3b39d495d50704317fe12ee4a4e735bb4
kylin/_injector.py
kylin/_injector.py
from functools import wraps from typing import Callable from ._scope import Scope class Injector(Callable): """ class decorator to inject dependencies into a callable decorated function """ def __init__(self, dependencies: dict, fun: Callable): self.dependencies = dependencies self.fun = fun @property def scope(self) -> Scope: return Scope() def __call__(self, *args, **kwargs): injections = {} for dependency_name, service_name in self.dependencies.items(): injections[dependency_name] = kwargs.get(dependency_name) or self.scope[service_name] kwargs.update(injections) return self.fun(*args, **kwargs) class Inject(Callable): """ class to recive the callable dependencies """ __injector__ = Injector def __init__(self, **dependencies): self.dependencies = dependencies def __call__(self, fun: Callable): return wraps(fun).__call__(self.__injector__(self.dependencies, fun))
from functools import wraps from typing import Callable from ._scope import Scope class Injector(Callable): """ class decorator to inject dependencies into a callable decorated function """ def __init__(self, dependencies: dict, fun: Callable): self.dependencies = dependencies self.fun = fun @property def scope(self) -> Scope: return Scope() def __call__(self, *args, **kwargs): injections = {} for dependency_name, service_name in self.dependencies.items(): injections[dependency_name] = kwargs.get(dependency_name) or self.scope[service_name] kwargs.update(injections) return self.fun(*args, **kwargs) class Inject(Callable): """ class to recive the callable dependencies """ __injector__ = Injector def __init__(self, **dependencies): self.dependencies = dependencies def __call__(self, fun: Callable): def call(*args, **kwargs): return self.__injector__(self.dependencies, fun).__call__(*args, **kwargs) return wraps(fun).__call__(call)
Fix bug of self injection into injector function
Fix bug of self injection into injector function
Python
mit
WatanukiRasadar/kylin
python
## Code Before: from functools import wraps from typing import Callable from ._scope import Scope class Injector(Callable): """ class decorator to inject dependencies into a callable decorated function """ def __init__(self, dependencies: dict, fun: Callable): self.dependencies = dependencies self.fun = fun @property def scope(self) -> Scope: return Scope() def __call__(self, *args, **kwargs): injections = {} for dependency_name, service_name in self.dependencies.items(): injections[dependency_name] = kwargs.get(dependency_name) or self.scope[service_name] kwargs.update(injections) return self.fun(*args, **kwargs) class Inject(Callable): """ class to recive the callable dependencies """ __injector__ = Injector def __init__(self, **dependencies): self.dependencies = dependencies def __call__(self, fun: Callable): return wraps(fun).__call__(self.__injector__(self.dependencies, fun)) ## Instruction: Fix bug of self injection into injector function ## Code After: from functools import wraps from typing import Callable from ._scope import Scope class Injector(Callable): """ class decorator to inject dependencies into a callable decorated function """ def __init__(self, dependencies: dict, fun: Callable): self.dependencies = dependencies self.fun = fun @property def scope(self) -> Scope: return Scope() def __call__(self, *args, **kwargs): injections = {} for dependency_name, service_name in self.dependencies.items(): injections[dependency_name] = kwargs.get(dependency_name) or self.scope[service_name] kwargs.update(injections) return self.fun(*args, **kwargs) class Inject(Callable): """ class to recive the callable dependencies """ __injector__ = Injector def __init__(self, **dependencies): self.dependencies = dependencies def __call__(self, fun: Callable): def call(*args, **kwargs): return self.__injector__(self.dependencies, fun).__call__(*args, **kwargs) return wraps(fun).__call__(call)
// ... existing code ... self.dependencies = dependencies def __call__(self, fun: Callable): def call(*args, **kwargs): return self.__injector__(self.dependencies, fun).__call__(*args, **kwargs) return wraps(fun).__call__(call) // ... rest of the code ...
3d48066c78d693b89cb2daabfd1ebe756862edc5
mopidy_gmusic/__init__.py
mopidy_gmusic/__init__.py
from __future__ import unicode_literals import os from mopidy import config, exceptions, ext __version__ = '0.2.2' class GMusicExtension(ext.Extension): dist_name = 'Mopidy-GMusic' ext_name = 'gmusic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(GMusicExtension, self).get_config_schema() schema['username'] = config.String() schema['password'] = config.Secret() schema['deviceid'] = config.String(optional=True) return schema def validate_environment(self): try: import gmusicapi # noqa except ImportError as e: raise exceptions.ExtensionError('gmusicapi library not found', e) pass def get_backend_classes(self): from .actor import GMusicBackend return [GMusicBackend]
from __future__ import unicode_literals import os from mopidy import config, ext __version__ = '0.2.2' class GMusicExtension(ext.Extension): dist_name = 'Mopidy-GMusic' ext_name = 'gmusic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(GMusicExtension, self).get_config_schema() schema['username'] = config.String() schema['password'] = config.Secret() schema['deviceid'] = config.String(optional=True) return schema def get_backend_classes(self): from .actor import GMusicBackend return [GMusicBackend]
Remove dependency check done by Mopidy
Remove dependency check done by Mopidy
Python
apache-2.0
hechtus/mopidy-gmusic,jaapz/mopidy-gmusic,Tilley/mopidy-gmusic,elrosti/mopidy-gmusic,jodal/mopidy-gmusic,jaibot/mopidy-gmusic,mopidy/mopidy-gmusic
python
## Code Before: from __future__ import unicode_literals import os from mopidy import config, exceptions, ext __version__ = '0.2.2' class GMusicExtension(ext.Extension): dist_name = 'Mopidy-GMusic' ext_name = 'gmusic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(GMusicExtension, self).get_config_schema() schema['username'] = config.String() schema['password'] = config.Secret() schema['deviceid'] = config.String(optional=True) return schema def validate_environment(self): try: import gmusicapi # noqa except ImportError as e: raise exceptions.ExtensionError('gmusicapi library not found', e) pass def get_backend_classes(self): from .actor import GMusicBackend return [GMusicBackend] ## Instruction: Remove dependency check done by Mopidy ## Code After: from __future__ import unicode_literals import os from mopidy import config, ext __version__ = '0.2.2' class GMusicExtension(ext.Extension): dist_name = 'Mopidy-GMusic' ext_name = 'gmusic' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(GMusicExtension, self).get_config_schema() schema['username'] = config.String() schema['password'] = config.Secret() schema['deviceid'] = config.String(optional=True) return schema def get_backend_classes(self): from .actor import GMusicBackend return [GMusicBackend]
# ... existing code ... import os from mopidy import config, ext __version__ = '0.2.2' # ... modified code ... schema['deviceid'] = config.String(optional=True) return schema def get_backend_classes(self): from .actor import GMusicBackend return [GMusicBackend] # ... rest of the code ...
0ea263fa9a496d8dbd8ff3f966cc23eba170842c
django_mfa/models.py
django_mfa/models.py
from django.db import models from django.conf import settings class UserOTP(models.Model): OTP_TYPES = ( ('HOTP', 'hotp'), ('TOTP', 'totp'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL) otp_type = models.CharField(max_length=20, choices=OTP_TYPES) secret_key = models.CharField(max_length=100, blank=True) def is_mfa_enabled(user): try: user_otp = user.userotp return True except: return False
from django.conf import settings from django.db import models class UserOTP(models.Model): OTP_TYPES = ( ('HOTP', 'hotp'), ('TOTP', 'totp'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL) otp_type = models.CharField(max_length=20, choices=OTP_TYPES) secret_key = models.CharField(max_length=100, blank=True) def is_mfa_enabled(user): """ Determine if a user has MFA enabled """ return hasattr(user, 'userotp')
Remove try/except from determing if mfa is enabled
Remove try/except from determing if mfa is enabled
Python
mit
MicroPyramid/django-mfa,MicroPyramid/django-mfa,MicroPyramid/django-mfa
python
## Code Before: from django.db import models from django.conf import settings class UserOTP(models.Model): OTP_TYPES = ( ('HOTP', 'hotp'), ('TOTP', 'totp'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL) otp_type = models.CharField(max_length=20, choices=OTP_TYPES) secret_key = models.CharField(max_length=100, blank=True) def is_mfa_enabled(user): try: user_otp = user.userotp return True except: return False ## Instruction: Remove try/except from determing if mfa is enabled ## Code After: from django.conf import settings from django.db import models class UserOTP(models.Model): OTP_TYPES = ( ('HOTP', 'hotp'), ('TOTP', 'totp'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL) otp_type = models.CharField(max_length=20, choices=OTP_TYPES) secret_key = models.CharField(max_length=100, blank=True) def is_mfa_enabled(user): """ Determine if a user has MFA enabled """ return hasattr(user, 'userotp')
# ... existing code ... from django.conf import settings from django.db import models class UserOTP(models.Model): OTP_TYPES = ( ('HOTP', 'hotp'), ('TOTP', 'totp'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL) # ... modified code ... def is_mfa_enabled(user): """ Determine if a user has MFA enabled """ return hasattr(user, 'userotp') # ... rest of the code ...
a1acbcfc41a3f55e58e0f240eedcdf6568de4850
test/contrib/test_securetransport.py
test/contrib/test_securetransport.py
import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import ( WrappedSocket, inject_into_urllib3, extract_from_urllib3 ) except ImportError as e: pytestmark = pytest.mark.skip('Could not import SecureTransport: %r' % e) from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1 # noqa: F401 from ..with_dummyserver.test_socketlevel import ( # noqa: F401 TestSNI, TestSocketClosing, TestClientCerts ) def setup_module(): inject_into_urllib3() def teardown_module(): extract_from_urllib3() def test_no_crash_with_empty_trust_bundle(): with contextlib.closing(socket.socket()) as s: ws = WrappedSocket(s) with pytest.raises(ssl.SSLError): ws._custom_validate(True, b"")
import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import WrappedSocket except ImportError: pass def setup_module(): try: from urllib3.contrib.securetransport import inject_into_urllib3 inject_into_urllib3() except ImportError as e: pytest.skip('Could not import SecureTransport: %r' % e) def teardown_module(): try: from urllib3.contrib.securetransport import extract_from_urllib3 extract_from_urllib3() except ImportError: pass from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1 # noqa: F401 from ..with_dummyserver.test_socketlevel import ( # noqa: F401 TestSNI, TestSocketClosing, TestClientCerts ) def test_no_crash_with_empty_trust_bundle(): with contextlib.closing(socket.socket()) as s: ws = WrappedSocket(s) with pytest.raises(ssl.SSLError): ws._custom_validate(True, b"")
Fix skip logic in SecureTransport tests
Fix skip logic in SecureTransport tests
Python
mit
urllib3/urllib3,urllib3/urllib3,sigmavirus24/urllib3,sigmavirus24/urllib3
python
## Code Before: import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import ( WrappedSocket, inject_into_urllib3, extract_from_urllib3 ) except ImportError as e: pytestmark = pytest.mark.skip('Could not import SecureTransport: %r' % e) from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1 # noqa: F401 from ..with_dummyserver.test_socketlevel import ( # noqa: F401 TestSNI, TestSocketClosing, TestClientCerts ) def setup_module(): inject_into_urllib3() def teardown_module(): extract_from_urllib3() def test_no_crash_with_empty_trust_bundle(): with contextlib.closing(socket.socket()) as s: ws = WrappedSocket(s) with pytest.raises(ssl.SSLError): ws._custom_validate(True, b"") ## Instruction: Fix skip logic in SecureTransport tests ## Code After: import contextlib import socket import ssl import pytest try: from urllib3.contrib.securetransport import WrappedSocket except ImportError: pass def setup_module(): try: from urllib3.contrib.securetransport import inject_into_urllib3 inject_into_urllib3() except ImportError as e: pytest.skip('Could not import SecureTransport: %r' % e) def teardown_module(): try: from urllib3.contrib.securetransport import extract_from_urllib3 extract_from_urllib3() except ImportError: pass from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1 # noqa: F401 from ..with_dummyserver.test_socketlevel import ( # noqa: F401 TestSNI, TestSocketClosing, TestClientCerts ) def test_no_crash_with_empty_trust_bundle(): with contextlib.closing(socket.socket()) as s: ws = WrappedSocket(s) with pytest.raises(ssl.SSLError): ws._custom_validate(True, b"")
... import pytest try: from urllib3.contrib.securetransport import WrappedSocket except ImportError: pass def setup_module(): try: from urllib3.contrib.securetransport import inject_into_urllib3 inject_into_urllib3() except ImportError as e: pytest.skip('Could not import SecureTransport: %r' % e) def teardown_module(): try: from urllib3.contrib.securetransport import extract_from_urllib3 extract_from_urllib3() except ImportError: pass from ..with_dummyserver.test_https import TestHTTPS, TestHTTPS_TLSv1 # noqa: F401 from ..with_dummyserver.test_socketlevel import ( # noqa: F401 ... ) def test_no_crash_with_empty_trust_bundle(): with contextlib.closing(socket.socket()) as s: ws = WrappedSocket(s) with pytest.raises(ssl.SSLError): ws._custom_validate(True, b"") ...
75638b6ab1dd7af0d56065529961b43d79668835
v2f-core/src/test/java/net/pdp7/v2f/core/RouterTest.java
v2f-core/src/test/java/net/pdp7/v2f/core/RouterTest.java
package net.pdp7.v2f.core; import junit.framework.TestCase; import net.pdp7.v2f.core.Router.ListTableRoute; public class RouterTest extends TestCase { public void testRouter() { ListTableRoute route = (ListTableRoute) new Router(null, null).findRoute("/table_name/"); assertEquals("table_name", route.table); } public void testDetailRoute() { assertFalse(new Router(null, null).getDetailRoute("table", "funky/id").contains("funky/id")); } }
package net.pdp7.v2f.core; import junit.framework.TestCase; import net.pdp7.v2f.core.Router.ListTableRoute; public class RouterTest extends TestCase { public void testRouter() { ListTableRoute route = (ListTableRoute) new Router(null, null, null).findRoute("/table_name/"); assertEquals("table_name", route.table); } public void testDetailRoute() { assertFalse(new Router(null, null, null).getDetailRoute("table", "funky/id").contains("funky/id")); } }
Fix broken build due to not running tests before committing :(
Fix broken build due to not running tests before committing :(
Java
apache-2.0
alexpdp7/v2f,alexpdp7/v2f,alexpdp7/v2f
java
## Code Before: package net.pdp7.v2f.core; import junit.framework.TestCase; import net.pdp7.v2f.core.Router.ListTableRoute; public class RouterTest extends TestCase { public void testRouter() { ListTableRoute route = (ListTableRoute) new Router(null, null).findRoute("/table_name/"); assertEquals("table_name", route.table); } public void testDetailRoute() { assertFalse(new Router(null, null).getDetailRoute("table", "funky/id").contains("funky/id")); } } ## Instruction: Fix broken build due to not running tests before committing :( ## Code After: package net.pdp7.v2f.core; import junit.framework.TestCase; import net.pdp7.v2f.core.Router.ListTableRoute; public class RouterTest extends TestCase { public void testRouter() { ListTableRoute route = (ListTableRoute) new Router(null, null, null).findRoute("/table_name/"); assertEquals("table_name", route.table); } public void testDetailRoute() { assertFalse(new Router(null, null, null).getDetailRoute("table", "funky/id").contains("funky/id")); } }
# ... existing code ... public class RouterTest extends TestCase { public void testRouter() { ListTableRoute route = (ListTableRoute) new Router(null, null, null).findRoute("/table_name/"); assertEquals("table_name", route.table); } public void testDetailRoute() { assertFalse(new Router(null, null, null).getDetailRoute("table", "funky/id").contains("funky/id")); } } # ... rest of the code ...
1a9fd1ee0be588aa465a2bc405a86bb4669e3288
src/whitgl/logging.c
src/whitgl/logging.c
char _buffer[LOG_BUFFER_MAX]; void whitgl_logit(const char *file, const int line, const char *str, ...) { va_list args; va_start(args, str); vsnprintf(_buffer, LOG_BUFFER_MAX, str, args); printf("%24s:%03d %s\n", file, line, _buffer); } void whitgl_panic(const char *file, const int line, const char *str, ...) { va_list args; va_start(args, str); vsnprintf(_buffer, LOG_BUFFER_MAX, str, args); printf("PANIC %24s:%03d %s\n", file, line, _buffer); __builtin_trap(); }
char _buffer[LOG_BUFFER_MAX]; void whitgl_logit(const char *file, const int line, const char *str, ...) { va_list args; va_start(args, str); vsnprintf(_buffer, LOG_BUFFER_MAX, str, args); printf("%24s:%03d %s\n", file, line, _buffer); } void whitgl_panic(const char *file, const int line, const char *str, ...) { va_list args; va_start(args, str); vsnprintf(_buffer, LOG_BUFFER_MAX, str, args); printf("PANIC %24s:%03d %s\n", file, line, _buffer); fflush(stdout); __builtin_trap(); }
Make sure stdout is flushed before trapping in panic
Make sure stdout is flushed before trapping in panic
C
mit
whitingjp/whitgl,whitingjp/whitgl,whitingjp/whitgl,whitingjp/whitgl
c
## Code Before: char _buffer[LOG_BUFFER_MAX]; void whitgl_logit(const char *file, const int line, const char *str, ...) { va_list args; va_start(args, str); vsnprintf(_buffer, LOG_BUFFER_MAX, str, args); printf("%24s:%03d %s\n", file, line, _buffer); } void whitgl_panic(const char *file, const int line, const char *str, ...) { va_list args; va_start(args, str); vsnprintf(_buffer, LOG_BUFFER_MAX, str, args); printf("PANIC %24s:%03d %s\n", file, line, _buffer); __builtin_trap(); } ## Instruction: Make sure stdout is flushed before trapping in panic ## Code After: char _buffer[LOG_BUFFER_MAX]; void whitgl_logit(const char *file, const int line, const char *str, ...) { va_list args; va_start(args, str); vsnprintf(_buffer, LOG_BUFFER_MAX, str, args); printf("%24s:%03d %s\n", file, line, _buffer); } void whitgl_panic(const char *file, const int line, const char *str, ...) { va_list args; va_start(args, str); vsnprintf(_buffer, LOG_BUFFER_MAX, str, args); printf("PANIC %24s:%03d %s\n", file, line, _buffer); fflush(stdout); __builtin_trap(); }
... va_start(args, str); vsnprintf(_buffer, LOG_BUFFER_MAX, str, args); printf("PANIC %24s:%03d %s\n", file, line, _buffer); fflush(stdout); __builtin_trap(); } ...
6db700685c0d46b52051bddbd79f481b22588a64
src/main/java/com/nelsonjrodrigues/pchud/net/Extractor.java
src/main/java/com/nelsonjrodrigues/pchud/net/Extractor.java
package com.nelsonjrodrigues.pchud.net; import static java.lang.Byte.toUnsignedInt; public class Extractor { private byte[] buffer; private int offset; private int length; public Extractor(byte[] buffer, int offset, int length) { this.buffer = buffer; this.offset = offset; this.length = length; } public int u8() { if (offset > length) { throw new ArrayIndexOutOfBoundsException(); } return toUnsignedInt(buffer[offset++]); } public int u16() { return u8() ^ u8() << 8; } public float f32() { return Float.intBitsToFloat(u8() ^ u8() << 8 ^ u8() << 16 ^ u8() << 24); } }
package com.nelsonjrodrigues.pchud.net; public class Extractor { private byte[] buffer; private int offset; private int length; public Extractor(byte[] buffer, int offset, int length) { this.buffer = buffer; this.offset = offset; this.length = length; } public int u8() { if (offset > length) { throw new ArrayIndexOutOfBoundsException(); } return Byte.toUnsignedInt(buffer[offset++]); } public int u16() { return u8() ^ u8() << 8; } public float f32() { return Float.intBitsToFloat(u8() ^ u8() << 8 ^ u8() << 16 ^ u8() << 24); } }
Remove static import, code is more readable like this
Remove static import, code is more readable like this
Java
mit
tuxetuxe/pchud,nrodrigues/pchud
java
## Code Before: package com.nelsonjrodrigues.pchud.net; import static java.lang.Byte.toUnsignedInt; public class Extractor { private byte[] buffer; private int offset; private int length; public Extractor(byte[] buffer, int offset, int length) { this.buffer = buffer; this.offset = offset; this.length = length; } public int u8() { if (offset > length) { throw new ArrayIndexOutOfBoundsException(); } return toUnsignedInt(buffer[offset++]); } public int u16() { return u8() ^ u8() << 8; } public float f32() { return Float.intBitsToFloat(u8() ^ u8() << 8 ^ u8() << 16 ^ u8() << 24); } } ## Instruction: Remove static import, code is more readable like this ## Code After: package com.nelsonjrodrigues.pchud.net; public class Extractor { private byte[] buffer; private int offset; private int length; public Extractor(byte[] buffer, int offset, int length) { this.buffer = buffer; this.offset = offset; this.length = length; } public int u8() { if (offset > length) { throw new ArrayIndexOutOfBoundsException(); } return Byte.toUnsignedInt(buffer[offset++]); } public int u16() { return u8() ^ u8() << 8; } public float f32() { return Float.intBitsToFloat(u8() ^ u8() << 8 ^ u8() << 16 ^ u8() << 24); } }
# ... existing code ... package com.nelsonjrodrigues.pchud.net; public class Extractor { # ... modified code ... if (offset > length) { throw new ArrayIndexOutOfBoundsException(); } return Byte.toUnsignedInt(buffer[offset++]); } public int u16() { # ... rest of the code ...
cb4c0cb2c35d97e0364a4c010715cdf15d261e4c
basehandler.py
basehandler.py
import os import jinja2 import webapp2 import utils JINJA_ENV = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), autoescape=True) class BaseHandler(webapp2.RequestHandler): def render(self, template, **kw): """Method render takes a template file and key-value pairs. It substitutes keys found in template with values in pairs. The resulted page is sent back to user.""" t = JINJA_ENV.get_template(template) self.response.write(t.render(kw)) def set_cookie(self, user): """Set user cookie in headers.""" cookie = utils.make_cookie(user) self.response.headers.add_header( 'Set-Cookie', 'user={}; Path=/'.format(cookie)) def logout(self): """Set user cookie to empty in headers.""" self.response.headers.add_header('Set-Cookie', 'user=;Path=/')
import os import jinja2 import webapp2 import utils JINJA_ENV = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), autoescape=True) class BaseHandler(webapp2.RequestHandler): def render(self, template, **kw): """Method render takes a template file and key-value pairs. It substitutes keys found in template with values in pairs. The resulted page is sent back to user.""" t = JINJA_ENV.get_template(template) self.response.write(t.render(kw)) def set_cookie(self, user): """Set user cookie in headers.""" cookie = utils.make_cookie(user) self.response.headers.add_header( 'Set-Cookie', 'user={}; Path=/'.format(cookie)) def logout(self): """Set user cookie to empty in headers.""" self.response.headers.add_header('Set-Cookie', 'user=;Path=/') def get_username(self): """Check if user has a valid cookie. Returns username if cookie is valid.""" cookie = self.request.cookies.get('user') if cookie and utils.valid_cookie(cookie): username = cookie.split('|')[0] return username
Add a method to get username if users have valid cookie
Add a method to get username if users have valid cookie
Python
mit
lttviet/udacity-final
python
## Code Before: import os import jinja2 import webapp2 import utils JINJA_ENV = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), autoescape=True) class BaseHandler(webapp2.RequestHandler): def render(self, template, **kw): """Method render takes a template file and key-value pairs. It substitutes keys found in template with values in pairs. The resulted page is sent back to user.""" t = JINJA_ENV.get_template(template) self.response.write(t.render(kw)) def set_cookie(self, user): """Set user cookie in headers.""" cookie = utils.make_cookie(user) self.response.headers.add_header( 'Set-Cookie', 'user={}; Path=/'.format(cookie)) def logout(self): """Set user cookie to empty in headers.""" self.response.headers.add_header('Set-Cookie', 'user=;Path=/') ## Instruction: Add a method to get username if users have valid cookie ## Code After: import os import jinja2 import webapp2 import utils JINJA_ENV = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), autoescape=True) class BaseHandler(webapp2.RequestHandler): def render(self, template, **kw): """Method render takes a template file and key-value pairs. It substitutes keys found in template with values in pairs. The resulted page is sent back to user.""" t = JINJA_ENV.get_template(template) self.response.write(t.render(kw)) def set_cookie(self, user): """Set user cookie in headers.""" cookie = utils.make_cookie(user) self.response.headers.add_header( 'Set-Cookie', 'user={}; Path=/'.format(cookie)) def logout(self): """Set user cookie to empty in headers.""" self.response.headers.add_header('Set-Cookie', 'user=;Path=/') def get_username(self): """Check if user has a valid cookie. Returns username if cookie is valid.""" cookie = self.request.cookies.get('user') if cookie and utils.valid_cookie(cookie): username = cookie.split('|')[0] return username
... """Set user cookie to empty in headers.""" self.response.headers.add_header('Set-Cookie', 'user=;Path=/') def get_username(self): """Check if user has a valid cookie. Returns username if cookie is valid.""" cookie = self.request.cookies.get('user') if cookie and utils.valid_cookie(cookie): username = cookie.split('|')[0] return username ...
61448043a039543c38c5ca7b9828792cfc8afbb8
justwatch/justwatchapi.py
justwatch/justwatchapi.py
import requests from babel import Locale class JustWatch: def __init__(self, country='AU', **kwargs): self.kwargs = kwargs self.country = country self.language = Locale.parse('und_{}'.format(self.country)).language def search_for_item(self, **kwargs): if kwargs: self.kwargs = kwargs null = None payload = { "content_types":null, "presentation_types":null, "providers":null, "genres":null, "languages":null, "release_year_from":null, "release_year_until":null, "monetization_types":null, "min_price":null, "max_price":null, "scoring_filter_types":null, "cinema_release":null, "query":null } for key, value in self.kwargs.items(): if key in payload.keys(): payload[key] = value else: print('{} is not a valid keyword'.format(key)) header = {'User-Agent':'JustWatch Python client (github.com/dawoudt/JustWatchAPI)'} api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country) r = requests.post(api_url, json=payload, headers=header) return r.json()
import requests from babel import Locale class JustWatch: def __init__(self, country='AU', **kwargs): self.kwargs = kwargs self.country = country self.language = Locale.parse('und_{}'.format(self.country)).language def search_for_item(self, **kwargs): if kwargs: self.kwargs = kwargs null = None payload = { "content_types":null, "presentation_types":null, "providers":null, "genres":null, "languages":null, "release_year_from":null, "release_year_until":null, "monetization_types":null, "min_price":null, "max_price":null, "scoring_filter_types":null, "cinema_release":null, "query":null } for key, value in self.kwargs.items(): if key in payload.keys(): payload[key] = value else: print('{} is not a valid keyword'.format(key)) header = {'User-Agent':'JustWatch Python client (github.com/dawoudt/JustWatchAPI)'} api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country) r = requests.post(api_url, json=payload, headers=header) # Client should deal with rate-limiting. JustWatch may send a 429 Too Many Requests response. r.raise_for_status() # Raises requests.exceptions.HTTPError if r.status_code != 200 return r.json()
Check and raise HTTP errors
Check and raise HTTP errors
Python
mit
dawoudt/JustWatchAPI
python
## Code Before: import requests from babel import Locale class JustWatch: def __init__(self, country='AU', **kwargs): self.kwargs = kwargs self.country = country self.language = Locale.parse('und_{}'.format(self.country)).language def search_for_item(self, **kwargs): if kwargs: self.kwargs = kwargs null = None payload = { "content_types":null, "presentation_types":null, "providers":null, "genres":null, "languages":null, "release_year_from":null, "release_year_until":null, "monetization_types":null, "min_price":null, "max_price":null, "scoring_filter_types":null, "cinema_release":null, "query":null } for key, value in self.kwargs.items(): if key in payload.keys(): payload[key] = value else: print('{} is not a valid keyword'.format(key)) header = {'User-Agent':'JustWatch Python client (github.com/dawoudt/JustWatchAPI)'} api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country) r = requests.post(api_url, json=payload, headers=header) return r.json() ## Instruction: Check and raise HTTP errors ## Code After: import requests from babel import Locale class JustWatch: def __init__(self, country='AU', **kwargs): self.kwargs = kwargs self.country = country self.language = Locale.parse('und_{}'.format(self.country)).language def search_for_item(self, **kwargs): if kwargs: self.kwargs = kwargs null = None payload = { "content_types":null, "presentation_types":null, "providers":null, "genres":null, "languages":null, "release_year_from":null, "release_year_until":null, "monetization_types":null, "min_price":null, "max_price":null, "scoring_filter_types":null, "cinema_release":null, "query":null } for key, value in self.kwargs.items(): if key in payload.keys(): payload[key] = value else: print('{} is not a valid keyword'.format(key)) header = {'User-Agent':'JustWatch Python client (github.com/dawoudt/JustWatchAPI)'} api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country) r = requests.post(api_url, json=payload, headers=header) # Client should deal with rate-limiting. JustWatch may send a 429 Too Many Requests response. r.raise_for_status() # Raises requests.exceptions.HTTPError if r.status_code != 200 return r.json()
... header = {'User-Agent':'JustWatch Python client (github.com/dawoudt/JustWatchAPI)'} api_url = 'https://api.justwatch.com/titles/{}_{}/popular'.format(self.language, self.country) r = requests.post(api_url, json=payload, headers=header) # Client should deal with rate-limiting. JustWatch may send a 429 Too Many Requests response. r.raise_for_status() # Raises requests.exceptions.HTTPError if r.status_code != 200 return r.json() ...
48362fa70ab20f66f4f398c68ab252dfd36c6117
crust/fields.py
crust/fields.py
class Field(object): """ Base class for all field types """ # This tracks each time a Field instance is created. Used to retain order. creation_counter = 0 def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs): super(Field, self).__init__(*args, **kwargs) self.name = name self.primary_key = primary_key self.serialize = serialize self.creation_counter = Field.creation_counter Field.creation_counter += 1 def hydrate(self, value): return value
class Field(object): """ Base class for all field types """ # This tracks each time a Field instance is created. Used to retain order. creation_counter = 0 def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs): super(Field, self).__init__(*args, **kwargs) self.name = name self.primary_key = primary_key self.serialize = serialize self.creation_counter = Field.creation_counter Field.creation_counter += 1 def hydrate(self, value): return value def dehydrate(self, value): return value
Make provisions for dehydrating a field
Make provisions for dehydrating a field
Python
bsd-2-clause
dstufft/crust
python
## Code Before: class Field(object): """ Base class for all field types """ # This tracks each time a Field instance is created. Used to retain order. creation_counter = 0 def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs): super(Field, self).__init__(*args, **kwargs) self.name = name self.primary_key = primary_key self.serialize = serialize self.creation_counter = Field.creation_counter Field.creation_counter += 1 def hydrate(self, value): return value ## Instruction: Make provisions for dehydrating a field ## Code After: class Field(object): """ Base class for all field types """ # This tracks each time a Field instance is created. Used to retain order. creation_counter = 0 def __init__(self, name=None, primary_key=False, serialize=True, *args, **kwargs): super(Field, self).__init__(*args, **kwargs) self.name = name self.primary_key = primary_key self.serialize = serialize self.creation_counter = Field.creation_counter Field.creation_counter += 1 def hydrate(self, value): return value def dehydrate(self, value): return value
... def hydrate(self, value): return value def dehydrate(self, value): return value ...
cc4b68c7eccf05ca32802022b2abfd31b51bce32
chef/exceptions.py
chef/exceptions.py
class ChefError(Exception): """Top-level Chef error.""" class ChefServerError(ChefError): """An error from a Chef server. May include a HTTP response code.""" def __init__(self, message, code=None): ChefError.__init__(self, message) self.code = code
class ChefError(Exception): """Top-level Chef error.""" class ChefServerError(ChefError): """An error from a Chef server. May include a HTTP response code.""" def __init__(self, message, code=None): super(ChefError, self).__init__(message) self.code = code
Use super() for great justice.
Use super() for great justice.
Python
apache-2.0
Scalr/pychef,Scalr/pychef,cread/pychef,dipakvwarade/pychef,dipakvwarade/pychef,cread/pychef,coderanger/pychef,coderanger/pychef,jarosser06/pychef,jarosser06/pychef
python
## Code Before: class ChefError(Exception): """Top-level Chef error.""" class ChefServerError(ChefError): """An error from a Chef server. May include a HTTP response code.""" def __init__(self, message, code=None): ChefError.__init__(self, message) self.code = code ## Instruction: Use super() for great justice. ## Code After: class ChefError(Exception): """Top-level Chef error.""" class ChefServerError(ChefError): """An error from a Chef server. May include a HTTP response code.""" def __init__(self, message, code=None): super(ChefError, self).__init__(message) self.code = code
# ... existing code ... class ChefServerError(ChefError): """An error from a Chef server. May include a HTTP response code.""" def __init__(self, message, code=None): super(ChefError, self).__init__(message) self.code = code # ... rest of the code ...
d09281f3ba33ac9175705e305272f9a77dbe4288
src/main/java/com/sangdol/experiment/portableDb/ViewResource.java
src/main/java/com/sangdol/experiment/portableDb/ViewResource.java
package com.sangdol.experiment.portableDb; import com.codahale.metrics.annotation.Timed; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.List; /** * @author hugh */ @Path("/user") @Produces(MediaType.APPLICATION_JSON) public class ViewResource { private ViewService viewService; public ViewResource(ViewService viewService) { this.viewService = viewService; } @GET @Path("{id}") @Timed public List<View> viewList(@PathParam("id") int userId) { return viewService.getLatest10Visitors(userId); } @POST @Path("{id}") @Timed public int createView(@PathParam("id") int hostId, @QueryParam("visitor_id") int visitorId) { if (visitorId == 0) return 0; // TODO throw 404 return viewService.createView(hostId, visitorId); } @POST @Path("clear") @Timed public String clear() { viewService.clear(); return "Success"; } @GET @Path("view-count") @Timed public List<Integer> viewCount() { return viewService.getAllViewCounts(); } }
package com.sangdol.experiment.portableDb; import com.codahale.metrics.annotation.Timed; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.List; /** * @author hugh */ @Path("/user") @Produces(MediaType.APPLICATION_JSON) public class ViewResource { private ViewService viewService; public ViewResource(ViewService viewService) { this.viewService = viewService; } @GET @Path("{id}") @Timed public List<View> viewList(@PathParam("id") int hostId) { checkValidity(hostId); return viewService.getLatest10Visitors(hostId); } @POST @Path("{id}") @Timed public int createView(@PathParam("id") int hostId, @QueryParam("visitor_id") int visitorId) { checkValidity(visitorId); return viewService.createView(hostId, visitorId); } private void checkValidity(int userId) { if (userId < 1) throw new WebApplicationException(404); } @POST @Path("clear") @Timed public String clear() { viewService.clear(); return "Success"; } @GET @Path("view-counts") @Timed public List<Integer> viewCount() { return viewService.getAllViewCounts(); } }
Throw 404 exception when accessing with invalid userId
Throw 404 exception when accessing with invalid userId
Java
mit
Sangdol/portable-db-experiment,Sangdol/portable-db-experiment
java
## Code Before: package com.sangdol.experiment.portableDb; import com.codahale.metrics.annotation.Timed; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.List; /** * @author hugh */ @Path("/user") @Produces(MediaType.APPLICATION_JSON) public class ViewResource { private ViewService viewService; public ViewResource(ViewService viewService) { this.viewService = viewService; } @GET @Path("{id}") @Timed public List<View> viewList(@PathParam("id") int userId) { return viewService.getLatest10Visitors(userId); } @POST @Path("{id}") @Timed public int createView(@PathParam("id") int hostId, @QueryParam("visitor_id") int visitorId) { if (visitorId == 0) return 0; // TODO throw 404 return viewService.createView(hostId, visitorId); } @POST @Path("clear") @Timed public String clear() { viewService.clear(); return "Success"; } @GET @Path("view-count") @Timed public List<Integer> viewCount() { return viewService.getAllViewCounts(); } } ## Instruction: Throw 404 exception when accessing with invalid userId ## Code After: package com.sangdol.experiment.portableDb; import com.codahale.metrics.annotation.Timed; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.List; /** * @author hugh */ @Path("/user") @Produces(MediaType.APPLICATION_JSON) public class ViewResource { private ViewService viewService; public ViewResource(ViewService viewService) { this.viewService = viewService; } @GET @Path("{id}") @Timed public List<View> viewList(@PathParam("id") int hostId) { checkValidity(hostId); return viewService.getLatest10Visitors(hostId); } @POST @Path("{id}") @Timed public int createView(@PathParam("id") int hostId, @QueryParam("visitor_id") int visitorId) { checkValidity(visitorId); return viewService.createView(hostId, visitorId); } private void checkValidity(int userId) { if (userId < 1) throw new WebApplicationException(404); } @POST @Path("clear") @Timed public String clear() { viewService.clear(); return "Success"; } @GET @Path("view-counts") @Timed public List<Integer> viewCount() { return viewService.getAllViewCounts(); } }
... @GET @Path("{id}") @Timed public List<View> viewList(@PathParam("id") int hostId) { checkValidity(hostId); return viewService.getLatest10Visitors(hostId); } @POST ... @Path("{id}") @Timed public int createView(@PathParam("id") int hostId, @QueryParam("visitor_id") int visitorId) { checkValidity(visitorId); return viewService.createView(hostId, visitorId); } private void checkValidity(int userId) { if (userId < 1) throw new WebApplicationException(404); } @POST ... } @GET @Path("view-counts") @Timed public List<Integer> viewCount() { return viewService.getAllViewCounts(); ...
a09491de1278db810c31280405c923c30337deb0
scanblog/scanning/management/commands/fixuploadperms.py
scanblog/scanning/management/commands/fixuploadperms.py
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname os.system('sudo chown -R www-data.btb "%s"' % dirname) # files: -rw-rw-r-- os.system('sudo chmod -R 0664 "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname)
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R 0664 "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname)
Change order of permission changes
Change order of permission changes
Python
agpl-3.0
yourcelf/btb,yourcelf/btb,flexpeace/btb,yourcelf/btb,flexpeace/btb,flexpeace/btb,flexpeace/btb,yourcelf/btb,flexpeace/btb,yourcelf/btb
python
## Code Before: import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname os.system('sudo chown -R www-data.btb "%s"' % dirname) # files: -rw-rw-r-- os.system('sudo chmod -R 0664 "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname) ## Instruction: Change order of permission changes ## Code After: import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R 0664 "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname)
// ... existing code ... os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R 0664 "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod 2775 {} \\;' % dirname) // ... rest of the code ...
5fa4bbf781117c20357cf6f477e0298047e11094
engine/migrate.py
engine/migrate.py
import store rstore = store.RedisStore() def populate_terminations(): for game in rstore.all_games(): rstore.set_game(game["game_id"], game["game"]) def populate_game_ids(): keys = rstore.rconn.keys("chess:games:*:game") game_ids = [k.split(":")[-2] for k in keys] rstore.rconn.sadd("chess:game_ids", *game_ids) def populate_players(): keys = rstore.rconn.keys("chess:games:*:*:email") players = set() for k in keys: val = rstore.rconn.get(k) if val: players.add(k) rstore.rconn.sadd("chess:players", *players)
import store rstore = store.RedisStore() def populate_terminations(): for game in rstore.all_games(): rstore.set_game(game["game_id"], game["game"]) def populate_game_ids(): keys = rstore.rconn.keys("chess:games:*:game") game_ids = [k.split(":")[-2] for k in keys] rstore.rconn.sadd("chess:game_ids", *game_ids) def populate_players(): keys = rstore.rconn.keys("chess:games:*:*:email") players = set() for k in keys: val = rstore.rconn.get(k) if val: players.add(val) print players rstore.rconn.sadd("chess:players", *players)
Print player emails in migration script.
Print player emails in migration script.
Python
mit
haldean/chess,haldean/chess,haldean/chess
python
## Code Before: import store rstore = store.RedisStore() def populate_terminations(): for game in rstore.all_games(): rstore.set_game(game["game_id"], game["game"]) def populate_game_ids(): keys = rstore.rconn.keys("chess:games:*:game") game_ids = [k.split(":")[-2] for k in keys] rstore.rconn.sadd("chess:game_ids", *game_ids) def populate_players(): keys = rstore.rconn.keys("chess:games:*:*:email") players = set() for k in keys: val = rstore.rconn.get(k) if val: players.add(k) rstore.rconn.sadd("chess:players", *players) ## Instruction: Print player emails in migration script. ## Code After: import store rstore = store.RedisStore() def populate_terminations(): for game in rstore.all_games(): rstore.set_game(game["game_id"], game["game"]) def populate_game_ids(): keys = rstore.rconn.keys("chess:games:*:game") game_ids = [k.split(":")[-2] for k in keys] rstore.rconn.sadd("chess:game_ids", *game_ids) def populate_players(): keys = rstore.rconn.keys("chess:games:*:*:email") players = set() for k in keys: val = rstore.rconn.get(k) if val: players.add(val) print players rstore.rconn.sadd("chess:players", *players)
// ... existing code ... for k in keys: val = rstore.rconn.get(k) if val: players.add(val) print players rstore.rconn.sadd("chess:players", *players) // ... rest of the code ...
8c39774323a9f462dd513032c5d84a43af3d5a89
ActionLog/scripts/specific-action-log/newIssueGroup.c
ActionLog/scripts/specific-action-log/newIssueGroup.c
specific action log: newIssueGroup # Set Variable [ $brainstate; Value:brainstate::_lockBrainstateID ] # Go to Layout [ “IssuesAndObservations Copy” (issue) ] # New Record/Request Set Field [ issue::lock; "location" ] Set Field [ issue::_keyBrainstate; $brainstate ] # Set Variable [ $group; Value:issue::_LockList ] # Go to Layout [ original layout ] # Go to Object [ Object Name: "group" ] # Go to Portal Row [ First ] Loop Exit Loop If [ $group = category::_LockList ] Go to Portal Row [ Select; Next ] End Loop # Go to Field [ category::text ] January 6, 平成26 11:15:58 ActionLog.fp7 - newIssueGroup -1-
specific action log: newIssueGroup # Set Variable [ $brainstate; Value:brainstate::_lockBrainstateID ] # Go to Layout [ “IssuesAndObservations Copy” (issue) ] # New Record/Request Set Field [ issue::lock; "location" ] Set Field [ issue::_keyBrainstate; $brainstate ] # Set Variable [ $group; Value:issue::_LockList ] # Go to Layout [ original layout ] # Go to Object [ Object Name: "group" ] # Go to Portal Row [ First ] Loop Exit Loop If [ $group = category::_LockList ] Go to Portal Row [ Select; Next; Exit after last ] End Loop # Go to Field [ category::text ] February 24, 平成26 15:13:03 ActionLog.fp7 - newIssueGroup -1-
Fix logic loop in script
Fix logic loop in script Fix logic loop in script attached to button [Specific Action Tag 47] so it exists after reaching last item.
C
apache-2.0
HelpGiveThanks/ActionLog,HelpGiveThanks/ActionLog
c
## Code Before: specific action log: newIssueGroup # Set Variable [ $brainstate; Value:brainstate::_lockBrainstateID ] # Go to Layout [ “IssuesAndObservations Copy” (issue) ] # New Record/Request Set Field [ issue::lock; "location" ] Set Field [ issue::_keyBrainstate; $brainstate ] # Set Variable [ $group; Value:issue::_LockList ] # Go to Layout [ original layout ] # Go to Object [ Object Name: "group" ] # Go to Portal Row [ First ] Loop Exit Loop If [ $group = category::_LockList ] Go to Portal Row [ Select; Next ] End Loop # Go to Field [ category::text ] January 6, 平成26 11:15:58 ActionLog.fp7 - newIssueGroup -1- ## Instruction: Fix logic loop in script Fix logic loop in script attached to button [Specific Action Tag 47] so it exists after reaching last item. ## Code After: specific action log: newIssueGroup # Set Variable [ $brainstate; Value:brainstate::_lockBrainstateID ] # Go to Layout [ “IssuesAndObservations Copy” (issue) ] # New Record/Request Set Field [ issue::lock; "location" ] Set Field [ issue::_keyBrainstate; $brainstate ] # Set Variable [ $group; Value:issue::_LockList ] # Go to Layout [ original layout ] # Go to Object [ Object Name: "group" ] # Go to Portal Row [ First ] Loop Exit Loop If [ $group = category::_LockList ] Go to Portal Row [ Select; Next; Exit after last ] End Loop # Go to Field [ category::text ] February 24, 平成26 15:13:03 ActionLog.fp7 - newIssueGroup -1-
# ... existing code ... Loop Exit Loop If [ $group = category::_LockList ] Go to Portal Row [ Select; Next; Exit after last ] End Loop # Go to Field [ category::text ] February 24, 平成26 15:13:03 ActionLog.fp7 - newIssueGroup -1- # ... rest of the code ...
8386d7372f9ff8bfad651efe43504746aff19b73
app/models/rooms/rooms.py
app/models/rooms/rooms.py
from models.people.people import Staff, Fellow from models.rooms.rooms import Office, LivingSpace import random class Dojo(object): def __init__(self): self.offices = [] self.livingrooms = [] self.staff = [] self.fellows = [] self.all_rooms = [] self.all_people = [] def get_room(self, rooms): """A function to generate a list of random rooms with space. :param rooms: :return: room_name """ # a room is only available if it's capacity is not exceeded available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity] # return False if all rooms are full if len(available_rooms) < 1: return False # choose a room fro the list of available rooms. chosen_room = random.choice(available_rooms) return chosen_room.room_name def create_room(self, room_name, room_type): if room_type is 'office': if room_name not in [room.room_name for room in self.offices]: room = Office(room_name=room_name, room_type=room_type) self.offices.append(room) self.all_rooms.append(room) return 'An office called' + ' ' + room_name + ' ' + 'has been successfully created' return 'An office with that name already exists' if room_type is 'livingspace': if room_name not in [room.room_name for room in self.livingrooms]: room = LivingSpace(room_name=room_name, room_type=room_type) # add object to list( has both room_name and room_type) self.livingrooms.append(room) self.all_rooms.append(room) return 'A room called ' + room_name + ' has been successfully created!' return 'A living room with that name already exists'
import os import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) class Room(object): """Models the kind of rooms available at Andela, It forms the base class Room from which OfficeSpace and LivingRoom inherit""" def __init__(self, room_name, room_type, room_capacity): """Initializes the base class Room :param room_name: A string representing the name of the room :param room_type: A string representing the type of room, whether office or residential :param room_capacity: An integer representing the amount of space per room. """ self.room_name = room_name self.room_type = room_type self.room_capacity = room_capacity self.occupants = []
Implement the Room base class
Implement the Room base class
Python
mit
Alweezy/alvin-mutisya-dojo-project
python
## Code Before: from models.people.people import Staff, Fellow from models.rooms.rooms import Office, LivingSpace import random class Dojo(object): def __init__(self): self.offices = [] self.livingrooms = [] self.staff = [] self.fellows = [] self.all_rooms = [] self.all_people = [] def get_room(self, rooms): """A function to generate a list of random rooms with space. :param rooms: :return: room_name """ # a room is only available if it's capacity is not exceeded available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity] # return False if all rooms are full if len(available_rooms) < 1: return False # choose a room fro the list of available rooms. chosen_room = random.choice(available_rooms) return chosen_room.room_name def create_room(self, room_name, room_type): if room_type is 'office': if room_name not in [room.room_name for room in self.offices]: room = Office(room_name=room_name, room_type=room_type) self.offices.append(room) self.all_rooms.append(room) return 'An office called' + ' ' + room_name + ' ' + 'has been successfully created' return 'An office with that name already exists' if room_type is 'livingspace': if room_name not in [room.room_name for room in self.livingrooms]: room = LivingSpace(room_name=room_name, room_type=room_type) # add object to list( has both room_name and room_type) self.livingrooms.append(room) self.all_rooms.append(room) return 'A room called ' + room_name + ' has been successfully created!' return 'A living room with that name already exists' ## Instruction: Implement the Room base class ## Code After: import os import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) class Room(object): """Models the kind of rooms available at Andela, It forms the base class Room from which OfficeSpace and LivingRoom inherit""" def __init__(self, room_name, room_type, room_capacity): """Initializes the base class Room :param room_name: A string representing the name of the room :param room_type: A string representing the type of room, whether office or residential :param room_capacity: An integer representing the amount of space per room. """ self.room_name = room_name self.room_type = room_type self.room_capacity = room_capacity self.occupants = []
... import os import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) class Room(object): """Models the kind of rooms available at Andela, It forms the base class Room from which OfficeSpace and LivingRoom inherit""" def __init__(self, room_name, room_type, room_capacity): """Initializes the base class Room :param room_name: A string representing the name of the room :param room_type: A string representing the type of room, whether office or residential :param room_capacity: An integer representing the amount of space per room. """ self.room_name = room_name self.room_type = room_type self.room_capacity = room_capacity self.occupants = [] ...
7a999f17e30283eaf97ff2fd9733bc617a398b9c
workflow/cli/src/main/java/com/asakusafw/workflow/cli/common/ExecutionContextParameter.java
workflow/cli/src/main/java/com/asakusafw/workflow/cli/common/ExecutionContextParameter.java
/** * Copyright 2011-2017 Asakusa Framework Team. * * 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.asakusafw.workflow.cli.common; import com.asakusafw.workflow.executor.ExecutionContext; import com.asakusafw.workflow.executor.basic.BasicExecutionContext; /** * Handles parameters about execution context. * @since 0.10.0 */ public class ExecutionContextParameter { // NOTE: require Hadoop Configuration? private final ExecutionContext context = new BasicExecutionContext() .withEnvironmentVariables(m -> m.putAll(System.getenv())); /** * Returns the execution context. * @return the execution context */ public ExecutionContext getExecutionContext() { return context; } }
/** * Copyright 2011-2017 Asakusa Framework Team. * * 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.asakusafw.workflow.cli.common; import com.asakusafw.workflow.executor.ExecutionContext; import com.asakusafw.workflow.executor.TaskExecutors; import com.asakusafw.workflow.executor.basic.BasicExecutionContext; import com.beust.jcommander.Parameter; /** * Handles parameters about execution context. * @since 0.10.0 */ public class ExecutionContextParameter { /** * The batch application base directory. */ @Parameter( names = { "-B", "--batchapps" }, description = "Batch application base directory (ASAKUSA_BATCHAPPS_HOME).", required = false ) public String batchappsPath; private final BasicExecutionContext context = new BasicExecutionContext() .withEnvironmentVariables(m -> m.putAll(System.getenv())); /** * Returns the execution context. * @return the execution context */ public ExecutionContext getExecutionContext() { if (batchappsPath != null) { context.withEnvironmentVariables(m -> m.put(TaskExecutors.ENV_BATCHAPPS_PATH, batchappsPath)); } return context; } }
Introduce `-B` option into `asakusafw.sh run`.
Introduce `-B` option into `asakusafw.sh run`.
Java
apache-2.0
asakusafw/asakusafw,akirakw/asakusafw,ashigeru/asakusafw,akirakw/asakusafw,asakusafw/asakusafw,ashigeru/asakusafw
java
## Code Before: /** * Copyright 2011-2017 Asakusa Framework Team. * * 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.asakusafw.workflow.cli.common; import com.asakusafw.workflow.executor.ExecutionContext; import com.asakusafw.workflow.executor.basic.BasicExecutionContext; /** * Handles parameters about execution context. * @since 0.10.0 */ public class ExecutionContextParameter { // NOTE: require Hadoop Configuration? private final ExecutionContext context = new BasicExecutionContext() .withEnvironmentVariables(m -> m.putAll(System.getenv())); /** * Returns the execution context. * @return the execution context */ public ExecutionContext getExecutionContext() { return context; } } ## Instruction: Introduce `-B` option into `asakusafw.sh run`. ## Code After: /** * Copyright 2011-2017 Asakusa Framework Team. * * 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.asakusafw.workflow.cli.common; import com.asakusafw.workflow.executor.ExecutionContext; import com.asakusafw.workflow.executor.TaskExecutors; import com.asakusafw.workflow.executor.basic.BasicExecutionContext; import com.beust.jcommander.Parameter; /** * Handles parameters about execution context. * @since 0.10.0 */ public class ExecutionContextParameter { /** * The batch application base directory. */ @Parameter( names = { "-B", "--batchapps" }, description = "Batch application base directory (ASAKUSA_BATCHAPPS_HOME).", required = false ) public String batchappsPath; private final BasicExecutionContext context = new BasicExecutionContext() .withEnvironmentVariables(m -> m.putAll(System.getenv())); /** * Returns the execution context. * @return the execution context */ public ExecutionContext getExecutionContext() { if (batchappsPath != null) { context.withEnvironmentVariables(m -> m.put(TaskExecutors.ENV_BATCHAPPS_PATH, batchappsPath)); } return context; } }
// ... existing code ... package com.asakusafw.workflow.cli.common; import com.asakusafw.workflow.executor.ExecutionContext; import com.asakusafw.workflow.executor.TaskExecutors; import com.asakusafw.workflow.executor.basic.BasicExecutionContext; import com.beust.jcommander.Parameter; /** * Handles parameters about execution context. // ... modified code ... */ public class ExecutionContextParameter { /** * The batch application base directory. */ @Parameter( names = { "-B", "--batchapps" }, description = "Batch application base directory (ASAKUSA_BATCHAPPS_HOME).", required = false ) public String batchappsPath; private final BasicExecutionContext context = new BasicExecutionContext() .withEnvironmentVariables(m -> m.putAll(System.getenv())); /** ... * @return the execution context */ public ExecutionContext getExecutionContext() { if (batchappsPath != null) { context.withEnvironmentVariables(m -> m.put(TaskExecutors.ENV_BATCHAPPS_PATH, batchappsPath)); } return context; } } // ... rest of the code ...
3dc90a8173dd3520fd4f335efe9adb77b9167f80
setup.py
setup.py
from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = '[email protected]', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('usr/share/man/man1', ['doc/danboorsync.1']), ('usr/share/licenses/imgfetch/LICENSE', ['doc/LICENSE'])], scripts = ['/usr/bin/danboorsync'], name = 'danboorsync' )
from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = '[email protected]', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('/usr/share/man/man1', ['doc/danboorsync.1']), ('/usr/share/licenses/danboorsync/LICENSE', ['doc/LICENSE'])], scripts = ['/usr/bin/danboorsync'], name = 'danboorsync' )
Fix data_files to install man and license documents
Setup: Fix data_files to install man and license documents
Python
isc
toddgaunt/imgfetch
python
## Code Before: from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = '[email protected]', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('usr/share/man/man1', ['doc/danboorsync.1']), ('usr/share/licenses/imgfetch/LICENSE', ['doc/LICENSE'])], scripts = ['/usr/bin/danboorsync'], name = 'danboorsync' ) ## Instruction: Setup: Fix data_files to install man and license documents ## Code After: from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = '[email protected]', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('/usr/share/man/man1', ['doc/danboorsync.1']), ('/usr/share/licenses/danboorsync/LICENSE', ['doc/LICENSE'])], scripts = ['/usr/bin/danboorsync'], name = 'danboorsync' )
# ... existing code ... package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('/usr/share/man/man1', ['doc/danboorsync.1']), ('/usr/share/licenses/danboorsync/LICENSE', ['doc/LICENSE'])], scripts = ['/usr/bin/danboorsync'], name = 'danboorsync' # ... rest of the code ...
f6bf104cbdcdb909a15c80dafe9ae2e7aebbc2f0
examples/snowball_stemmer_example.py
examples/snowball_stemmer_example.py
from __future__ import unicode_literals from nltk.stem.snowball import HungarianStemmer from nltk import word_tokenize stemmer = HungarianStemmer() test_sentence = "Szeretnék kérni tőled egy óriási szívességet az édesanyám számára." tokenized_sentence = word_tokenize(test_sentence) for word in tokenized_sentence: print "Original word form is '{0}' and the root is '{1}'".format(word, stemmer.stem(word))
from __future__ import unicode_literals from nltk.stem.snowball import HungarianStemmer from nltk import word_tokenize stemmer = HungarianStemmer() test_sentence = "Péter szereti Enikőt és Marit" tokenized_sentence = word_tokenize(test_sentence) print('With SnowballStemmer') for word in tokenized_sentence: print "Original word form is '{}' and the root is '{}'".format(word, stemmer.stem(word))
Add more information to SnowballStemmer
Add more information to SnowballStemmer
Python
apache-2.0
davidpgero/hungarian-nltk
python
## Code Before: from __future__ import unicode_literals from nltk.stem.snowball import HungarianStemmer from nltk import word_tokenize stemmer = HungarianStemmer() test_sentence = "Szeretnék kérni tőled egy óriási szívességet az édesanyám számára." tokenized_sentence = word_tokenize(test_sentence) for word in tokenized_sentence: print "Original word form is '{0}' and the root is '{1}'".format(word, stemmer.stem(word)) ## Instruction: Add more information to SnowballStemmer ## Code After: from __future__ import unicode_literals from nltk.stem.snowball import HungarianStemmer from nltk import word_tokenize stemmer = HungarianStemmer() test_sentence = "Péter szereti Enikőt és Marit" tokenized_sentence = word_tokenize(test_sentence) print('With SnowballStemmer') for word in tokenized_sentence: print "Original word form is '{}' and the root is '{}'".format(word, stemmer.stem(word))
// ... existing code ... from nltk.stem.snowball import HungarianStemmer from nltk import word_tokenize stemmer = HungarianStemmer() test_sentence = "Péter szereti Enikőt és Marit" tokenized_sentence = word_tokenize(test_sentence) print('With SnowballStemmer') for word in tokenized_sentence: print "Original word form is '{}' and the root is '{}'".format(word, stemmer.stem(word)) // ... rest of the code ...
9be8ac9ad3f94875a9381555d8859f289c59d6df
application/browser/application_system_linux.h
application/browser/application_system_linux.h
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef XWALK_APPLICATION_BROWSER_APPLICATION_SYSTEM_LINUX_H_ #define XWALK_APPLICATION_BROWSER_APPLICATION_SYSTEM_LINUX_H_ #include "xwalk/application/browser/application_system.h" namespace xwalk { class DBusManager; } namespace xwalk { namespace application { class ApplicationServiceProviderLinux; class ApplicationSystemLinux : public ApplicationSystem { public: explicit ApplicationSystemLinux(RuntimeContext* runtime_context); virtual ~ApplicationSystemLinux(); DBusManager& dbus_manager(); private: scoped_ptr<ApplicationServiceProviderLinux> service_provider_; scoped_ptr<DBusManager> dbus_manager_; DISALLOW_COPY_AND_ASSIGN(ApplicationSystemLinux); }; } // namespace application } // namespace xwalk #endif // XWALK_APPLICATION_BROWSER_APPLICATION_SYSTEM_LINUX_H_
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef XWALK_APPLICATION_BROWSER_APPLICATION_SYSTEM_LINUX_H_ #define XWALK_APPLICATION_BROWSER_APPLICATION_SYSTEM_LINUX_H_ #include "xwalk/application/browser/application_system.h" namespace xwalk { class DBusManager; } namespace xwalk { namespace application { class ApplicationServiceProviderLinux; class ApplicationSystemLinux : public ApplicationSystem { public: explicit ApplicationSystemLinux(RuntimeContext* runtime_context); virtual ~ApplicationSystemLinux(); DBusManager& dbus_manager(); private: scoped_ptr<DBusManager> dbus_manager_; scoped_ptr<ApplicationServiceProviderLinux> service_provider_; DISALLOW_COPY_AND_ASSIGN(ApplicationSystemLinux); }; } // namespace application } // namespace xwalk #endif // XWALK_APPLICATION_BROWSER_APPLICATION_SYSTEM_LINUX_H_
Fix crash when shutting down
[Application][D-Bus] Fix crash when shutting down DBusManager owns the Bus connection and was being destroyed before the service provider that uses it. TEST=Loaded xwalk --run-as-service and xwalkctl <APP_ID> then closed the window. The first process should not crash but exit cleanly.
C
bsd-3-clause
tedshroyer/crosswalk,minggangw/crosswalk,axinging/crosswalk,xzhan96/crosswalk,RafuCater/crosswalk,tedshroyer/crosswalk,stonegithubs/crosswalk,dreamsxin/crosswalk,Bysmyyr/crosswalk,crosswalk-project/crosswalk-efl,siovene/crosswalk,RafuCater/crosswalk,axinging/crosswalk,darktears/crosswalk,chinakids/crosswalk,xzhan96/crosswalk,darktears/crosswalk,ZhengXinCN/crosswalk,dreamsxin/crosswalk,stonegithubs/crosswalk,PeterWangIntel/crosswalk,chuan9/crosswalk,chuan9/crosswalk,fujunwei/crosswalk,chuan9/crosswalk,bestwpw/crosswalk,chuan9/crosswalk,lincsoon/crosswalk,tedshroyer/crosswalk,jpike88/crosswalk,lincsoon/crosswalk,weiyirong/crosswalk-1,huningxin/crosswalk,siovene/crosswalk,amaniak/crosswalk,chinakids/crosswalk,jpike88/crosswalk,qjia7/crosswalk,minggangw/crosswalk,crosswalk-project/crosswalk-efl,bestwpw/crosswalk,shaochangbin/crosswalk,tomatell/crosswalk,jpike88/crosswalk,crosswalk-project/crosswalk-efl,crosswalk-project/crosswalk-efl,minggangw/crosswalk,siovene/crosswalk,tedshroyer/crosswalk,hgl888/crosswalk-efl,marcuspridham/crosswalk,jondong/crosswalk,amaniak/crosswalk,hgl888/crosswalk,siovene/crosswalk,TheDirtyCalvinist/spacewalk,bestwpw/crosswalk,hgl888/crosswalk,weiyirong/crosswalk-1,hgl888/crosswalk,ZhengXinCN/crosswalk,lincsoon/crosswalk,stonegithubs/crosswalk,lincsoon/crosswalk,PeterWangIntel/crosswalk,pk-sam/crosswalk,mrunalk/crosswalk,baleboy/crosswalk,jondwillis/crosswalk,XiaosongWei/crosswalk,RafuCater/crosswalk,DonnaWuDongxia/crosswalk,TheDirtyCalvinist/spacewalk,XiaosongWei/crosswalk,crosswalk-project/crosswalk,zliang7/crosswalk,stonegithubs/crosswalk,shaochangbin/crosswalk,huningxin/crosswalk,TheDirtyCalvinist/spacewalk,lincsoon/crosswalk,shaochangbin/crosswalk,amaniak/crosswalk,qjia7/crosswalk,dreamsxin/crosswalk,myroot/crosswalk,crosswalk-project/crosswalk,zeropool/crosswalk,baleboy/crosswalk,jondwillis/crosswalk,stonegithubs/crosswalk,pk-sam/crosswalk,stonegithubs/crosswalk,fujunwei/crosswalk,tedshroyer/crosswalk,ZhengXinCN/crosswalk,minggangw/crosswalk,zeropool/crosswalk,pk-sam/crosswalk,leonhsl/crosswalk,minggangw/crosswalk,axinging/crosswalk,chuan9/crosswalk,baleboy/crosswalk,hgl888/crosswalk,fujunwei/crosswalk,zeropool/crosswalk,axinging/crosswalk,bestwpw/crosswalk,baleboy/crosswalk,marcuspridham/crosswalk,shaochangbin/crosswalk,dreamsxin/crosswalk,alex-zhang/crosswalk,RafuCater/crosswalk,PeterWangIntel/crosswalk,huningxin/crosswalk,jpike88/crosswalk,hgl888/crosswalk,hgl888/crosswalk-efl,TheDirtyCalvinist/spacewalk,heke123/crosswalk,DonnaWuDongxia/crosswalk,qjia7/crosswalk,marcuspridham/crosswalk,heke123/crosswalk,weiyirong/crosswalk-1,Bysmyyr/crosswalk,myroot/crosswalk,hgl888/crosswalk,rakuco/crosswalk,fujunwei/crosswalk,jondwillis/crosswalk,qjia7/crosswalk,zliang7/crosswalk,amaniak/crosswalk,tomatell/crosswalk,shaochangbin/crosswalk,rakuco/crosswalk,siovene/crosswalk,weiyirong/crosswalk-1,xzhan96/crosswalk,marcuspridham/crosswalk,DonnaWuDongxia/crosswalk,PeterWangIntel/crosswalk,DonnaWuDongxia/crosswalk,chinakids/crosswalk,lincsoon/crosswalk,heke123/crosswalk,pk-sam/crosswalk,rakuco/crosswalk,tomatell/crosswalk,huningxin/crosswalk,siovene/crosswalk,rakuco/crosswalk,jondwillis/crosswalk,darktears/crosswalk,axinging/crosswalk,alex-zhang/crosswalk,zliang7/crosswalk,RafuCater/crosswalk,zeropool/crosswalk,marcuspridham/crosswalk,bestwpw/crosswalk,heke123/crosswalk,lincsoon/crosswalk,hgl888/crosswalk-efl,Bysmyyr/crosswalk,zliang7/crosswalk,jondwillis/crosswalk,TheDirtyCalvinist/spacewalk,crosswalk-project/crosswalk,XiaosongWei/crosswalk,heke123/crosswalk,huningxin/crosswalk,Pluto-tv/crosswalk,hgl888/crosswalk,leonhsl/crosswalk,rakuco/crosswalk,alex-zhang/crosswalk,crosswalk-project/crosswalk,qjia7/crosswalk,Bysmyyr/crosswalk,jpike88/crosswalk,zliang7/crosswalk,minggangw/crosswalk,Pluto-tv/crosswalk,crosswalk-project/crosswalk-efl,axinging/crosswalk,ZhengXinCN/crosswalk,baleboy/crosswalk,tedshroyer/crosswalk,jondong/crosswalk,marcuspridham/crosswalk,baleboy/crosswalk,hgl888/crosswalk-efl,zeropool/crosswalk,marcuspridham/crosswalk,alex-zhang/crosswalk,zeropool/crosswalk,TheDirtyCalvinist/spacewalk,tedshroyer/crosswalk,XiaosongWei/crosswalk,mrunalk/crosswalk,huningxin/crosswalk,Bysmyyr/crosswalk,Pluto-tv/crosswalk,Bysmyyr/crosswalk,chinakids/crosswalk,xzhan96/crosswalk,darktears/crosswalk,marcuspridham/crosswalk,RafuCater/crosswalk,Pluto-tv/crosswalk,amaniak/crosswalk,leonhsl/crosswalk,DonnaWuDongxia/crosswalk,myroot/crosswalk,alex-zhang/crosswalk,mrunalk/crosswalk,xzhan96/crosswalk,crosswalk-project/crosswalk,Bysmyyr/crosswalk,Bysmyyr/crosswalk,tomatell/crosswalk,fujunwei/crosswalk,zliang7/crosswalk,jpike88/crosswalk,fujunwei/crosswalk,pk-sam/crosswalk,zliang7/crosswalk,Pluto-tv/crosswalk,rakuco/crosswalk,tomatell/crosswalk,jondwillis/crosswalk,ZhengXinCN/crosswalk,shaochangbin/crosswalk,bestwpw/crosswalk,XiaosongWei/crosswalk,myroot/crosswalk,siovene/crosswalk,zeropool/crosswalk,dreamsxin/crosswalk,stonegithubs/crosswalk,DonnaWuDongxia/crosswalk,bestwpw/crosswalk,jondong/crosswalk,leonhsl/crosswalk,xzhan96/crosswalk,fujunwei/crosswalk,axinging/crosswalk,jondong/crosswalk,lincsoon/crosswalk,weiyirong/crosswalk-1,darktears/crosswalk,heke123/crosswalk,RafuCater/crosswalk,darktears/crosswalk,minggangw/crosswalk,ZhengXinCN/crosswalk,chinakids/crosswalk,hgl888/crosswalk-efl,leonhsl/crosswalk,leonhsl/crosswalk,qjia7/crosswalk,tomatell/crosswalk,xzhan96/crosswalk,dreamsxin/crosswalk,crosswalk-project/crosswalk,jondwillis/crosswalk,weiyirong/crosswalk-1,darktears/crosswalk,tomatell/crosswalk,crosswalk-project/crosswalk,amaniak/crosswalk,darktears/crosswalk,chuan9/crosswalk,baleboy/crosswalk,crosswalk-project/crosswalk-efl,crosswalk-project/crosswalk,weiyirong/crosswalk-1,Pluto-tv/crosswalk,myroot/crosswalk,myroot/crosswalk,rakuco/crosswalk,rakuco/crosswalk,mrunalk/crosswalk,minggangw/crosswalk,XiaosongWei/crosswalk,ZhengXinCN/crosswalk,jondong/crosswalk,chuan9/crosswalk,heke123/crosswalk,mrunalk/crosswalk,XiaosongWei/crosswalk,crosswalk-project/crosswalk-efl,PeterWangIntel/crosswalk,alex-zhang/crosswalk,jondong/crosswalk,pk-sam/crosswalk,PeterWangIntel/crosswalk,jpike88/crosswalk,jondong/crosswalk,mrunalk/crosswalk,dreamsxin/crosswalk,xzhan96/crosswalk,amaniak/crosswalk,chinakids/crosswalk,DonnaWuDongxia/crosswalk,jondong/crosswalk,PeterWangIntel/crosswalk,heke123/crosswalk,pk-sam/crosswalk,zliang7/crosswalk,hgl888/crosswalk-efl,alex-zhang/crosswalk,hgl888/crosswalk,hgl888/crosswalk-efl,leonhsl/crosswalk,Pluto-tv/crosswalk,baleboy/crosswalk
c
## Code Before: // Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef XWALK_APPLICATION_BROWSER_APPLICATION_SYSTEM_LINUX_H_ #define XWALK_APPLICATION_BROWSER_APPLICATION_SYSTEM_LINUX_H_ #include "xwalk/application/browser/application_system.h" namespace xwalk { class DBusManager; } namespace xwalk { namespace application { class ApplicationServiceProviderLinux; class ApplicationSystemLinux : public ApplicationSystem { public: explicit ApplicationSystemLinux(RuntimeContext* runtime_context); virtual ~ApplicationSystemLinux(); DBusManager& dbus_manager(); private: scoped_ptr<ApplicationServiceProviderLinux> service_provider_; scoped_ptr<DBusManager> dbus_manager_; DISALLOW_COPY_AND_ASSIGN(ApplicationSystemLinux); }; } // namespace application } // namespace xwalk #endif // XWALK_APPLICATION_BROWSER_APPLICATION_SYSTEM_LINUX_H_ ## Instruction: [Application][D-Bus] Fix crash when shutting down DBusManager owns the Bus connection and was being destroyed before the service provider that uses it. TEST=Loaded xwalk --run-as-service and xwalkctl <APP_ID> then closed the window. The first process should not crash but exit cleanly. ## Code After: // Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef XWALK_APPLICATION_BROWSER_APPLICATION_SYSTEM_LINUX_H_ #define XWALK_APPLICATION_BROWSER_APPLICATION_SYSTEM_LINUX_H_ #include "xwalk/application/browser/application_system.h" namespace xwalk { class DBusManager; } namespace xwalk { namespace application { class ApplicationServiceProviderLinux; class ApplicationSystemLinux : public ApplicationSystem { public: explicit ApplicationSystemLinux(RuntimeContext* runtime_context); virtual ~ApplicationSystemLinux(); DBusManager& dbus_manager(); private: scoped_ptr<DBusManager> dbus_manager_; scoped_ptr<ApplicationServiceProviderLinux> service_provider_; DISALLOW_COPY_AND_ASSIGN(ApplicationSystemLinux); }; } // namespace application } // namespace xwalk #endif // XWALK_APPLICATION_BROWSER_APPLICATION_SYSTEM_LINUX_H_
# ... existing code ... DBusManager& dbus_manager(); private: scoped_ptr<DBusManager> dbus_manager_; scoped_ptr<ApplicationServiceProviderLinux> service_provider_; DISALLOW_COPY_AND_ASSIGN(ApplicationSystemLinux); }; # ... rest of the code ...
4c6f40f3d1394fff9ed9a4c6fe3ffd0ae5cb6230
jsondb/file_writer.py
jsondb/file_writer.py
from .compat import decode, encode def read_data(path): """ Reads a file and returns a json encoded representation of the file. """ db = open(path, "r+") content = db.read() obj = decode(content) db.close() return obj def write_data(path, obj): """ Writes to a file and returns the updated file content. """ with open(path, "w+") as db: db.write(encode(obj)) return obj def is_valid(file_path): """ Check to see if a file exists or is empty """ from os import path, stat return path.exists(file_path) and stat(file_path).st_size > 0
from .compat import decode, encode def read_data(file_path): """ Reads a file and returns a json encoded representation of the file. """ if not is_valid(file_path): write_data(file_path, {}) db = open(file_path, "r+") content = db.read() obj = decode(content) db.close() return obj def write_data(path, obj): """ Writes to a file and returns the updated file content. """ with open(path, "w+") as db: db.write(encode(obj)) return obj def is_valid(file_path): """ Check to see if a file exists or is empty. """ from os import path, stat can_open = False try: with open(file_path) as fp: can_open = True except IOError: return False is_file = path.isfile(file_path) return path.exists(file_path) and is_file and stat(file_path).st_size > 0
Create a new file if the path is invalid.
Create a new file if the path is invalid.
Python
bsd-3-clause
gunthercox/jsondb
python
## Code Before: from .compat import decode, encode def read_data(path): """ Reads a file and returns a json encoded representation of the file. """ db = open(path, "r+") content = db.read() obj = decode(content) db.close() return obj def write_data(path, obj): """ Writes to a file and returns the updated file content. """ with open(path, "w+") as db: db.write(encode(obj)) return obj def is_valid(file_path): """ Check to see if a file exists or is empty """ from os import path, stat return path.exists(file_path) and stat(file_path).st_size > 0 ## Instruction: Create a new file if the path is invalid. ## Code After: from .compat import decode, encode def read_data(file_path): """ Reads a file and returns a json encoded representation of the file. """ if not is_valid(file_path): write_data(file_path, {}) db = open(file_path, "r+") content = db.read() obj = decode(content) db.close() return obj def write_data(path, obj): """ Writes to a file and returns the updated file content. """ with open(path, "w+") as db: db.write(encode(obj)) return obj def is_valid(file_path): """ Check to see if a file exists or is empty. """ from os import path, stat can_open = False try: with open(file_path) as fp: can_open = True except IOError: return False is_file = path.isfile(file_path) return path.exists(file_path) and is_file and stat(file_path).st_size > 0
// ... existing code ... from .compat import decode, encode def read_data(file_path): """ Reads a file and returns a json encoded representation of the file. """ if not is_valid(file_path): write_data(file_path, {}) db = open(file_path, "r+") content = db.read() obj = decode(content) // ... modified code ... def is_valid(file_path): """ Check to see if a file exists or is empty. """ from os import path, stat can_open = False try: with open(file_path) as fp: can_open = True except IOError: return False is_file = path.isfile(file_path) return path.exists(file_path) and is_file and stat(file_path).st_size > 0 // ... rest of the code ...
cf752f01ef49fe6f26789ad3220863f1bd37a44f
raven/src/main/java/net/kencochrane/raven/marshaller/json/MessageInterfaceBinding.java
raven/src/main/java/net/kencochrane/raven/marshaller/json/MessageInterfaceBinding.java
package net.kencochrane.raven.marshaller.json; import com.fasterxml.jackson.core.JsonGenerator; import net.kencochrane.raven.event.interfaces.MessageInterface; import java.io.IOException; public class MessageInterfaceBinding implements InterfaceBinding<MessageInterface> { private static final String MESSAGE_PARAMETER = "message"; private static final String PARAMS_PARAMETER = "params"; @Override public void writeInterface(JsonGenerator generator, MessageInterface messageInterface) throws IOException { generator.writeStartObject(); generator.writeStringField(MESSAGE_PARAMETER, messageInterface.getMessage()); generator.writeArrayFieldStart(PARAMS_PARAMETER); for (String parameter : messageInterface.getParams()) { generator.writeString(parameter); } generator.writeEndArray(); generator.writeEndObject(); } }
package net.kencochrane.raven.marshaller.json; import com.fasterxml.jackson.core.JsonGenerator; import net.kencochrane.raven.event.interfaces.MessageInterface; import java.io.IOException; public class MessageInterfaceBinding implements InterfaceBinding<MessageInterface> { /** * Maximum length for a message. */ public static final int MAX_MESSAGE_LENGTH = 1000; private static final String MESSAGE_PARAMETER = "message"; private static final String PARAMS_PARAMETER = "params"; /** * Formats a message, ensuring that the maximum length {@link #MAX_MESSAGE_LENGTH} isn't reached. * * @param message message to format. * @return formatted message (shortened if necessary). */ private String formatMessage(String message) { if (message == null) return null; else if (message.length() > MAX_MESSAGE_LENGTH) return message.substring(0, MAX_MESSAGE_LENGTH); else return message; } @Override public void writeInterface(JsonGenerator generator, MessageInterface messageInterface) throws IOException { generator.writeStartObject(); generator.writeStringField(MESSAGE_PARAMETER, formatMessage(messageInterface.getMessage())); generator.writeArrayFieldStart(PARAMS_PARAMETER); for (String parameter : messageInterface.getParams()) { generator.writeString(parameter); } generator.writeEndArray(); generator.writeEndObject(); } }
Set a maximum size for the Message interface
Set a maximum size for the Message interface
Java
bsd-3-clause
littleyang/raven-java,reki2000/raven-java6,buckett/raven-java,galmeida/raven-java,galmeida/raven-java,littleyang/raven-java,buckett/raven-java,reki2000/raven-java6
java
## Code Before: package net.kencochrane.raven.marshaller.json; import com.fasterxml.jackson.core.JsonGenerator; import net.kencochrane.raven.event.interfaces.MessageInterface; import java.io.IOException; public class MessageInterfaceBinding implements InterfaceBinding<MessageInterface> { private static final String MESSAGE_PARAMETER = "message"; private static final String PARAMS_PARAMETER = "params"; @Override public void writeInterface(JsonGenerator generator, MessageInterface messageInterface) throws IOException { generator.writeStartObject(); generator.writeStringField(MESSAGE_PARAMETER, messageInterface.getMessage()); generator.writeArrayFieldStart(PARAMS_PARAMETER); for (String parameter : messageInterface.getParams()) { generator.writeString(parameter); } generator.writeEndArray(); generator.writeEndObject(); } } ## Instruction: Set a maximum size for the Message interface ## Code After: package net.kencochrane.raven.marshaller.json; import com.fasterxml.jackson.core.JsonGenerator; import net.kencochrane.raven.event.interfaces.MessageInterface; import java.io.IOException; public class MessageInterfaceBinding implements InterfaceBinding<MessageInterface> { /** * Maximum length for a message. */ public static final int MAX_MESSAGE_LENGTH = 1000; private static final String MESSAGE_PARAMETER = "message"; private static final String PARAMS_PARAMETER = "params"; /** * Formats a message, ensuring that the maximum length {@link #MAX_MESSAGE_LENGTH} isn't reached. * * @param message message to format. * @return formatted message (shortened if necessary). */ private String formatMessage(String message) { if (message == null) return null; else if (message.length() > MAX_MESSAGE_LENGTH) return message.substring(0, MAX_MESSAGE_LENGTH); else return message; } @Override public void writeInterface(JsonGenerator generator, MessageInterface messageInterface) throws IOException { generator.writeStartObject(); generator.writeStringField(MESSAGE_PARAMETER, formatMessage(messageInterface.getMessage())); generator.writeArrayFieldStart(PARAMS_PARAMETER); for (String parameter : messageInterface.getParams()) { generator.writeString(parameter); } generator.writeEndArray(); generator.writeEndObject(); } }
// ... existing code ... import java.io.IOException; public class MessageInterfaceBinding implements InterfaceBinding<MessageInterface> { /** * Maximum length for a message. */ public static final int MAX_MESSAGE_LENGTH = 1000; private static final String MESSAGE_PARAMETER = "message"; private static final String PARAMS_PARAMETER = "params"; /** * Formats a message, ensuring that the maximum length {@link #MAX_MESSAGE_LENGTH} isn't reached. * * @param message message to format. * @return formatted message (shortened if necessary). */ private String formatMessage(String message) { if (message == null) return null; else if (message.length() > MAX_MESSAGE_LENGTH) return message.substring(0, MAX_MESSAGE_LENGTH); else return message; } @Override public void writeInterface(JsonGenerator generator, MessageInterface messageInterface) throws IOException { generator.writeStartObject(); generator.writeStringField(MESSAGE_PARAMETER, formatMessage(messageInterface.getMessage())); generator.writeArrayFieldStart(PARAMS_PARAMETER); for (String parameter : messageInterface.getParams()) { generator.writeString(parameter); // ... rest of the code ...
b65c1af09bb81f1ed9566db0f189e9a530523d23
src/cjl_magistri/LoremIpsumText.java
src/cjl_magistri/LoremIpsumText.java
package cjl_magistri; /** * Created with IntelliJ IDEA. * User: larry * Date: 6/20/15 * Time: 5:57 PM * To change this template use File | Settings | File Templates. */ public class LoremIpsumText { public LoremIpsumText(String textSource) { //To change body of created methods use File | Settings | File Templates. } public String nextWord() { return null; //To change body of created methods use File | Settings | File Templates. } }
package cjl_magistri; /** * Created with IntelliJ IDEA. * User: larry * Date: 6/20/15 * Time: 5:57 PM * To change this template use File | Settings | File Templates. */ public class LoremIpsumText { private final String _source; public LoremIpsumText(String textSource) { _source = textSource; } public String nextWord() { return _source; } }
Write silly implementation to turn test green.
Write silly implementation to turn test green.
Java
apache-2.0
mrwizard82d1/lorem_ipsum_java,mrwizard82d1/lorem_ipsum_java
java
## Code Before: package cjl_magistri; /** * Created with IntelliJ IDEA. * User: larry * Date: 6/20/15 * Time: 5:57 PM * To change this template use File | Settings | File Templates. */ public class LoremIpsumText { public LoremIpsumText(String textSource) { //To change body of created methods use File | Settings | File Templates. } public String nextWord() { return null; //To change body of created methods use File | Settings | File Templates. } } ## Instruction: Write silly implementation to turn test green. ## Code After: package cjl_magistri; /** * Created with IntelliJ IDEA. * User: larry * Date: 6/20/15 * Time: 5:57 PM * To change this template use File | Settings | File Templates. */ public class LoremIpsumText { private final String _source; public LoremIpsumText(String textSource) { _source = textSource; } public String nextWord() { return _source; } }
// ... existing code ... * To change this template use File | Settings | File Templates. */ public class LoremIpsumText { private final String _source; public LoremIpsumText(String textSource) { _source = textSource; } public String nextWord() { return _source; } } // ... rest of the code ...
ff7ec23bcef13412ee4ad997843664bbb4ff3738
wedding/wsgi.py
wedding/wsgi.py
import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wedding.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application)
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wedding.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application)
Set DJANGO_SETTINGS_MODULE before importing DjangoWhiteNoise
[heroku] Set DJANGO_SETTINGS_MODULE before importing DjangoWhiteNoise
Python
mit
jbinney/wedding,jbinney/wedding,jbinney/wedding
python
## Code Before: import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wedding.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) ## Instruction: [heroku] Set DJANGO_SETTINGS_MODULE before importing DjangoWhiteNoise ## Code After: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wedding.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application)
# ... existing code ... import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wedding.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application) # ... rest of the code ...
cc51137aedeee8bdcf6b47e98b195ec750183ab4
context_variables/__init__.py
context_variables/__init__.py
class context_variable(object): def __init__(self, func): self.func = func self.__doc__ = func.__doc__ def __get__(self, obj, objtype=None): # Handle case of being called from class instead of an instance if obj is None: return self # Evaluate the property value = self.func(obj) # Save value into the instance, replacing the descriptor object.__setattr__(obj, self.func.__name__, value) return value def get_context_variables(obj): context = {} for attr in dir(obj.__class__): # Don't bother to check _private/__special attributes if attr.startswith('_'): continue # Get attributes off the class, in case they've already been # cached as their final values in the instance dictionary and to # avoid general descriptor weirdness raw_attr = getattr(obj.__class__, attr) if isinstance(raw_attr, context_variable): # Force evaluation of obj.`attr` context[attr] = getattr(obj, attr) return context
class context_variable(object): def __init__(self, func): self.func = func self.__doc__ = func.__doc__ def __get__(self, obj, objtype=None): # Handle case of being called from class instead of an instance if obj is None: return self # If we got a plain value, return that if not callable(self.func): return self.func # Evaluate the property value = self.func(obj) # Save value into the instance, replacing the descriptor object.__setattr__(obj, self.func.__name__, value) return value def get_context_variables(obj): context = {} for attr in dir(obj.__class__): # Don't bother to check _private/__special attributes if attr.startswith('_'): continue # Get attributes off the class, in case they've already been # cached as their final values in the instance dictionary and to # avoid general descriptor weirdness raw_attr = getattr(obj.__class__, attr) if isinstance(raw_attr, context_variable): # Force evaluation of obj.`attr` context[attr] = getattr(obj, attr) return context
Allow plain values, not just methods
Allow plain values, not just methods
Python
mit
carlmjohnson/django-context-variables
python
## Code Before: class context_variable(object): def __init__(self, func): self.func = func self.__doc__ = func.__doc__ def __get__(self, obj, objtype=None): # Handle case of being called from class instead of an instance if obj is None: return self # Evaluate the property value = self.func(obj) # Save value into the instance, replacing the descriptor object.__setattr__(obj, self.func.__name__, value) return value def get_context_variables(obj): context = {} for attr in dir(obj.__class__): # Don't bother to check _private/__special attributes if attr.startswith('_'): continue # Get attributes off the class, in case they've already been # cached as their final values in the instance dictionary and to # avoid general descriptor weirdness raw_attr = getattr(obj.__class__, attr) if isinstance(raw_attr, context_variable): # Force evaluation of obj.`attr` context[attr] = getattr(obj, attr) return context ## Instruction: Allow plain values, not just methods ## Code After: class context_variable(object): def __init__(self, func): self.func = func self.__doc__ = func.__doc__ def __get__(self, obj, objtype=None): # Handle case of being called from class instead of an instance if obj is None: return self # If we got a plain value, return that if not callable(self.func): return self.func # Evaluate the property value = self.func(obj) # Save value into the instance, replacing the descriptor object.__setattr__(obj, self.func.__name__, value) return value def get_context_variables(obj): context = {} for attr in dir(obj.__class__): # Don't bother to check _private/__special attributes if attr.startswith('_'): continue # Get attributes off the class, in case they've already been # cached as their final values in the instance dictionary and to # avoid general descriptor weirdness raw_attr = getattr(obj.__class__, attr) if isinstance(raw_attr, context_variable): # Force evaluation of obj.`attr` context[attr] = getattr(obj, attr) return context
# ... existing code ... # Handle case of being called from class instead of an instance if obj is None: return self # If we got a plain value, return that if not callable(self.func): return self.func # Evaluate the property value = self.func(obj) # Save value into the instance, replacing the descriptor # ... rest of the code ...
91db70d1fc266e3e3925e84fcaf83410e0504e37
Lib/tkinter/test/test_tkinter/test_font.py
Lib/tkinter/test/test_tkinter/test_font.py
import unittest import tkinter from tkinter import font from test.support import requires, run_unittest import tkinter.test.support as support requires('gui') class FontTest(unittest.TestCase): def setUp(self): support.root_deiconify() def tearDown(self): support.root_withdraw() def test_font_eq(self): font1 = font.nametofont("TkDefaultFont") font2 = font.nametofont("TkDefaultFont") self.assertIsNot(font1, font2) self.assertEqual(font1, font2) self.assertNotEqual(font1, font1.copy()) self.assertNotEqual(font1, 0) tests_gui = (FontTest, ) if __name__ == "__main__": run_unittest(*tests_gui)
import unittest import tkinter from tkinter import font from test.support import requires, run_unittest import tkinter.test.support as support requires('gui') class FontTest(unittest.TestCase): def setUp(self): support.root_deiconify() def tearDown(self): support.root_withdraw() def test_font_eq(self): fontname = "TkDefaultFont" try: f = font.Font(name=fontname, exists=True) except tkinter._tkinter.TclError: f = font.Font(name=fontname, exists=False) font1 = font.nametofont(fontname) font2 = font.nametofont(fontname) self.assertIsNot(font1, font2) self.assertEqual(font1, font2) self.assertNotEqual(font1, font1.copy()) self.assertNotEqual(font1, 0) tests_gui = (FontTest, ) if __name__ == "__main__": run_unittest(*tests_gui)
Fix test_tk under OS X with Tk 8.4. Patch by Ned Deily. This should fix some buildbot failures.
Fix test_tk under OS X with Tk 8.4. Patch by Ned Deily. This should fix some buildbot failures.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
python
## Code Before: import unittest import tkinter from tkinter import font from test.support import requires, run_unittest import tkinter.test.support as support requires('gui') class FontTest(unittest.TestCase): def setUp(self): support.root_deiconify() def tearDown(self): support.root_withdraw() def test_font_eq(self): font1 = font.nametofont("TkDefaultFont") font2 = font.nametofont("TkDefaultFont") self.assertIsNot(font1, font2) self.assertEqual(font1, font2) self.assertNotEqual(font1, font1.copy()) self.assertNotEqual(font1, 0) tests_gui = (FontTest, ) if __name__ == "__main__": run_unittest(*tests_gui) ## Instruction: Fix test_tk under OS X with Tk 8.4. Patch by Ned Deily. This should fix some buildbot failures. ## Code After: import unittest import tkinter from tkinter import font from test.support import requires, run_unittest import tkinter.test.support as support requires('gui') class FontTest(unittest.TestCase): def setUp(self): support.root_deiconify() def tearDown(self): support.root_withdraw() def test_font_eq(self): fontname = "TkDefaultFont" try: f = font.Font(name=fontname, exists=True) except tkinter._tkinter.TclError: f = font.Font(name=fontname, exists=False) font1 = font.nametofont(fontname) font2 = font.nametofont(fontname) self.assertIsNot(font1, font2) self.assertEqual(font1, font2) self.assertNotEqual(font1, font1.copy()) self.assertNotEqual(font1, 0) tests_gui = (FontTest, ) if __name__ == "__main__": run_unittest(*tests_gui)
# ... existing code ... support.root_withdraw() def test_font_eq(self): fontname = "TkDefaultFont" try: f = font.Font(name=fontname, exists=True) except tkinter._tkinter.TclError: f = font.Font(name=fontname, exists=False) font1 = font.nametofont(fontname) font2 = font.nametofont(fontname) self.assertIsNot(font1, font2) self.assertEqual(font1, font2) self.assertNotEqual(font1, font1.copy()) # ... rest of the code ...
1cf7b11cdb12a135f2dfa99d7e625eb160b0d7c2
apps/orders/models.py
apps/orders/models.py
from django.db import models # Create your models here.
from django.db import models from ..shop.models import Product class Order(models.Model): first_name = models.CharField(verbose_name="Ім,я", max_length=50) last_name = models.CharField(verbose_name="Прізвище", max_length=50) email = models.EmailField(verbose_name="Email") address = models.CharField(verbose_name="Адреса", max_length=250) postal_code = models.CharField(verbose_name="Поштовий код", max_length=20) city = models.CharField(verbose_name="Місто", max_length=100) created = models.DateTimeField(verbose_name="Створене", auto_now_add=True) updated = models.DateTimeField(verbose_name="Оновлене", auto_now=True) paid = models.BooleanField(verbose_name="Оплачене", default=False) class Meta: ordering = ('-created', ) verbose_name = "Замовлення" verbose_name_plural = "Замовлення" def __str__(self): return "Замовлення: {}".format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items") product = models.ForeignKey(Product, related_name="order_items") price = models.DecimalField(verbose_name="Ціна", max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(verbose_name="К-сть", default=1) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * self.quantity
Create Order and OrderItem Models
Create Order and OrderItem Models
Python
mit
samitnuk/online_shop,samitnuk/online_shop,samitnuk/online_shop
python
## Code Before: from django.db import models # Create your models here. ## Instruction: Create Order and OrderItem Models ## Code After: from django.db import models from ..shop.models import Product class Order(models.Model): first_name = models.CharField(verbose_name="Ім,я", max_length=50) last_name = models.CharField(verbose_name="Прізвище", max_length=50) email = models.EmailField(verbose_name="Email") address = models.CharField(verbose_name="Адреса", max_length=250) postal_code = models.CharField(verbose_name="Поштовий код", max_length=20) city = models.CharField(verbose_name="Місто", max_length=100) created = models.DateTimeField(verbose_name="Створене", auto_now_add=True) updated = models.DateTimeField(verbose_name="Оновлене", auto_now=True) paid = models.BooleanField(verbose_name="Оплачене", default=False) class Meta: ordering = ('-created', ) verbose_name = "Замовлення" verbose_name_plural = "Замовлення" def __str__(self): return "Замовлення: {}".format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items") product = models.ForeignKey(Product, related_name="order_items") price = models.DecimalField(verbose_name="Ціна", max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(verbose_name="К-сть", default=1) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * self.quantity
# ... existing code ... from django.db import models from ..shop.models import Product class Order(models.Model): first_name = models.CharField(verbose_name="Ім,я", max_length=50) last_name = models.CharField(verbose_name="Прізвище", max_length=50) email = models.EmailField(verbose_name="Email") address = models.CharField(verbose_name="Адреса", max_length=250) postal_code = models.CharField(verbose_name="Поштовий код", max_length=20) city = models.CharField(verbose_name="Місто", max_length=100) created = models.DateTimeField(verbose_name="Створене", auto_now_add=True) updated = models.DateTimeField(verbose_name="Оновлене", auto_now=True) paid = models.BooleanField(verbose_name="Оплачене", default=False) class Meta: ordering = ('-created', ) verbose_name = "Замовлення" verbose_name_plural = "Замовлення" def __str__(self): return "Замовлення: {}".format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items") product = models.ForeignKey(Product, related_name="order_items") price = models.DecimalField(verbose_name="Ціна", max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(verbose_name="К-сть", default=1) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * self.quantity # ... rest of the code ...
7a193d8267c2d21a9236c8950a8f5e896535d5cf
link-grammar/dict-file/word-file.h
link-grammar/dict-file/word-file.h
/*************************************************************************/ /* Copyright (c) 2004 */ /* Daniel Sleator, David Temperley, and John Lafferty */ /* Copyright (c) 2014 Linas Vepstas */ /* All rights reserved */ /* */ /* Use of the link grammar parsing system is subject to the terms of the */ /* license set forth in the LICENSE file included with this software. */ /* This license allows free redistribution and use in source and binary */ /* forms, with or without modification, subject to certain conditions. */ /* */ /*************************************************************************/ #include "dict-api.h" #include "structures.h" /* The structure below stores a list of dictionary word files. */ struct Word_file_struct { Word_file * next; const char *file; /* the file name */ bool changed; /* TRUE if this file has been changed */ }; void free_Word_file(Word_file * wf); Dict_node * read_word_file(Dictionary dict, Dict_node * dn, char * filename);
/*************************************************************************/ /* Copyright (c) 2004 */ /* Daniel Sleator, David Temperley, and John Lafferty */ /* Copyright (c) 2014 Linas Vepstas */ /* All rights reserved */ /* */ /* Use of the link grammar parsing system is subject to the terms of the */ /* license set forth in the LICENSE file included with this software. */ /* This license allows free redistribution and use in source and binary */ /* forms, with or without modification, subject to certain conditions. */ /* */ /*************************************************************************/ #include "dict-api.h" #include "structures.h" /* The structure below stores a list of dictionary word files. */ struct Word_file_struct { Word_file * next; const char *file; /* the file name */ bool changed; /* TRUE if this file has been changed (XXX unused) */ }; void free_Word_file(Word_file * wf); Dict_node * read_word_file(Dictionary dict, Dict_node * dn, char * filename);
Add a comment that "changed" is unused.
Word_file_struct: Add a comment that "changed" is unused.
C
lgpl-2.1
linas/link-grammar,linas/link-grammar,ampli/link-grammar,opencog/link-grammar,ampli/link-grammar,linas/link-grammar,ampli/link-grammar,ampli/link-grammar,linas/link-grammar,ampli/link-grammar,opencog/link-grammar,linas/link-grammar,ampli/link-grammar,linas/link-grammar,ampli/link-grammar,ampli/link-grammar,opencog/link-grammar,opencog/link-grammar,opencog/link-grammar,opencog/link-grammar,linas/link-grammar,opencog/link-grammar,linas/link-grammar,linas/link-grammar,opencog/link-grammar,ampli/link-grammar,opencog/link-grammar
c
## Code Before: /*************************************************************************/ /* Copyright (c) 2004 */ /* Daniel Sleator, David Temperley, and John Lafferty */ /* Copyright (c) 2014 Linas Vepstas */ /* All rights reserved */ /* */ /* Use of the link grammar parsing system is subject to the terms of the */ /* license set forth in the LICENSE file included with this software. */ /* This license allows free redistribution and use in source and binary */ /* forms, with or without modification, subject to certain conditions. */ /* */ /*************************************************************************/ #include "dict-api.h" #include "structures.h" /* The structure below stores a list of dictionary word files. */ struct Word_file_struct { Word_file * next; const char *file; /* the file name */ bool changed; /* TRUE if this file has been changed */ }; void free_Word_file(Word_file * wf); Dict_node * read_word_file(Dictionary dict, Dict_node * dn, char * filename); ## Instruction: Word_file_struct: Add a comment that "changed" is unused. ## Code After: /*************************************************************************/ /* Copyright (c) 2004 */ /* Daniel Sleator, David Temperley, and John Lafferty */ /* Copyright (c) 2014 Linas Vepstas */ /* All rights reserved */ /* */ /* Use of the link grammar parsing system is subject to the terms of the */ /* license set forth in the LICENSE file included with this software. */ /* This license allows free redistribution and use in source and binary */ /* forms, with or without modification, subject to certain conditions. */ /* */ /*************************************************************************/ #include "dict-api.h" #include "structures.h" /* The structure below stores a list of dictionary word files. */ struct Word_file_struct { Word_file * next; const char *file; /* the file name */ bool changed; /* TRUE if this file has been changed (XXX unused) */ }; void free_Word_file(Word_file * wf); Dict_node * read_word_file(Dictionary dict, Dict_node * dn, char * filename);
// ... existing code ... { Word_file * next; const char *file; /* the file name */ bool changed; /* TRUE if this file has been changed (XXX unused) */ }; void free_Word_file(Word_file * wf); // ... rest of the code ...
ac900d1a42e5379e192b57cef67845db202e82c3
tests/test_signed_div.py
tests/test_signed_div.py
import nose import angr import subprocess import logging l = logging.getLogger('angr.tests.test_signed_div') import os test_location = str(os.path.dirname(os.path.realpath(__file__))) def run_strtol(threads): test_bin = os.path.join(test_location, "../../binaries-private/tests/i386/test_signed_div") b = angr.Project(test_bin) pg = b.factory.path_group() pg.explore() out_angr = pg.deadended[0].state.posix.dumps(1) proc = subprocess.Popen(test_bin, stdout=subprocess.PIPE) stdout_real, _ = proc.communicate() nose.tools.assert_equal(out_angr, stdout_real) def test_strtol(): yield run_strtol, None yield run_strtol, 8 if __name__ == "__main__": run_strtol(4)
import nose import angr import subprocess import logging l = logging.getLogger('angr.tests.test_signed_div') import os test_location = str(os.path.dirname(os.path.realpath(__file__))) def run_signed_div(): test_bin = os.path.join(test_location, "../../binaries-private/tests/i386/test_signed_div") b = angr.Project(test_bin) pg = b.factory.path_group() pg.explore() out_angr = pg.deadended[0].state.posix.dumps(1) proc = subprocess.Popen(test_bin, stdout=subprocess.PIPE) stdout_real, _ = proc.communicate() nose.tools.assert_equal(out_angr, stdout_real) def test_signed_div(): yield run_signed_div if __name__ == "__main__": run_signed_div()
Rename the signed_div test case, and ... disable the multithreaded test case.
Rename the signed_div test case, and ... disable the multithreaded test case.
Python
bsd-2-clause
tyb0807/angr,angr/angr,tyb0807/angr,chubbymaggie/angr,schieb/angr,f-prettyland/angr,f-prettyland/angr,iamahuman/angr,f-prettyland/angr,axt/angr,chubbymaggie/angr,schieb/angr,angr/angr,schieb/angr,tyb0807/angr,chubbymaggie/angr,iamahuman/angr,iamahuman/angr,angr/angr,axt/angr,axt/angr
python
## Code Before: import nose import angr import subprocess import logging l = logging.getLogger('angr.tests.test_signed_div') import os test_location = str(os.path.dirname(os.path.realpath(__file__))) def run_strtol(threads): test_bin = os.path.join(test_location, "../../binaries-private/tests/i386/test_signed_div") b = angr.Project(test_bin) pg = b.factory.path_group() pg.explore() out_angr = pg.deadended[0].state.posix.dumps(1) proc = subprocess.Popen(test_bin, stdout=subprocess.PIPE) stdout_real, _ = proc.communicate() nose.tools.assert_equal(out_angr, stdout_real) def test_strtol(): yield run_strtol, None yield run_strtol, 8 if __name__ == "__main__": run_strtol(4) ## Instruction: Rename the signed_div test case, and ... disable the multithreaded test case. ## Code After: import nose import angr import subprocess import logging l = logging.getLogger('angr.tests.test_signed_div') import os test_location = str(os.path.dirname(os.path.realpath(__file__))) def run_signed_div(): test_bin = os.path.join(test_location, "../../binaries-private/tests/i386/test_signed_div") b = angr.Project(test_bin) pg = b.factory.path_group() pg.explore() out_angr = pg.deadended[0].state.posix.dumps(1) proc = subprocess.Popen(test_bin, stdout=subprocess.PIPE) stdout_real, _ = proc.communicate() nose.tools.assert_equal(out_angr, stdout_real) def test_signed_div(): yield run_signed_div if __name__ == "__main__": run_signed_div()
... test_location = str(os.path.dirname(os.path.realpath(__file__))) def run_signed_div(): test_bin = os.path.join(test_location, "../../binaries-private/tests/i386/test_signed_div") b = angr.Project(test_bin) ... nose.tools.assert_equal(out_angr, stdout_real) def test_signed_div(): yield run_signed_div if __name__ == "__main__": run_signed_div() ...
fb9ca96431a4f72135245705359eb1f6d340a536
moksha/api/hub/__init__.py
moksha/api/hub/__init__.py
from consumer import * from hub import *
from consumer import * from hub import * from moksha.hub.reactor import reactor from moksha.hub.hub import MokshaHub
Make the MokshaHub and reactor available in the moksha.api.hub module
Make the MokshaHub and reactor available in the moksha.api.hub module
Python
apache-2.0
lmacken/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,ralphbean/moksha,lmacken/moksha,lmacken/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,ralphbean/moksha,ralphbean/moksha,pombredanne/moksha,mokshaproject/moksha
python
## Code Before: from consumer import * from hub import * ## Instruction: Make the MokshaHub and reactor available in the moksha.api.hub module ## Code After: from consumer import * from hub import * from moksha.hub.reactor import reactor from moksha.hub.hub import MokshaHub
# ... existing code ... from consumer import * from hub import * from moksha.hub.reactor import reactor from moksha.hub.hub import MokshaHub # ... rest of the code ...