commit
stringlengths 40
40
| old_file
stringlengths 4
150
| new_file
stringlengths 4
150
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
501
| message
stringlengths 15
4.06k
| lang
stringclasses 4
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
| diff
stringlengths 0
4.35k
|
|---|---|---|---|---|---|---|---|---|---|---|
46328b5baaf25b04703ca04fd376f3f79a26a00f
|
sockjs/cyclone/proto.py
|
sockjs/cyclone/proto.py
|
import simplejson
json_encode = lambda data: simplejson.dumps(data, separators=(',', ':'))
json_decode = lambda data: simplejson.loads(data)
JSONDecodeError = ValueError
# Protocol handlers
CONNECT = 'o'
DISCONNECT = 'c'
MESSAGE = 'm'
HEARTBEAT = 'h'
# Various protocol helpers
def disconnect(code, reason):
"""Return SockJS packet with code and close reason
@param code: Closing code
@param reason: Closing reason
"""
return 'c[%d,"%s"]' % (code, reason)
|
try:
import simplejson
except ImportError:
import json as simplejson
json_encode = lambda data: simplejson.dumps(data, separators=(',', ':'))
json_decode = lambda data: simplejson.loads(data)
JSONDecodeError = ValueError
# Protocol handlers
CONNECT = 'o'
DISCONNECT = 'c'
MESSAGE = 'm'
HEARTBEAT = 'h'
# Various protocol helpers
def disconnect(code, reason):
"""Return SockJS packet with code and close reason
@param code: Closing code
@param reason: Closing reason
"""
return 'c[%d,"%s"]' % (code, reason)
|
Use the json module from stdlib (Python 2.6+) as fallback
|
Use the json module from stdlib (Python 2.6+) as fallback
|
Python
|
mit
|
flaviogrossi/sockjs-cyclone
|
---
+++
@@ -1,4 +1,7 @@
-import simplejson
+try:
+ import simplejson
+except ImportError:
+ import json as simplejson
json_encode = lambda data: simplejson.dumps(data, separators=(',', ':'))
json_decode = lambda data: simplejson.loads(data)
|
5288a47a3a68e216b9c59a46f70b4a2de79bba37
|
server/api/registration/serializers.py
|
server/api/registration/serializers.py
|
from rest_framework import serializers
from django.core import exceptions
from django.contrib.auth import password_validation
from user.models import User
class CaptchaSerializer(serializers.Serializer):
OPERATION_CHOICES = (
('+', '+'),
('-', '-'),
# ('/', '/'),
# ('*', '*'),
)
hash = serializers.CharField(max_length=100)
base64image = serializers.CharField(max_length=100000)
operation = serializers.ChoiceField(choices=OPERATION_CHOICES)
number = serializers.IntegerField()
class UserRegistrationSerializer(serializers.ModelSerializer):
password_repeat = serializers.CharField(max_length=128, required=True, label='Repeat password')
class Meta:
model = User
fields = ('id', 'username', 'email', 'password', 'password_repeat')
def validate_password(self, password):
password_validation.validate_password(password=password)
return password
def validate(self, attrs):
try:
# use django default validators
password_validation.validate_password(password=attrs['password_repeat'])
# compare passwords
if attrs['password'] != attrs['password_repeat']:
raise exceptions.ValidationError({'password_repeat': 'Does not equal password field.'})
except exceptions.ValidationError as e:
raise serializers.ValidationError(
{'password_repeat': e.messages[0]}
)
return attrs
def create(self, validated_data):
del validated_data['password_repeat']
return User.objects.create(**validated_data)
|
from rest_framework import serializers
from django.core import exceptions
from django.contrib.auth import password_validation
from user.models import User
class CaptchaSerializer(serializers.Serializer):
OPERATION_CHOICES = (
('+', '+'),
('-', '-'),
# ('/', '/'),
# ('*', '*'),
)
hash = serializers.CharField(max_length=100)
base64image = serializers.CharField(max_length=100000)
operation = serializers.ChoiceField(choices=OPERATION_CHOICES)
number = serializers.IntegerField()
class UserRegistrationSerializer(serializers.ModelSerializer):
password_repeat = serializers.CharField(max_length=128, required=True, label='Repeat password')
class Meta:
model = User
fields = ('id', 'username', 'email', 'password', 'password_repeat')
def validate_password(self, password):
password_validation.validate_password(password=password)
return password
def validate(self, attrs):
try:
# use django default validators
password_validation.validate_password(password=attrs['password_repeat'])
# compare passwords
if attrs['password'] != attrs['password_repeat']:
raise exceptions.ValidationError({'password_repeat': 'Does not equal password field.'})
except exceptions.ValidationError as e:
raise serializers.ValidationError(
{'password_repeat': e.messages[0]}
)
return attrs
def create(self, validated_data):
del validated_data['password_repeat']
return User.objects.create_user(**validated_data)
|
Update user creation method in register serializer.
|
Update user creation method in register serializer.
|
Python
|
mit
|
olegpshenichniy/truechat,olegpshenichniy/truechat,olegpshenichniy/truechat
|
---
+++
@@ -46,4 +46,4 @@
def create(self, validated_data):
del validated_data['password_repeat']
- return User.objects.create(**validated_data)
+ return User.objects.create_user(**validated_data)
|
196b5aabe2bcee8677c34481f19099f65699a44e
|
billjobs/tests/tests_user_admin_api.py
|
billjobs/tests/tests_user_admin_api.py
|
from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, \
force_authenticate
from billjobs.views import UserAdmin
class UserAdminAPI(TestCase):
""" Test User Admin API REST endpoint """
fixtures=['account_test.yaml']
def setUp(self):
self.client = APIClient()
self.factory = APIRequestFactory()
self.admin = User.objects.get(pk=1)
def test_admin_list_user(self):
request = self.factory.get('/billjobs/users/')
force_authenticate(request, user=self.admin)
view = UserAdmin.as_view()
response = view(request)
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, \
force_authenticate
from billjobs.views import UserAdmin, UserAdminDetail
class UserAdminAPI(TestCase):
""" Test User Admin API REST endpoint """
fixtures=['account_test.yaml']
def setUp(self):
self.client = APIClient()
self.factory = APIRequestFactory()
self.admin = User.objects.get(pk=1)
def test_admin_list_user(self):
request = self.factory.get('/billjobs/users/')
force_authenticate(request, user=self.admin)
view = UserAdmin.as_view()
response = view(request)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_admin_retrieve_user(self):
request = self.factory.get('/billjobs/users/')
force_authenticate(request, user=self.admin)
view = UserAdminDetail.as_view()
response = view(request, pk=1)
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
Add test admin to retrieve a user detail
|
Add test admin to retrieve a user detail
|
Python
|
mit
|
ioO/billjobs
|
---
+++
@@ -3,7 +3,7 @@
from rest_framework import status
from rest_framework.test import APIClient, APIRequestFactory, \
force_authenticate
-from billjobs.views import UserAdmin
+from billjobs.views import UserAdmin, UserAdminDetail
class UserAdminAPI(TestCase):
""" Test User Admin API REST endpoint """
@@ -21,3 +21,10 @@
view = UserAdmin.as_view()
response = view(request)
self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ def test_admin_retrieve_user(self):
+ request = self.factory.get('/billjobs/users/')
+ force_authenticate(request, user=self.admin)
+ view = UserAdminDetail.as_view()
+ response = view(request, pk=1)
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
|
f34afd52aa1b89163d90a21feac7bd9e3425639d
|
gapipy/resources/booking/agency_chain.py
|
gapipy/resources/booking/agency_chain.py
|
# Python 2 and 3
from __future__ import unicode_literals
from gapipy.resources.base import Resource
from gapipy.resources.booking_company import BookingCompany
class AgencyChain(Resource):
_resource_name = 'agency_chains'
_as_is_fields = [
'id',
'href',
'name',
'agencies',
'agent_notifications',
'communication_preferences',
'flags',
'payment_options',
'passenger_notifications',
]
_date_time_fields_local = [
'date_created',
'date_last_modified',
]
_resource_fields = [
('booking_company', BookingCompany),
]
|
# Python 2 and 3
from __future__ import unicode_literals
from gapipy.resources.base import Resource
from gapipy.resources.booking_company import BookingCompany
class AgencyChain(Resource):
_resource_name = 'agency_chains'
_is_parent_resource = True
_as_is_fields = [
'id',
'href',
'name',
'agent_notifications',
'communication_preferences',
'flags',
'payment_options',
'passenger_notifications',
]
_date_time_fields_local = [
'date_created',
'date_last_modified',
]
_resource_fields = [
('booking_company', BookingCompany),
]
_resource_collection_fields = [('agencies', 'Agency')]
|
Make `AgencyChain.agencies` a "resource collection" field
|
Make `AgencyChain.agencies` a "resource collection" field
We can now get a `Query` when accessing the `agencies` attribute on an
`AgencyChain` instead of a dict with an URI to the agencies list.
|
Python
|
mit
|
gadventures/gapipy
|
---
+++
@@ -7,12 +7,12 @@
class AgencyChain(Resource):
_resource_name = 'agency_chains'
+ _is_parent_resource = True
_as_is_fields = [
'id',
'href',
'name',
- 'agencies',
'agent_notifications',
'communication_preferences',
'flags',
@@ -28,3 +28,5 @@
_resource_fields = [
('booking_company', BookingCompany),
]
+
+ _resource_collection_fields = [('agencies', 'Agency')]
|
a42d238fcc33a18cd90267864f0d308e27319ec5
|
rbtools/utils/checks.py
|
rbtools/utils/checks.py
|
import os
import subprocess
import sys
from rbtools.utils.process import die, execute
GNU_DIFF_WIN32_URL = 'http://gnuwin32.sourceforge.net/packages/diffutils.htm'
def check_install(command):
"""
Try executing an external command and return a boolean indicating whether
that command is installed or not. The 'command' argument should be
something that executes quickly, without hitting the network (for
instance, 'svn help' or 'git --version').
"""
try:
subprocess.Popen(command.split(' '),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
return True
except OSError:
return False
def check_gnu_diff():
"""Checks if GNU diff is installed, and informs the user if it's not."""
has_gnu_diff = False
try:
result = execute(['diff', '--version'], ignore_errors=True)
has_gnu_diff = 'GNU diffutils' in result
except OSError:
pass
if not has_gnu_diff:
sys.stderr.write('\n')
sys.stderr.write('GNU diff is required for Subversion '
'repositories. Make sure it is installed\n')
sys.stderr.write('and in the path.\n')
sys.stderr.write('\n')
if os.name == 'nt':
sys.stderr.write('On Windows, you can install this from:\n')
sys.stderr.write(GNU_DIFF_WIN32_URL)
sys.stderr.write('\n')
die()
|
import os
import subprocess
import sys
from rbtools.utils.process import die, execute
GNU_DIFF_WIN32_URL = 'http://gnuwin32.sourceforge.net/packages/diffutils.htm'
def check_install(command):
"""
Try executing an external command and return a boolean indicating whether
that command is installed or not. The 'command' argument should be
something that executes quickly, without hitting the network (for
instance, 'svn help' or 'git --version').
"""
try:
subprocess.Popen(command.split(' '),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
return True
except OSError:
return False
def check_gnu_diff():
"""Checks if GNU diff is installed, and informs the user if it's not."""
has_gnu_diff = False
try:
result = execute(['diff', '--version'], ignore_errors=True)
has_gnu_diff = 'GNU diffutils' in result
except OSError:
pass
if not has_gnu_diff:
sys.stderr.write('\n')
sys.stderr.write('GNU diff is required in order to generate diffs. '
'Make sure it is installed\n')
sys.stderr.write('and in the path.\n')
sys.stderr.write('\n')
if os.name == 'nt':
sys.stderr.write('On Windows, you can install this from:\n')
sys.stderr.write(GNU_DIFF_WIN32_URL)
sys.stderr.write('\n')
die()
|
Fix the GNU diff error to not mention Subversion.
|
Fix the GNU diff error to not mention Subversion.
The GNU diff error was specifically saying Subversion was required,
which didn't make sense when other SCMClients triggered the check.
Instead, make the error more generic.
|
Python
|
mit
|
davidt/rbtools,datjwu/rbtools,halvorlu/rbtools,datjwu/rbtools,davidt/rbtools,bcelary/rbtools,clach04/rbtools,halvorlu/rbtools,datjwu/rbtools,reviewboard/rbtools,reviewboard/rbtools,haosdent/rbtools,beol/rbtools,1tush/rbtools,beol/rbtools,Khan/rbtools,haosdent/rbtools,reviewboard/rbtools,beol/rbtools,haosdent/rbtools,halvorlu/rbtools,clach04/rbtools_0.4.1,Khan/rbtools,davidt/rbtools
|
---
+++
@@ -37,8 +37,8 @@
if not has_gnu_diff:
sys.stderr.write('\n')
- sys.stderr.write('GNU diff is required for Subversion '
- 'repositories. Make sure it is installed\n')
+ sys.stderr.write('GNU diff is required in order to generate diffs. '
+ 'Make sure it is installed\n')
sys.stderr.write('and in the path.\n')
sys.stderr.write('\n')
|
408ccc648d48725271db36a83c71aed1f03ff8c7
|
gntp/test/__init__.py
|
gntp/test/__init__.py
|
import unittest
from gntp.config import GrowlNotifier
class GNTPTestCase(unittest.TestCase):
def setUp(self):
self.growl = GrowlNotifier('GNTP unittest', ['Testing'])
self.growl.register()
self.notification = {
'noteType': 'Testing',
'title': 'Unittest Title',
'description': 'Unittest Description',
}
def _notify(self, **kargs):
for k in self.notification:
if not k in kargs:
kargs[k] = self.notification[k]
return self.growl.notify(**kargs)
|
import unittest
from gntp.config import GrowlNotifier
class GNTPTestCase(unittest.TestCase):
notification = {
'noteType': 'Testing',
'title': 'Unittest Title',
'description': 'Unittest Description',
}
def setUp(self):
self.growl = GrowlNotifier('GNTP unittest', ['Testing'])
self.growl.register()
def _notify(self, **kargs):
for k in self.notification:
if not k in kargs:
kargs[k] = self.notification[k]
return self.growl.notify(**kargs)
|
Move variables to class variables so that we have to duplicate less for child classes
|
Move variables to class variables so that we have to duplicate less for child classes
|
Python
|
mit
|
kfdm/gntp
|
---
+++
@@ -3,15 +3,15 @@
class GNTPTestCase(unittest.TestCase):
+ notification = {
+ 'noteType': 'Testing',
+ 'title': 'Unittest Title',
+ 'description': 'Unittest Description',
+ }
+
def setUp(self):
self.growl = GrowlNotifier('GNTP unittest', ['Testing'])
self.growl.register()
-
- self.notification = {
- 'noteType': 'Testing',
- 'title': 'Unittest Title',
- 'description': 'Unittest Description',
- }
def _notify(self, **kargs):
for k in self.notification:
|
5ce17bba417d6d9edff970c1bc775797f29b7ec4
|
pysat/_constellation.py
|
pysat/_constellation.py
|
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments = None, name = None):
if instruments and name:
raise ValueError('When creating a constellation, please specify a '
'list of instruments or a name, not both.')
elif instruments and not hasattr(instruments, '__getitem__'):
raise ValueError('Constellation: Instruments must be list-like.')
elif not (name or instruments):
raise ValueError('Constellation: Cannot create empty constellation.')
# FIXME
pass
def __getitem__(self, **argv):
return self.instruments.__getitem__(**argv)
def __str__(self):
# FIXME
raise NotImplementedError()
def __repr__(self):
# FIXME
raise NotImplementedError()
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
# FIXME
raise NotImplementedError()
def difference(self, instrument1, instrumet2, data_labels):
# FIXME
raise NotImplementedError()
|
class Constellation(object):
"""Manage and analyze data from multiple pysat Instruments.
FIXME document this.
"""
def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify a '
'list of instruments or a name, not both.')
elif instruments and not hasattr(instruments, '__getitem__'):
raise ValueError('Constellation: Instruments must be list-like.')
elif not (name or instruments):
raise ValueError('Constellation: Cannot create empty constellation.')
if instruments:
self.instruments = instruments
else:
# TODO Implement constellation lookup by name.
raise NotImplementedError()
def __getitem__(self, *args, **kwargs):
return self.instruments.__getitem__(*args, **kwargs)
def __str__(self):
# TODO Implement conversion to string.
raise NotImplementedError()
def __repr__(self):
# TODO Implement __repr__
raise NotImplementedError()
def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
# TODO Implement signal addition.
raise NotImplementedError()
def difference(self, instrument1, instrumet2, data_labels):
# TODO Implement signal difference.
raise NotImplementedError()
|
Fix bugs and style issues.
|
Fix bugs and style issues.
Fix __getitem__, improve documentation, partially implement __init__.
This got rid of some of pylint's complaints.
|
Python
|
bsd-3-clause
|
jklenzing/pysat,rstoneback/pysat
|
---
+++
@@ -4,7 +4,7 @@
FIXME document this.
"""
- def __init__(self, instruments = None, name = None):
+ def __init__(self, instruments=None, name=None):
if instruments and name:
raise ValueError('When creating a constellation, please specify a '
'list of instruments or a name, not both.')
@@ -13,28 +13,28 @@
elif not (name or instruments):
raise ValueError('Constellation: Cannot create empty constellation.')
- # FIXME
- pass
+ if instruments:
+ self.instruments = instruments
+ else:
+ # TODO Implement constellation lookup by name.
+ raise NotImplementedError()
- def __getitem__(self, **argv):
- return self.instruments.__getitem__(**argv)
-
+ def __getitem__(self, *args, **kwargs):
+ return self.instruments.__getitem__(*args, **kwargs)
+
def __str__(self):
- # FIXME
+ # TODO Implement conversion to string.
raise NotImplementedError()
def __repr__(self):
- # FIXME
+ # TODO Implement __repr__
raise NotImplementedError()
-
- def add(self, bounds1, label1, bounds2, label2, bin3, label3,
+
+ def add(self, bounds1, label1, bounds2, label2, bin3, label3,
data_label):
- # FIXME
+ # TODO Implement signal addition.
raise NotImplementedError()
def difference(self, instrument1, instrumet2, data_labels):
- # FIXME
+ # TODO Implement signal difference.
raise NotImplementedError()
-
-
-
|
b5240580e1786185bc6a889b0106d404cddc78e0
|
AnnotationToXMLConverter/AnnotationToXMLConverter.py
|
AnnotationToXMLConverter/AnnotationToXMLConverter.py
|
import os
from TextFileReader import *
def main():
# get the base directory
base_directory = os.getcwd()
# counter for percentage print
stage_counter = 0
total_stage = len(os.listdir(base_directory + "/Annotation"))
for filename in os.listdir(base_directory + "/Annotation"):
# print the percentage.
stage_counter += 1
print(stage_counter, "/", total_stage, end=" ", sep=" ")
print("(", int(stage_counter / total_stage * 100), "%)", sep="")
# check the given file is a valid txt file.
if not filename.endswith(".txt"):
continue
# get filename without .txt extension
base_filename = truncate_extension(filename, 3)
# read data from the file
image_size = read_image_size(base_directory + "/Image/" + concatenate_extension(base_filename, "jpg"))
annotation_data = read_annotation_data(base_directory + "/Annotation/"
+ concatenate_extension(base_filename, "txt"), image_size)
# write the xml file
write_xml_tag(base_directory + "/XML/" + concatenate_extension(base_filename, "xml"),
concatenate_extension(base_filename, "jpg"), image_size, annotation_data)
if __name__ == "__main__":
main()
|
import os
import time
from TextFileReader import *
def main():
# get the base directory
base_directory = os.getcwd()
# counter for percentage print
stage_counter = 0
total_stage = len(os.listdir(base_directory + "/Annotation"))
start_time = time.time()
for filename in os.listdir(base_directory + "/Annotation"):
# print the percentage.
stage_counter += 1
print(stage_counter, "/", total_stage, end=" ", sep=" ")
print("(", int(stage_counter / total_stage * 100), "%)", sep="")
# check the given file is a valid txt file.
if not filename.endswith(".txt"):
continue
# get filename without .txt extension
base_filename = truncate_extension(filename, 3)
# read data from the file
image_size = read_image_size(base_directory + "/Image/" + concatenate_extension(base_filename, "jpg"))
annotation_data = read_annotation_data(base_directory + "/Annotation/"
+ concatenate_extension(base_filename, "txt"), image_size)
# write the xml file
write_xml_tag(base_directory + "/XML/" + concatenate_extension(base_filename, "xml"),
concatenate_extension(base_filename, "jpg"), image_size, annotation_data)
end_time = time.time()
print()
print("%d annotations converted into xml. Total running time: %lf secs." % (total_stage, end_time - start_time))
# main function
if __name__ == "__main__":
main()
|
Add display for running states
|
Add display for running states
|
Python
|
mit
|
Jamjomjara/snu-artoon,Jamjomjara/snu-artoon
|
---
+++
@@ -1,5 +1,7 @@
import os
+import time
from TextFileReader import *
+
def main():
# get the base directory
@@ -8,6 +10,7 @@
# counter for percentage print
stage_counter = 0
total_stage = len(os.listdir(base_directory + "/Annotation"))
+ start_time = time.time()
for filename in os.listdir(base_directory + "/Annotation"):
# print the percentage.
@@ -31,6 +34,11 @@
write_xml_tag(base_directory + "/XML/" + concatenate_extension(base_filename, "xml"),
concatenate_extension(base_filename, "jpg"), image_size, annotation_data)
+ end_time = time.time()
+ print()
+ print("%d annotations converted into xml. Total running time: %lf secs." % (total_stage, end_time - start_time))
+
+# main function
if __name__ == "__main__":
main()
|
493314bb1d8778c10033f7011cd865526c34b6ce
|
boardinghouse/contrib/template/apps.py
|
boardinghouse/contrib/template/apps.py
|
from django.apps import AppConfig
from django.db import models
from django.dispatch import receiver
from boardinghouse.schema import activate_schema
class BoardingHouseTemplateConfig(AppConfig):
name = 'boardinghouse.contrib.template'
def ready(self):
from boardinghouse import signals
from .models import SchemaTemplate
models.signals.post_save.connect(signals.create_schema,
sender=SchemaTemplate,
dispatch_uid='create-schema-template')
models.signals.post_delete.connect(signals.drop_schema, sender=SchemaTemplate)
@receiver(signals.schema_aware_operation, weak=False)
def execute_on_all_templates(sender, db_table, function, **kwargs):
for schema in SchemaTemplate.objects.all():
activate_schema(schema.schema)
function(*kwargs.get('args', []), **kwargs.get('kwargs', {}))
|
from django.apps import AppConfig
from django.db import models
from django.dispatch import receiver
from boardinghouse.schema import activate_schema
class BoardingHouseTemplateConfig(AppConfig):
name = 'boardinghouse.contrib.template'
def ready(self):
from boardinghouse import signals
from .models import SchemaTemplate
models.signals.post_save.connect(signals.create_schema,
sender=SchemaTemplate,
dispatch_uid='create-schema-template')
models.signals.post_delete.connect(signals.drop_schema, sender=SchemaTemplate)
@receiver(signals.schema_aware_operation, weak=False)
def execute_on_all_templates(sender, db_table, function, **kwargs):
for schema in SchemaTemplate.objects.all():
activate_schema(schema.schema)
print schema.schema
print kwargs
function(*kwargs.get('args', []), **kwargs.get('kwargs', {}))
|
Debug version to check codeship.
|
Debug version to check codeship.
--HG--
branch : schema-templates/fix-codeship-issue
|
Python
|
bsd-3-clause
|
schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse
|
---
+++
@@ -22,4 +22,6 @@
def execute_on_all_templates(sender, db_table, function, **kwargs):
for schema in SchemaTemplate.objects.all():
activate_schema(schema.schema)
+ print schema.schema
+ print kwargs
function(*kwargs.get('args', []), **kwargs.get('kwargs', {}))
|
e8acef69e01e7a38b6497c03db3c993b67fd1e45
|
dependency_to_prioritize/prioritize.py
|
dependency_to_prioritize/prioritize.py
|
class Prioritize(object):
'''
Class which convert dependency relationship to priority level
'''
def __init__(self):
self._priorityLevel = {}
def getPrioritizeLevel(self, item):
if item in self._priorityLevel:
return self._priorityLevel[item]
return -1
def reset(self):
self._priorityLevel.clear()
@staticmethod
def _rmItemRelationship(relationship, item):
rmRelation = set([])
for (f, t) in relationship:
if t == item or f == item:
rmRelation.add((f, t))
relationship -= rmRelation
def convertFrom(self, dependRelations):
"""
Return true when convert is succeed.
The priority level is stored in _priorityLevel.
Input args:
dependRelations - Set of dependency relationship.
example: set([(A, B), (A, C)]) means A depends on B and C.
"""
self.reset()
curLev = 0
depent = dependRelations.copy()
todo = set([])
for (f, t) in depent:
todo.add(f)
todo.add(t)
while todo:
exclude = set([])
for (f, t) in depent:
exclude.add(f)
curLevItem = todo - exclude
if not curLevItem:
print("ERROR: dependency relationship error. Circular dependency exist.")
return False
for item in curLevItem:
Prioritize._rmItemRelationship(depent, item)
self._priorityLevel[item] = curLev
todo -= curLevItem
curLev = curLev + 1
return True
|
import logging
class Prioritize(object):
'''
Class which convert dependency relationship to priority level
'''
def __init__(self):
self._priorityLevel = {}
def getPrioritizeLevel(self, item):
if item in self._priorityLevel:
return self._priorityLevel[item]
return -1
def reset(self):
self._priorityLevel.clear()
@staticmethod
def _rmItemRelationship(relationship, item):
rmRelation = set([])
for (f, t) in relationship:
if t == item or f == item:
rmRelation.add((f, t))
relationship -= rmRelation
def convertFrom(self, dependRelations):
"""
Return true when convert is succeed.
The priority level is stored in _priorityLevel.
Input args:
dependRelations - Set of dependency relationship.
example: set([(A, B), (A, C)]) means A depends on B and C.
"""
self.reset()
curLev = 0
depent = dependRelations.copy()
todo = set([])
for (f, t) in depent:
todo.add(f)
todo.add(t)
while todo:
exclude = set([])
for (f, t) in depent:
exclude.add(f)
curLevItem = todo - exclude
if not curLevItem:
logging.warning("Dependency relationship error. Circular dependency exist.")
return False
for item in curLevItem:
Prioritize._rmItemRelationship(depent, item)
self._priorityLevel[item] = curLev
todo -= curLevItem
curLev = curLev + 1
return True
|
Use logging instead of print logs.
|
Use logging instead of print logs.
|
Python
|
mit
|
scott-zhou/algorithms
|
---
+++
@@ -1,3 +1,5 @@
+import logging
+
class Prioritize(object):
'''
Class which convert dependency relationship to priority level
@@ -42,7 +44,7 @@
exclude.add(f)
curLevItem = todo - exclude
if not curLevItem:
- print("ERROR: dependency relationship error. Circular dependency exist.")
+ logging.warning("Dependency relationship error. Circular dependency exist.")
return False
for item in curLevItem:
Prioritize._rmItemRelationship(depent, item)
|
9e0633207c5fc881821e9be1b8db34bc609d582d
|
censusreporter/config/prod/settings.py
|
censusreporter/config/prod/settings.py
|
from config.base.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ROOT_URLCONF = 'config.prod.urls'
WSGI_APPLICATION = "config.prod.wsgi.application"
ALLOWED_HOSTS = [
'.censusreporter.org',
'.compute-1.amazonaws.com', # allows viewing of instances directly
'cr-prod-409865157.us-east-1.elb.amazonaws.com', # from the load balancer
]
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': 'localhost:11211',
}
}
|
from config.base.settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ROOT_URLCONF = 'config.prod.urls'
WSGI_APPLICATION = "config.prod.wsgi.application"
ALLOWED_HOSTS = [
'.censusreporter.org',
'.compute-1.amazonaws.com', # allows viewing of instances directly
'cr-prod-409865157.us-east-1.elb.amazonaws.com', # from the load balancer
]
# From https://forums.aws.amazon.com/thread.jspa?messageID=423533:
# "The Elastic Load Balancer HTTP health check will use the instance's internal IP."
# From https://dryan.com/articles/elb-django-allowed-hosts/
import requests
EC2_PRIVATE_IP = None
try:
EC2_PRIVATE_IP = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4', timeout=0.01).text
except requests.exceptions.RequestException:
pass
if EC2_PRIVATE_IP:
ALLOWED_HOSTS.append(EC2_PRIVATE_IP)
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': 'localhost:11211',
}
}
|
Add back the EC2 metadata-based private IP fetch for ALLOWED_HOSTS
|
Add back the EC2 metadata-based private IP fetch for ALLOWED_HOSTS
|
Python
|
mit
|
censusreporter/censusreporter,censusreporter/censusreporter,censusreporter/censusreporter,censusreporter/censusreporter
|
---
+++
@@ -12,6 +12,19 @@
'cr-prod-409865157.us-east-1.elb.amazonaws.com', # from the load balancer
]
+# From https://forums.aws.amazon.com/thread.jspa?messageID=423533:
+# "The Elastic Load Balancer HTTP health check will use the instance's internal IP."
+# From https://dryan.com/articles/elb-django-allowed-hosts/
+import requests
+EC2_PRIVATE_IP = None
+try:
+ EC2_PRIVATE_IP = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4', timeout=0.01).text
+except requests.exceptions.RequestException:
+ pass
+
+if EC2_PRIVATE_IP:
+ ALLOWED_HOSTS.append(EC2_PRIVATE_IP)
+
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
|
30f47656f7e288153b452ec355bb17a0c3cda85f
|
chnnlsdmo/chnnlsdmo/settings_heroku.py
|
chnnlsdmo/chnnlsdmo/settings_heroku.py
|
import os
from os.path import abspath, basename, dirname, join, normpath
from sys import path
from .settings import *
DEBUG = True
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
DATABASES['default'] = dj_database_url.config()
ROOT_URLCONF = 'chnnlsdmo.chnnlsdmo.urls'
|
import os
from os.path import abspath, basename, dirname, join, normpath
from sys import path
import dj_database_url
from .settings import *
DEBUG = True
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
DATABASES['default'] = dj_database_url.config()
ROOT_URLCONF = 'chnnlsdmo.chnnlsdmo.urls'
|
Fix up import problem with dj-database-url
|
Fix up import problem with dj-database-url
|
Python
|
bsd-3-clause
|
shearichard/django-channels-demo,shearichard/django-channels-demo,shearichard/django-channels-demo
|
---
+++
@@ -1,6 +1,7 @@
import os
from os.path import abspath, basename, dirname, join, normpath
from sys import path
+import dj_database_url
from .settings import *
|
43a7f6a2130f57bd1e94aa418c4b7d6e085c09ea
|
tests/test_api_info.py
|
tests/test_api_info.py
|
from tests import string
def test_get(test):
def handle_connect(handler):
info = handler.api.get_info()
assert isinstance(info['api_version'], string)
assert isinstance(info['server_timestamp'], string)
if info.get('rest_server_url'):
assert info['websocket_server_url'] is None
assert isinstance(info['rest_server_url'], string)
return
assert isinstance(info['websocket_server_url'], string)
assert info['rest_server_url'] is None
test.run(handle_connect)
def test_get_cluster(test):
# TODO: implement websocket support when API will be added.
test.only_http_implementation()
def handle_connect(handler):
cluster_info = handler.api.get_cluster_info()
assert isinstance(cluster_info['bootstrap.servers'], string)
assert isinstance(cluster_info['zookeeper.connect'], string)
test.run(handle_connect)
|
from tests import string
def test_get(test):
def handle_connect(handler):
info = handler.api.get_info()
assert isinstance(info['api_version'], string)
assert isinstance(info['server_timestamp'], string)
if info.get('rest_server_url'):
assert info['websocket_server_url'] is None
assert isinstance(info['rest_server_url'], string)
return
assert isinstance(info['websocket_server_url'], string)
assert info['rest_server_url'] is None
test.run(handle_connect)
def test_get_cluster(test):
def handle_connect(handler):
cluster_info = handler.api.get_cluster_info()
assert isinstance(cluster_info['bootstrap.servers'], string)
assert isinstance(cluster_info['zookeeper.connect'], string)
test.run(handle_connect)
|
Remove skip of test_get_cluster function for websocket transport
|
Remove skip of test_get_cluster function for websocket transport
|
Python
|
apache-2.0
|
devicehive/devicehive-python
|
---
+++
@@ -18,8 +18,6 @@
def test_get_cluster(test):
- # TODO: implement websocket support when API will be added.
- test.only_http_implementation()
def handle_connect(handler):
cluster_info = handler.api.get_cluster_info()
|
8e623faa44ad767baf4c92596a2501f98dfd2bbb
|
src/masterfile/validators/__init__.py
|
src/masterfile/validators/__init__.py
|
from __future__ import absolute_import
from . import io_validator
from . import index_column_validator
|
from __future__ import absolute_import
from . import ( # noqa
io_validator,
index_column_validator
)
|
Clean up validator package imports
|
Clean up validator package imports
|
Python
|
mit
|
njvack/masterfile
|
---
+++
@@ -1,5 +1,6 @@
from __future__ import absolute_import
-from . import io_validator
-from . import index_column_validator
-
+from . import ( # noqa
+ io_validator,
+ index_column_validator
+)
|
6cfebbf4548db9d52ba0c94997e81196705b4cc8
|
mimesis_project/apps/mimesis/managers.py
|
mimesis_project/apps/mimesis/managers.py
|
from django.db import models
from django.contrib.contenttypes.models import ContentType
class MediaAssociationManager(models.Manager):
def for_model(self, model, content_type=None):
content_type = content_type or ContentType.objects.get_for_model(model)
objects = self.get_query_set().filter(
owner_content_type=content_type,
owner_object_id=model.pk,
)
return objects
|
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import force_unicode
class MediaAssociationManager(models.Manager):
def for_model(self, model, content_type=None):
"""
QuerySet for all media for a particular model (either an instance or
a class).
"""
ct = content_type or ContentType.objects.get_for_model(model)
qs = self.get_query_set().filter(owner_content_type=ct)
if isinstance(model, models.Model):
qs = qs.filter(owner_object_id=force_unicode(model._get_pk_val()))
return qs
|
Allow both instance and model classes in Media.objects.for_model()
|
Allow both instance and model classes in Media.objects.for_model()
|
Python
|
bsd-3-clause
|
eldarion/mimesis,eldarion/mimesis
|
---
+++
@@ -1,14 +1,17 @@
from django.db import models
-
from django.contrib.contenttypes.models import ContentType
-
+from django.utils.encoding import force_unicode
class MediaAssociationManager(models.Manager):
-
+
def for_model(self, model, content_type=None):
- content_type = content_type or ContentType.objects.get_for_model(model)
- objects = self.get_query_set().filter(
- owner_content_type=content_type,
- owner_object_id=model.pk,
- )
- return objects
+ """
+ QuerySet for all media for a particular model (either an instance or
+ a class).
+ """
+ ct = content_type or ContentType.objects.get_for_model(model)
+ qs = self.get_query_set().filter(owner_content_type=ct)
+ if isinstance(model, models.Model):
+ qs = qs.filter(owner_object_id=force_unicode(model._get_pk_val()))
+ return qs
+
|
d760c42b1abb37087e9d5cf97d1bd1f2c0d76279
|
application/__init__.py
|
application/__init__.py
|
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail
from flask_login import LoginManager
from rauth import OAuth2Service
app = Flask(__name__)
BASE_FOLDER = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))
app.static_folder = os.path.join(BASE_FOLDER, 'static')
app.config.from_pyfile('../config')
mail = Mail(app)
db = SQLAlchemy(app)
lm = LoginManager(app)
migrate = Migrate(app, db)
app.config['SQLALC_INSTANCE'] = db
app.config['MAILADDR'] = mail
oauth_alveo = OAuth2Service(
name='alveo',
client_id=app.config['OAUTH_ALVEO_APPID'],
client_secret=app.config['OAUTH_ALVEO_APPSEC'],
authorize_url='https://example.com/oauth/authorize',
access_token_url='https://example.com/oauth/access_token',
base_url='https://example.com/'
)
import application.views
|
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail
from flask_login import LoginManager
from rauth import OAuth2Service
app = Flask(__name__)
BASE_FOLDER = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))
app.static_folder = os.path.join(BASE_FOLDER, 'static')
app.config.from_pyfile('../config')
mail = Mail(app)
db = SQLAlchemy(app)
lm = LoginManager(app)
migrate = Migrate(app, db)
app.config['SQLALC_INSTANCE'] = db
app.config['MAILADDR'] = mail
oauth_alveo = OAuth2Service(
name='alveo',
client_id=app.config['OAUTH_ALVEO_APPID'],
client_secret=app.config['OAUTH_ALVEO_APPSEC'],
authorize_url='https://example.com/oauth/authorize',
access_token_url='https://example.com/oauth/access_token',
base_url='https://example.com/'
)
# Allow cross origin headers only on dev mode
if app.config['DEVELOPMENT'] == True:
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
return response
import application.views
|
Allow cross-origin headers on dev builds
|
Allow cross-origin headers on dev builds
|
Python
|
bsd-3-clause
|
Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber,Alveo/alveo-transcriber
|
---
+++
@@ -29,4 +29,13 @@
base_url='https://example.com/'
)
+# Allow cross origin headers only on dev mode
+if app.config['DEVELOPMENT'] == True:
+ @app.after_request
+ def after_request(response):
+ response.headers.add('Access-Control-Allow-Origin', '*')
+ response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
+ response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
+ return response
+
import application.views
|
680271d4669a309977e5fcfe89f92ea35ebc8d6f
|
common/djangoapps/dark_lang/migrations/0002_data__enable_on_install.py
|
common/djangoapps/dark_lang/migrations/0002_data__enable_on_install.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Converted from the original South migration 0002_enable_on_install.py
#
from django.db import migrations, models
def create_dark_lang_config(apps, schema_editor):
"""
Enable DarkLang by default when it is installed, to prevent accidental
release of testing languages.
"""
dark_lang_model = apps.get_model("dark_lang", "DarkLangConfig")
db_alias = schema_editor.connection.alias
dark_lang_model.objects.using(db_alias).get_or_create(enabled=True)
def remove_dark_lang_config(apps, schema_editor):
"""Write your backwards methods here."""
raise RuntimeError("Cannot reverse this migration.")
class Migration(migrations.Migration):
dependencies = [
('dark_lang', '0001_initial'),
]
operations = [
migrations.RunPython(create_dark_lang_config, remove_dark_lang_config),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# Converted from the original South migration 0002_enable_on_install.py
#
from django.db import migrations, models
def create_dark_lang_config(apps, schema_editor):
"""
Enable DarkLang by default when it is installed, to prevent accidental
release of testing languages.
"""
dark_lang_model = apps.get_model("dark_lang", "DarkLangConfig")
db_alias = schema_editor.connection.alias
if not dark_lang_model.objects.using(db_alias).exists():
dark_lang_model.objects.using(db_alias).create(enabled=True)
def remove_dark_lang_config(apps, schema_editor):
"""Write your backwards methods here."""
raise RuntimeError("Cannot reverse this migration.")
class Migration(migrations.Migration):
dependencies = [
('dark_lang', '0001_initial'),
]
operations = [
migrations.RunPython(create_dark_lang_config, remove_dark_lang_config),
]
|
Correct the darklang migration, since many darklang configs can exist.
|
Correct the darklang migration, since many darklang configs can exist.
|
Python
|
agpl-3.0
|
waheedahmed/edx-platform,hamzehd/edx-platform,ovnicraft/edx-platform,hamzehd/edx-platform,miptliot/edx-platform,Lektorium-LLC/edx-platform,kursitet/edx-platform,Ayub-Khan/edx-platform,marcore/edx-platform,teltek/edx-platform,analyseuc3m/ANALYSE-v1,msegado/edx-platform,franosincic/edx-platform,marcore/edx-platform,kmoocdev2/edx-platform,philanthropy-u/edx-platform,Edraak/circleci-edx-platform,gymnasium/edx-platform,jzoldak/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,EDUlib/edx-platform,edx/edx-platform,cognitiveclass/edx-platform,louyihua/edx-platform,deepsrijit1105/edx-platform,jjmiranda/edx-platform,msegado/edx-platform,stvstnfrd/edx-platform,mbareta/edx-platform-ft,Edraak/edx-platform,antoviaque/edx-platform,louyihua/edx-platform,deepsrijit1105/edx-platform,prarthitm/edxplatform,devs1991/test_edx_docmode,MakeHer/edx-platform,edx-solutions/edx-platform,halvertoluke/edx-platform,ESOedX/edx-platform,a-parhom/edx-platform,EDUlib/edx-platform,nttks/edx-platform,antoviaque/edx-platform,doganov/edx-platform,wwj718/edx-platform,caesar2164/edx-platform,jolyonb/edx-platform,cpennington/edx-platform,CourseTalk/edx-platform,mbareta/edx-platform-ft,solashirai/edx-platform,ampax/edx-platform,chrisndodge/edx-platform,cpennington/edx-platform,procangroup/edx-platform,proversity-org/edx-platform,bigdatauniversity/edx-platform,ovnicraft/edx-platform,cecep-edu/edx-platform,ZLLab-Mooc/edx-platform,antoviaque/edx-platform,Edraak/edraak-platform,JioEducation/edx-platform,doganov/edx-platform,franosincic/edx-platform,devs1991/test_edx_docmode,10clouds/edx-platform,amir-qayyum-khan/edx-platform,shabab12/edx-platform,gsehub/edx-platform,cpennington/edx-platform,hamzehd/edx-platform,kmoocdev2/edx-platform,pabloborrego93/edx-platform,kursitet/edx-platform,fintech-circle/edx-platform,a-parhom/edx-platform,solashirai/edx-platform,Livit/Livit.Learn.EdX,MakeHer/edx-platform,angelapper/edx-platform,UOMx/edx-platform,wwj718/edx-platform,IndonesiaX/edx-platform,inares/edx-platform,appsembler/edx-platform,10clouds/edx-platform,hastexo/edx-platform,romain-li/edx-platform,pomegranited/edx-platform,BehavioralInsightsTeam/edx-platform,IndonesiaX/edx-platform,halvertoluke/edx-platform,Edraak/edx-platform,angelapper/edx-platform,marcore/edx-platform,pepeportela/edx-platform,waheedahmed/edx-platform,10clouds/edx-platform,mbareta/edx-platform-ft,mbareta/edx-platform-ft,synergeticsedx/deployment-wipro,angelapper/edx-platform,inares/edx-platform,nttks/edx-platform,kursitet/edx-platform,RPI-OPENEDX/edx-platform,defance/edx-platform,doganov/edx-platform,eduNEXT/edunext-platform,solashirai/edx-platform,philanthropy-u/edx-platform,tanmaykm/edx-platform,jjmiranda/edx-platform,eduNEXT/edx-platform,eduNEXT/edx-platform,jzoldak/edx-platform,nttks/edx-platform,Edraak/circleci-edx-platform,lduarte1991/edx-platform,kmoocdev2/edx-platform,wwj718/edx-platform,ZLLab-Mooc/edx-platform,pomegranited/edx-platform,miptliot/edx-platform,mitocw/edx-platform,jbzdak/edx-platform,Edraak/circleci-edx-platform,MakeHer/edx-platform,proversity-org/edx-platform,ZLLab-Mooc/edx-platform,halvertoluke/edx-platform,MakeHer/edx-platform,mitocw/edx-platform,pepeportela/edx-platform,marcore/edx-platform,tanmaykm/edx-platform,franosincic/edx-platform,BehavioralInsightsTeam/edx-platform,Endika/edx-platform,zhenzhai/edx-platform,defance/edx-platform,pepeportela/edx-platform,Lektorium-LLC/edx-platform,shabab12/edx-platform,ovnicraft/edx-platform,pepeportela/edx-platform,JioEducation/edx-platform,JioEducation/edx-platform,Endika/edx-platform,Endika/edx-platform,a-parhom/edx-platform,arbrandes/edx-platform,TeachAtTUM/edx-platform,cognitiveclass/edx-platform,hastexo/edx-platform,edx/edx-platform,synergeticsedx/deployment-wipro,CourseTalk/edx-platform,louyihua/edx-platform,Livit/Livit.Learn.EdX,eduNEXT/edx-platform,Edraak/edraak-platform,mitocw/edx-platform,arbrandes/edx-platform,caesar2164/edx-platform,cognitiveclass/edx-platform,edx-solutions/edx-platform,ahmedaljazzar/edx-platform,gymnasium/edx-platform,BehavioralInsightsTeam/edx-platform,ampax/edx-platform,franosincic/edx-platform,CredoReference/edx-platform,cecep-edu/edx-platform,shurihell/testasia,edx-solutions/edx-platform,longmen21/edx-platform,EDUlib/edx-platform,edx-solutions/edx-platform,eduNEXT/edx-platform,amir-qayyum-khan/edx-platform,romain-li/edx-platform,halvertoluke/edx-platform,simbs/edx-platform,Livit/Livit.Learn.EdX,wwj718/edx-platform,caesar2164/edx-platform,TeachAtTUM/edx-platform,JioEducation/edx-platform,eduNEXT/edunext-platform,solashirai/edx-platform,gsehub/edx-platform,solashirai/edx-platform,Ayub-Khan/edx-platform,itsjeyd/edx-platform,bigdatauniversity/edx-platform,RPI-OPENEDX/edx-platform,philanthropy-u/edx-platform,lduarte1991/edx-platform,defance/edx-platform,romain-li/edx-platform,shurihell/testasia,pabloborrego93/edx-platform,msegado/edx-platform,gymnasium/edx-platform,pomegranited/edx-platform,mitocw/edx-platform,RPI-OPENEDX/edx-platform,Edraak/circleci-edx-platform,simbs/edx-platform,pomegranited/edx-platform,Livit/Livit.Learn.EdX,Stanford-Online/edx-platform,zhenzhai/edx-platform,ESOedX/edx-platform,EDUlib/edx-platform,naresh21/synergetics-edx-platform,Stanford-Online/edx-platform,procangroup/edx-platform,simbs/edx-platform,Ayub-Khan/edx-platform,longmen21/edx-platform,raccoongang/edx-platform,hastexo/edx-platform,deepsrijit1105/edx-platform,Edraak/circleci-edx-platform,miptliot/edx-platform,CourseTalk/edx-platform,waheedahmed/edx-platform,itsjeyd/edx-platform,kmoocdev2/edx-platform,procangroup/edx-platform,devs1991/test_edx_docmode,shabab12/edx-platform,antoviaque/edx-platform,edx/edx-platform,gsehub/edx-platform,msegado/edx-platform,deepsrijit1105/edx-platform,appsembler/edx-platform,Edraak/edx-platform,tanmaykm/edx-platform,zhenzhai/edx-platform,Edraak/edx-platform,inares/edx-platform,chrisndodge/edx-platform,alu042/edx-platform,ESOedX/edx-platform,itsjeyd/edx-platform,jbzdak/edx-platform,teltek/edx-platform,miptliot/edx-platform,ovnicraft/edx-platform,RPI-OPENEDX/edx-platform,halvertoluke/edx-platform,inares/edx-platform,chrisndodge/edx-platform,philanthropy-u/edx-platform,UOMx/edx-platform,simbs/edx-platform,a-parhom/edx-platform,longmen21/edx-platform,teltek/edx-platform,nttks/edx-platform,devs1991/test_edx_docmode,ZLLab-Mooc/edx-platform,shurihell/testasia,bigdatauniversity/edx-platform,romain-li/edx-platform,stvstnfrd/edx-platform,jbzdak/edx-platform,Edraak/edx-platform,jbzdak/edx-platform,cecep-edu/edx-platform,synergeticsedx/deployment-wipro,waheedahmed/edx-platform,appsembler/edx-platform,alu042/edx-platform,lduarte1991/edx-platform,hastexo/edx-platform,caesar2164/edx-platform,BehavioralInsightsTeam/edx-platform,cecep-edu/edx-platform,romain-li/edx-platform,bigdatauniversity/edx-platform,ampax/edx-platform,devs1991/test_edx_docmode,bigdatauniversity/edx-platform,Lektorium-LLC/edx-platform,Endika/edx-platform,raccoongang/edx-platform,shabab12/edx-platform,jjmiranda/edx-platform,Stanford-Online/edx-platform,defance/edx-platform,raccoongang/edx-platform,IndonesiaX/edx-platform,analyseuc3m/ANALYSE-v1,teltek/edx-platform,procangroup/edx-platform,TeachAtTUM/edx-platform,pabloborrego93/edx-platform,CredoReference/edx-platform,stvstnfrd/edx-platform,amir-qayyum-khan/edx-platform,jzoldak/edx-platform,arbrandes/edx-platform,IndonesiaX/edx-platform,cpennington/edx-platform,prarthitm/edxplatform,pomegranited/edx-platform,lduarte1991/edx-platform,edx/edx-platform,Edraak/edraak-platform,UOMx/edx-platform,itsjeyd/edx-platform,fintech-circle/edx-platform,eduNEXT/edunext-platform,Stanford-Online/edx-platform,appsembler/edx-platform,kursitet/edx-platform,CredoReference/edx-platform,ahmedaljazzar/edx-platform,prarthitm/edxplatform,jolyonb/edx-platform,jolyonb/edx-platform,jolyonb/edx-platform,devs1991/test_edx_docmode,shurihell/testasia,doganov/edx-platform,proversity-org/edx-platform,Ayub-Khan/edx-platform,ampax/edx-platform,ovnicraft/edx-platform,cognitiveclass/edx-platform,angelapper/edx-platform,simbs/edx-platform,pabloborrego93/edx-platform,synergeticsedx/deployment-wipro,waheedahmed/edx-platform,naresh21/synergetics-edx-platform,alu042/edx-platform,shurihell/testasia,prarthitm/edxplatform,ESOedX/edx-platform,cecep-edu/edx-platform,fintech-circle/edx-platform,stvstnfrd/edx-platform,naresh21/synergetics-edx-platform,zhenzhai/edx-platform,MakeHer/edx-platform,kmoocdev2/edx-platform,gsehub/edx-platform,analyseuc3m/ANALYSE-v1,jjmiranda/edx-platform,kursitet/edx-platform,proversity-org/edx-platform,hamzehd/edx-platform,longmen21/edx-platform,inares/edx-platform,wwj718/edx-platform,tanmaykm/edx-platform,CourseTalk/edx-platform,analyseuc3m/ANALYSE-v1,hamzehd/edx-platform,gymnasium/edx-platform,louyihua/edx-platform,jzoldak/edx-platform,naresh21/synergetics-edx-platform,devs1991/test_edx_docmode,Edraak/edraak-platform,amir-qayyum-khan/edx-platform,ahmedaljazzar/edx-platform,UOMx/edx-platform,msegado/edx-platform,CredoReference/edx-platform,RPI-OPENEDX/edx-platform,Ayub-Khan/edx-platform,IndonesiaX/edx-platform,10clouds/edx-platform,Lektorium-LLC/edx-platform,chrisndodge/edx-platform,TeachAtTUM/edx-platform,jbzdak/edx-platform,raccoongang/edx-platform,ZLLab-Mooc/edx-platform,ahmedaljazzar/edx-platform,devs1991/test_edx_docmode,franosincic/edx-platform,cognitiveclass/edx-platform,fintech-circle/edx-platform,zhenzhai/edx-platform,nttks/edx-platform,alu042/edx-platform,doganov/edx-platform,longmen21/edx-platform
|
---
+++
@@ -14,7 +14,8 @@
dark_lang_model = apps.get_model("dark_lang", "DarkLangConfig")
db_alias = schema_editor.connection.alias
- dark_lang_model.objects.using(db_alias).get_or_create(enabled=True)
+ if not dark_lang_model.objects.using(db_alias).exists():
+ dark_lang_model.objects.using(db_alias).create(enabled=True)
def remove_dark_lang_config(apps, schema_editor):
"""Write your backwards methods here."""
|
8cac0c660eee774c32b87d2511e4d2eeddf0ffe8
|
scripts/slave/chromium/dart_buildbot_run.py
|
scripts/slave/chromium/dart_buildbot_run.py
|
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation scheme.
"""
import sys
from common import chromium_utils
def main():
return chromium_utils.RunCommand(
[sys.executable,
'src/build/buildbot_annotated_steps.py',
])
if __name__ == '__main__':
sys.exit(main())
|
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation scheme.
"""
import os
import sys
from common import chromium_utils
def main():
builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='')
is_release_bot = builder_name.startswith('release')
script = ''
if is_release_bot:
script = 'src/dartium_tools/buildbot_release_annotated_steps.py'
else:
script = 'src/dartium_tools/buildbot_annotated_steps.py'
return chromium_utils.RunCommand([sys.executable, script])
if __name__ == '__main__':
sys.exit(main())
|
Call dartium_tools/buildbot_annotated_steps.py directly, there is no need for moving this as part of the dartium patching process.
|
Call dartium_tools/buildbot_annotated_steps.py directly, there is no need for moving this as part of the dartium patching process.
Additionally, start calling a new script for release builds (there are none yet, but this is what will be used to build the sdk and editor)
TBR=foo
Review URL: https://chromiumcodereview.appspot.com/11466003
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@171512 0039d316-1c4b-4281-b951-d872f2087c98
|
Python
|
bsd-3-clause
|
eunchong/build,eunchong/build,eunchong/build,eunchong/build
|
---
+++
@@ -9,16 +9,21 @@
annotation scheme.
"""
+import os
import sys
from common import chromium_utils
+def main():
+ builder_name = os.getenv('BUILDBOT_BUILDERNAME', default='')
+ is_release_bot = builder_name.startswith('release')
+ script = ''
+ if is_release_bot:
+ script = 'src/dartium_tools/buildbot_release_annotated_steps.py'
+ else:
+ script = 'src/dartium_tools/buildbot_annotated_steps.py'
-def main():
- return chromium_utils.RunCommand(
- [sys.executable,
- 'src/build/buildbot_annotated_steps.py',
- ])
+ return chromium_utils.RunCommand([sys.executable, script])
if __name__ == '__main__':
sys.exit(main())
|
0daae44acaefcc40b749166a1ee4ab8fe6ace368
|
fix_virtualenv.py
|
fix_virtualenv.py
|
from __future__ import unicode_literals, print_function
import os
import argparse
import sys
import shutil
def main():
ap = argparse.ArgumentParser()
ap.add_argument("virtualenv", help="The path to the virtual environment.")
args = ap.parse_args()
target = "{}/include/python{}.{}".format(args.virtualenv, sys.version_info.major, sys.version_info.minor)
try:
source = os.readlink(target)
except:
print(target, "is not a symlink. Perhaps this script has already been run.")
sys.exit(1)
tmp = target + ".tmp"
if os.path.exists(tmp):
shutil.rmtree(tmp)
os.mkdir(tmp)
for i in os.listdir(source):
if i == "pygame_sdl2":
continue
os.symlink(os.path.join(source, i), os.path.join(tmp, i))
os.unlink(target)
os.rename(tmp, target)
if __name__ == "__main__":
main()
|
from __future__ import unicode_literals, print_function
import os
import argparse
import sys
import shutil
import sysconfig
def main():
target = os.path.dirname(sysconfig.get_config_h_filename())
try:
source = os.readlink(target)
except:
print(target, "is not a symlink. Perhaps this script has already been run.")
sys.exit(1)
tmp = target + ".tmp"
if os.path.exists(tmp):
shutil.rmtree(tmp)
os.mkdir(tmp)
for i in os.listdir(source):
if i == "pygame_sdl2":
continue
os.symlink(os.path.join(source, i), os.path.join(tmp, i))
os.unlink(target)
os.rename(tmp, target)
if __name__ == "__main__":
main()
|
Use sysconfig to find the include directory.
|
Use sysconfig to find the include directory.
|
Python
|
lgpl-2.1
|
renpy/pygame_sdl2,renpy/pygame_sdl2,renpy/pygame_sdl2,renpy/pygame_sdl2
|
---
+++
@@ -4,14 +4,10 @@
import argparse
import sys
import shutil
+import sysconfig
def main():
- ap = argparse.ArgumentParser()
- ap.add_argument("virtualenv", help="The path to the virtual environment.")
- args = ap.parse_args()
-
- target = "{}/include/python{}.{}".format(args.virtualenv, sys.version_info.major, sys.version_info.minor)
-
+ target = os.path.dirname(sysconfig.get_config_h_filename())
try:
source = os.readlink(target)
|
703c0f20215e63cb92436875a1798c1becf4b89f
|
tests/test_examples.py
|
tests/test_examples.py
|
import requests
import time
import multiprocessing
from examples import minimal
def test_minimal():
port = minimal.app.get_port()
p = multiprocessing.Process(
target=minimal.app.start_server)
p.start()
try:
time.sleep(3)
r = requests.get('http://127.0.0.1:{port}/hello'.format(port=port))
r.raise_for_status()
assert r.text == 'Hello world\n'
except:
p.terminate()
raise
p.terminate()
|
import requests
import time
import multiprocessing
from examples import minimal
class TestExamples(object):
servers = {}
@classmethod
def setup_class(self):
""" setup any state specific to the execution of the given module."""
self.servers['minimal'] = {'port': minimal.app.get_port()}
self.servers['minimal']['process'] = multiprocessing.Process(
target=minimal.app.start_server)
self.servers['minimal']['process'].start()
time.sleep(3)
@classmethod
def teardown_class(self):
""" teardown any state that was previously setup with a setup_module
method.
"""
self.servers['minimal']['process'].terminate()
def test_minimal(self):
r = requests.get('http://127.0.0.1:{port}/hello'.format(
port=self.servers['minimal']['port']))
r.raise_for_status()
assert r.text == 'Hello world\n'
|
Reorganize tests in a class
|
Reorganize tests in a class
|
Python
|
mit
|
factornado/factornado
|
---
+++
@@ -5,17 +5,27 @@
from examples import minimal
-def test_minimal():
- port = minimal.app.get_port()
- p = multiprocessing.Process(
- target=minimal.app.start_server)
- p.start()
- try:
+class TestExamples(object):
+ servers = {}
+
+ @classmethod
+ def setup_class(self):
+ """ setup any state specific to the execution of the given module."""
+ self.servers['minimal'] = {'port': minimal.app.get_port()}
+ self.servers['minimal']['process'] = multiprocessing.Process(
+ target=minimal.app.start_server)
+ self.servers['minimal']['process'].start()
time.sleep(3)
- r = requests.get('http://127.0.0.1:{port}/hello'.format(port=port))
+
+ @classmethod
+ def teardown_class(self):
+ """ teardown any state that was previously setup with a setup_module
+ method.
+ """
+ self.servers['minimal']['process'].terminate()
+
+ def test_minimal(self):
+ r = requests.get('http://127.0.0.1:{port}/hello'.format(
+ port=self.servers['minimal']['port']))
r.raise_for_status()
assert r.text == 'Hello world\n'
- except:
- p.terminate()
- raise
- p.terminate()
|
4078743923befac99672b67ea53fd1fe11af2e8c
|
tests/test_mjviewer.py
|
tests/test_mjviewer.py
|
"""
Test mujoco viewer.
"""
import unittest
from mujoco_py import mjviewer, mjcore
class MjLibTest(unittest.TestCase):
xml_path = 'tests/models/cartpole.xml'
def setUp(self):
self.width = 100
self.height = 100
self.viewer = mjviewer.MjViewer(visible=False,
init_width=self.width,
init_height=self.height)
def tearDown(self):
self.viewer.finish()
self.viewer = None
def test_start(self):
self.viewer.start()
self.assertTrue(self.viewer.running)
def test_render(self):
self.viewer.start()
model = mjcore.MjModel(self.xml_path)
self.viewer.set_model(model)
(data, width, height) = self.viewer.get_image()
# check image size is consistent
# note that width and height may not equal self.width and self.height
# e.g. on a computer with retina screen,
# the width and height are scaled
self.assertEqual(len(data), 3 * width * height)
# make sure the image is not pitch black
self.assertTrue(any(map(ord, data)))
|
"""
Test mujoco viewer.
"""
import unittest
from mujoco_py import mjviewer, mjcore
class MjLibTest(unittest.TestCase):
xml_path = 'tests/models/cartpole.xml'
def setUp(self):
self.width = 100
self.height = 100
self.viewer = mjviewer.MjViewer(visible=False,
init_width=self.width,
init_height=self.height)
def tearDown(self):
self.viewer.finish()
self.viewer = None
def test_start(self):
self.viewer.start()
self.assertTrue(self.viewer.running)
def test_render(self):
self.viewer.start()
model = mjcore.MjModel(self.xml_path)
self.viewer.set_model(model)
(data, width, height) = self.viewer.get_image()
# check image size is consistent
# note that width and height may not equal self.width and self.height
# e.g. on a computer with retina screen,
# the width and height are scaled
self.assertEqual(len(data), 3 * width * height)
# make sure the image is not pitch black
self.assertTrue(any(map(lambda x: x > 0, data)))
|
Stop using ord with ints
|
Stop using ord with ints
|
Python
|
mit
|
pulkitag/mujoco140-py,pulkitag/mujoco140-py,pulkitag/mujoco140-py
|
---
+++
@@ -38,4 +38,4 @@
# the width and height are scaled
self.assertEqual(len(data), 3 * width * height)
# make sure the image is not pitch black
- self.assertTrue(any(map(ord, data)))
+ self.assertTrue(any(map(lambda x: x > 0, data)))
|
94e13e5d00dc5e2782cf4a1346f098e3c2ad2fc0
|
iotendpoints/endpoints/urls.py
|
iotendpoints/endpoints/urls.py
|
import os
from django.conf.urls import url
from . import views
OBSCURE_URL = r'^{}$'.format(os.environ.get('OBSCURE_URL', 'this_should_be_in_env_var'))
urlpatterns = [
url(r'^$', views.index, name='index'),
url(OBSCURE_URL, views.obscure_dump_request_endpoint, name='dump_request'),
]
|
import os
from django.conf.urls import url
from . import views
DUMMY_OBSCURE_URL = 'this_should_be_in_env_var'
OBSCURE_URL = os.environ.get('OBSCURE_URL', DUMMY_OBSCURE_URL)
if DUMMY_OBSCURE_URL == OBSCURE_URL:
print("Warning: you should set OBSCURE_URL environment variable in this env\n\n")
OBSCURE_URL_PATTERN = r'^{}$'.format(os.environ.get('OBSCURE_URL', OBSCURE_URL))
urlpatterns = [
url(r'^$', views.index, name='index'),
url(OBSCURE_URL_PATTERN, views.obscure_dump_request_endpoint, name='dump_request'),
]
|
Add warning if OBSCURE_URL env var is not set
|
Add warning if OBSCURE_URL env var is not set
|
Python
|
mit
|
aapris/IoT-Web-Experiments
|
---
+++
@@ -2,9 +2,15 @@
from django.conf.urls import url
from . import views
-OBSCURE_URL = r'^{}$'.format(os.environ.get('OBSCURE_URL', 'this_should_be_in_env_var'))
+
+DUMMY_OBSCURE_URL = 'this_should_be_in_env_var'
+OBSCURE_URL = os.environ.get('OBSCURE_URL', DUMMY_OBSCURE_URL)
+if DUMMY_OBSCURE_URL == OBSCURE_URL:
+ print("Warning: you should set OBSCURE_URL environment variable in this env\n\n")
+
+OBSCURE_URL_PATTERN = r'^{}$'.format(os.environ.get('OBSCURE_URL', OBSCURE_URL))
urlpatterns = [
url(r'^$', views.index, name='index'),
- url(OBSCURE_URL, views.obscure_dump_request_endpoint, name='dump_request'),
+ url(OBSCURE_URL_PATTERN, views.obscure_dump_request_endpoint, name='dump_request'),
]
|
8895cd5090bd1014d3fe16976c56d6c24bad0ded
|
parlai/agents/local_human/local_human.py
|
parlai/agents/local_human/local_human.py
|
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
"""Agent does gets the local keyboard input in the act() function.
Example: python examples/eval_model.py -m local_human -t babi:Task1k:1 -dt valid
"""
from parlai.core.agents import Agent
from parlai.core.worlds import display_messages
class LocalHumanAgent(Agent):
def __init__(self, opt, shared=None):
super().__init__(opt)
self.id = 'localHuman'
def observe(self, msg):
print(display_messages([msg]))
def act(self):
obs = self.observation
reply = {}
reply['id'] = self.getID()
reply['text'] = input("Enter Your Reply: ")
return reply
|
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
"""Agent does gets the local keyboard input in the act() function.
Example: python examples/eval_model.py -m local_human -t babi:Task1k:1 -dt valid
"""
from parlai.core.agents import Agent
from parlai.core.worlds import display_messages
class LocalHumanAgent(Agent):
def __init__(self, opt, shared=None):
super().__init__(opt)
self.id = 'localHuman'
self.done = False
def observe(self, msg):
print(display_messages([msg]))
def act(self):
obs = self.observation
reply = {}
reply['id'] = self.getID()
reply['text'] = input("Enter Your Reply: ")
if reply_text == '[DONE]':
reply['episode_done'] = True
self.done = True
reply['text'] = reply_text
return reply
def epoch_done(self):
return self.done
|
Send episode_done=True from local human agent
|
Send episode_done=True from local human agent
|
Python
|
mit
|
facebookresearch/ParlAI,calee88/ParlAI,facebookresearch/ParlAI,facebookresearch/ParlAI,calee88/ParlAI,facebookresearch/ParlAI,calee88/ParlAI,facebookresearch/ParlAI
|
---
+++
@@ -15,6 +15,7 @@
def __init__(self, opt, shared=None):
super().__init__(opt)
self.id = 'localHuman'
+ self.done = False
def observe(self, msg):
print(display_messages([msg]))
@@ -24,4 +25,11 @@
reply = {}
reply['id'] = self.getID()
reply['text'] = input("Enter Your Reply: ")
+ if reply_text == '[DONE]':
+ reply['episode_done'] = True
+ self.done = True
+ reply['text'] = reply_text
return reply
+
+ def epoch_done(self):
+ return self.done
|
a5b7dabcb4450cadd931421738c0ee6f6b63ea4a
|
helpers/config.py
|
helpers/config.py
|
import os
from os.path import join, dirname, abspath
from dotenv import load_dotenv
class Config:
loaded = False
@staticmethod
def load(file_name='../config/.env'):
load_dotenv(join(dirname(__file__), file_name))
env_file_path = abspath(join(dirname(__file__), '../config', os.environ.get('ENV_FILE')))
if not os.path.exists(env_file_path):
raise FileNotFoundError('Can''t find site config file')
load_dotenv(env_file_path)
Config.loaded = True
@staticmethod
def get(key, default_value=None):
if Config.loaded is False:
Config.load()
value = os.environ.get(key)
if not value:
if default_value:
return default_value
raise ValueError('Empty config value, name {}'.format(key))
return value
@staticmethod
def get_seq(key, sep='_'):
if Config.loaded is False:
Config.load()
array = []
counter = 1
while True:
value = os.environ.get('{}{}{}'.format(key, sep, counter))
if value is None or counter > 1000:
break
array.append(value)
counter += 1
if len(array) == 0:
raise ValueError('Empty seq values')
return array
|
import os
from os.path import join, dirname, abspath
from dotenv import load_dotenv
class Config:
max_seq_size = 1000
loaded = False
@staticmethod
def load(file_name='../config/.env'):
load_dotenv(join(dirname(__file__), file_name))
env_file_path = abspath(join(dirname(__file__), '../config', os.environ.get('ENV_FILE')))
if not os.path.exists(env_file_path):
raise FileNotFoundError('Can''t find site config file')
load_dotenv(env_file_path)
Config.loaded = True
@staticmethod
def get(key, default_value=None):
if Config.loaded is False:
Config.load()
value = os.environ.get(key)
if not value:
if default_value is not None:
return default_value
raise ValueError('Empty config value, name {}'.format(key))
return value
@staticmethod
def get_seq(key, sep='_'):
if Config.loaded is False:
Config.load()
array = []
counter = 1
while True:
value = os.environ.get('{}{}{}'.format(key, sep, counter))
if value is None or counter > Config.max_seq_size:
break
array.append(value)
counter += 1
if len(array) == 0:
raise ValueError('Empty seq values')
return array
|
Move seq size to const
|
Move seq size to const
|
Python
|
mit
|
Holovin/D_GrabDemo
|
---
+++
@@ -4,6 +4,7 @@
class Config:
+ max_seq_size = 1000
loaded = False
@staticmethod
@@ -25,7 +26,7 @@
value = os.environ.get(key)
if not value:
- if default_value:
+ if default_value is not None:
return default_value
raise ValueError('Empty config value, name {}'.format(key))
@@ -43,7 +44,7 @@
while True:
value = os.environ.get('{}{}{}'.format(key, sep, counter))
- if value is None or counter > 1000:
+ if value is None or counter > Config.max_seq_size:
break
array.append(value)
|
1ae097291a42022013969287ecb91bafa60ae625
|
examples/send_transfer.py
|
examples/send_transfer.py
|
# coding=utf-8
"""
Example script that shows how to use PyOTA to send a transfer to an address.
"""
from iota import *
# Create the API instance.
api =\
Iota(
# URI of a locally running node.
'http://localhost:14265/',
# Seed used for cryptographic functions.
seed = b'SEED9GOES9HERE'
)
# For more information, see :py:meth:`Iota.send_transfer`.
api.send_transfer(
depth = 100,
# One or more :py:class:`ProposedTransaction` objects to add to the
# bundle.
transfers = [
ProposedTransaction(
# Recipient of the transfer.
address =
Address(
b'TESTVALUE9DONTUSEINPRODUCTION99999FBFFTG'
b'QFWEHEL9KCAFXBJBXGE9HID9XCOHFIDABHDG9AHDR'
),
# Amount of IOTA to transfer.
# This value may be zero.
value = 1,
# Optional tag to attach to the transfer.
tag = Tag(b'EXAMPLE'),
# Optional message to include with the transfer.
message = TryteString.from_string('Hello!'),
),
],
)
|
# coding=utf-8
"""
Example script that shows how to use PyOTA to send a transfer to an address.
"""
from iota import *
SEED1 = b"THESEEDOFTHEWALLETSENDINGGOESHERE999999999999999999999999999999999999999999999999"
ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2 = b"RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVEL2999999999999999999999999999999"
# Create the API instance.
api =\
Iota(
# URI of a locally running node.
'http://localhost:14265/',
# Seed used for cryptographic functions.
seed = SEED1
)
# For more information, see :py:meth:`Iota.send_transfer`.
api.send_transfer(
depth = 100,
# One or more :py:class:`ProposedTransaction` objects to add to the
# bundle.
transfers = [
ProposedTransaction(
# Recipient of the transfer.
address =
Address(
ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2,
),
# Amount of IOTA to transfer.
# This value may be zero.
value = 1,
# Optional tag to attach to the transfer.
tag = Tag(b'EXAMPLE'),
# Optional message to include with the transfer.
message = TryteString.from_string('Hello!'),
),
],
)
|
Clarify Address usage in send example
|
Clarify Address usage in send example
Improved the script to explain the recipient address a little better.
Changed the address concat to a reference to a specific kind of Iota address.
This is loosely inspired by the JAVA sen transaction test case.
|
Python
|
mit
|
iotaledger/iota.lib.py
|
---
+++
@@ -4,6 +4,8 @@
"""
from iota import *
+SEED1 = b"THESEEDOFTHEWALLETSENDINGGOESHERE999999999999999999999999999999999999999999999999"
+ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2 = b"RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVEL2999999999999999999999999999999"
# Create the API instance.
api =\
@@ -12,7 +14,7 @@
'http://localhost:14265/',
# Seed used for cryptographic functions.
- seed = b'SEED9GOES9HERE'
+ seed = SEED1
)
# For more information, see :py:meth:`Iota.send_transfer`.
@@ -26,8 +28,7 @@
# Recipient of the transfer.
address =
Address(
- b'TESTVALUE9DONTUSEINPRODUCTION99999FBFFTG'
- b'QFWEHEL9KCAFXBJBXGE9HID9XCOHFIDABHDG9AHDR'
+ ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2,
),
# Amount of IOTA to transfer.
|
a029c6f4fce36693a9dee53ff8bc797890cfe71e
|
plugins/basic_info_plugin.py
|
plugins/basic_info_plugin.py
|
import string
import textwrap
from plugins import BasePlugin
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
name = 'BasicInfoPlugin'
short_description = 'Basic info:'
default = True
description = textwrap.dedent('''
This plugin provides some basic info about the string such as:
- Length
- Presence of alpha/digits/raw bytes
''')
def handle(self):
result = ''
for s in self.args['STRING']:
if len(self.args['STRING']) > 1:
result += '{0}:\n'.format(s)
result += 'len: {0}\n'.format(len(s))
result += 'number of digits: {0}\n'.format(sum(x.isdigit() for x in s))
result += 'number of alpha: {0}\n'.format(sum(x.isalpha() for x in s))
result += 'number of unprintable: {0}\n'.format(sum(x in string.printable for x in s))
return result
|
import string
import textwrap
from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
name = 'BasicInfoPlugin'
short_description = 'Basic info:'
default = True
description = textwrap.dedent('''
This plugin provides some basic info about the string such as:
- Length
- Presence of alpha/digits/raw bytes
''')
def handle(self):
result = ''
for s in self.args['STRING']:
if len(self.args['STRING']) > 1:
result += '{0}:\n'.format(s)
table = VeryPrettyTable()
table.field_names = ['Length', '# Digits', '# Alpha', '# unprintable']
table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s),
sum(x in string.printable for x in s)))
result += str(table) + '\n'
return result
|
Use table instead of separate lines
|
Use table instead of separate lines
|
Python
|
mit
|
Sakartu/stringinfo
|
---
+++
@@ -1,5 +1,6 @@
import string
import textwrap
+from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
__author__ = 'peter'
@@ -20,9 +21,10 @@
for s in self.args['STRING']:
if len(self.args['STRING']) > 1:
result += '{0}:\n'.format(s)
- result += 'len: {0}\n'.format(len(s))
- result += 'number of digits: {0}\n'.format(sum(x.isdigit() for x in s))
- result += 'number of alpha: {0}\n'.format(sum(x.isalpha() for x in s))
- result += 'number of unprintable: {0}\n'.format(sum(x in string.printable for x in s))
+ table = VeryPrettyTable()
+ table.field_names = ['Length', '# Digits', '# Alpha', '# unprintable']
+ table.add_row((len(s), sum(x.isdigit() for x in s), sum(x.isalpha() for x in s),
+ sum(x in string.printable for x in s)))
+ result += str(table) + '\n'
return result
|
1ff53eade7c02a92f5f09c371b766e7b176a90a1
|
speyer/ingest/gerrit.py
|
speyer/ingest/gerrit.py
|
from __future__ import print_function
import select
import paramiko
class GerritEvents(object):
def __init__(self, userid, host, key=None):
self.userid = userid
self.host = host
self.port = 29418
self.key = key
def _read_events(self, stream, use_poll=False):
if not use_poll:
yield stream.readline().strip()
poller = select.poll()
poller.register(stream.channel)
while True:
for fd, event in poller.poll():
if fd == stream.channel.fileno():
if event == select.POLLIN:
yield stream.readline().strip()
else:
raise Exception('Non-POLLIN event on stdout!')
@property
def events(self):
client = paramiko.SSHClient()
client.load_system_host_keys()
connargs = {
'hostname': self.host,
'port': self.port,
'username': self.userid
}
if self.key:
connargs['pkey'] = self.key
client.connect(**connargs)
stdin, stdout, stderr = client.exec_command('gerrit stream-events')
for event in self._read_events(stdout, use_poll=True):
yield event
|
from __future__ import print_function
import select
import paramiko
class GerritEvents(object):
def __init__(self, userid, host, key=None):
self.userid = userid
self.host = host
self.port = 29418
self.key = key
def _read_events(self, stream, use_poll=False):
if not use_poll:
yield stream.readline().strip()
poller = select.poll()
poller.register(stream.channel)
while True:
for fd, event in poller.poll():
if fd == stream.channel.fileno():
if event == select.POLLIN:
yield stream.readline().strip()
else:
raise Exception('Non-POLLIN event on stdout!')
@property
def events(self):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
connargs = {
'hostname': self.host,
'port': self.port,
'username': self.userid
}
if self.key:
connargs['pkey'] = self.key
client.connect(**connargs)
stdin, stdout, stderr = client.exec_command('gerrit stream-events')
for event in self._read_events(stdout, use_poll=True):
yield event
|
Allow connecting to unknown hosts but warn
|
Allow connecting to unknown hosts but warn
|
Python
|
apache-2.0
|
locke105/streaming-python-testdrive
|
---
+++
@@ -32,6 +32,7 @@
def events(self):
client = paramiko.SSHClient()
client.load_system_host_keys()
+ client.set_missing_host_key_policy(paramiko.WarningPolicy())
connargs = {
'hostname': self.host,
|
8614f782196a86507c1b659f0b1d9ee293ddc309
|
virtool/job_classes.py
|
virtool/job_classes.py
|
import virtool.subtraction
import virtool.virus_index
import virtool.sample_create
import virtool.job_analysis
import virtool.job_dummy
#: A dict containing :class:`~.job.Job` subclasses keyed by their task names.
TASK_CLASSES = {
"rebuild_index": virtool.virus_index.RebuildIndex,
"pathoscope_bowtie": virtool.job_analysis.PathoscopeBowtie,
"nuvs": virtool.job_analysis.NuVs,
"add_subtraction": virtool.subtraction.CreateSubtraction,
"create_sample": virtool.sample_create.CreateSample,
"dummy": virtool.job_dummy.DummyJob
}
|
import virtool.subtraction
import virtool.virus_index
import virtool.sample_create
import virtool.job_analysis
import virtool.job_dummy
#: A dict containing :class:`~.job.Job` subclasses keyed by their task names.
TASK_CLASSES = {
"rebuild_index": virtool.virus_index.RebuildIndex,
"pathoscope_bowtie": virtool.job_analysis.PathoscopeBowtie,
"nuvs": virtool.job_analysis.NuVs,
"create_subtraction": virtool.subtraction.CreateSubtraction,
"create_sample": virtool.sample_create.CreateSample,
"dummy": virtool.job_dummy.DummyJob
}
|
Change job class name from add_host to create_subtraction
|
Change job class name from add_host to create_subtraction
|
Python
|
mit
|
igboyes/virtool,virtool/virtool,virtool/virtool,igboyes/virtool
|
---
+++
@@ -10,7 +10,7 @@
"rebuild_index": virtool.virus_index.RebuildIndex,
"pathoscope_bowtie": virtool.job_analysis.PathoscopeBowtie,
"nuvs": virtool.job_analysis.NuVs,
- "add_subtraction": virtool.subtraction.CreateSubtraction,
+ "create_subtraction": virtool.subtraction.CreateSubtraction,
"create_sample": virtool.sample_create.CreateSample,
"dummy": virtool.job_dummy.DummyJob
}
|
df0b04ec5142631a0fb1e2051b622f8c2568fec6
|
pyoracc/model/oraccobject.py
|
pyoracc/model/oraccobject.py
|
from mako.template import Template
class OraccObject(object):
template = Template(r"""@${objecttype}
% for child in children:
${child.serialize()}
% endfor""", output_encoding='utf-8')
def __init__(self, objecttype):
self.objecttype = objecttype
self.children = []
self.query = False
self.broken = False
self.remarkable = False
self.collated = False
def __str__(self):
return OraccObject.template.render_unicode(**vars(self))
def serialize(self):
return OraccObject.template.render_unicode(**vars(self))
|
from mako.template import Template
class OraccObject(object):
template = Template(r"""@${objecttype}
% for child in children:
${child.serialize()}
% endfor""", output_encoding='utf-8')
def __init__(self, objecttype):
self.objecttype = objecttype
self.children = []
self.query = False
self.broken = False
self.remarkable = False
self.collated = False
def __str__(self):
return OraccObject.template.render_unicode(**vars(self))
def serialize(self):
return OraccObject.template.render_unicode(**vars(self))
|
Remove trailing space after object type.
|
Remove trailing space after object type.
|
Python
|
mit
|
UCL/pyoracc
|
---
+++
@@ -2,7 +2,7 @@
class OraccObject(object):
- template = Template(r"""@${objecttype}
+ template = Template(r"""@${objecttype}
% for child in children:
${child.serialize()}
% endfor""", output_encoding='utf-8')
|
5954196d3c81083f7f94eca147fe1a76a6dfb301
|
vc_vidyo/indico_vc_vidyo/blueprint.py
|
vc_vidyo/indico_vc_vidyo/blueprint.py
|
# This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from indico.core.plugins import IndicoPluginBlueprint
from indico_vc_vidyo.controllers import RHVidyoRoomOwner
blueprint = IndicoPluginBlueprint('vc_vidyo', 'indico_vc_vidyo')
# Room management
blueprint.add_url_rule('/event/<confId>/manage/videoconference/vidyo/<int:event_vc_room_id>/room-owner/',
'set_room_owner', RHVidyoRoomOwner, methods=('POST',), defaults={'service': 'vidyo'})
|
# This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
from indico.core.plugins import IndicoPluginBlueprint
from indico_vc_vidyo.controllers import RHVidyoRoomOwner
blueprint = IndicoPluginBlueprint('vc_vidyo', 'indico_vc_vidyo')
# Room management
# using any(vidyo) instead of defaults since the event vc room locator
# includes the service and normalization skips values provided in 'defaults'
blueprint.add_url_rule('/event/<confId>/manage/videoconference/<any(vidyo):service>/<int:event_vc_room_id>/room-owner',
'set_room_owner', RHVidyoRoomOwner, methods=('POST',))
|
Fix "make me room owner"
|
VC/Vidyo: Fix "make me room owner"
|
Python
|
mit
|
ThiefMaster/indico-plugins,ThiefMaster/indico-plugins,ThiefMaster/indico-plugins,indico/indico-plugins,ThiefMaster/indico-plugins,indico/indico-plugins,indico/indico-plugins,indico/indico-plugins
|
---
+++
@@ -23,5 +23,7 @@
blueprint = IndicoPluginBlueprint('vc_vidyo', 'indico_vc_vidyo')
# Room management
-blueprint.add_url_rule('/event/<confId>/manage/videoconference/vidyo/<int:event_vc_room_id>/room-owner/',
- 'set_room_owner', RHVidyoRoomOwner, methods=('POST',), defaults={'service': 'vidyo'})
+# using any(vidyo) instead of defaults since the event vc room locator
+# includes the service and normalization skips values provided in 'defaults'
+blueprint.add_url_rule('/event/<confId>/manage/videoconference/<any(vidyo):service>/<int:event_vc_room_id>/room-owner',
+ 'set_room_owner', RHVidyoRoomOwner, methods=('POST',))
|
e1a1a19408c052c93ccc1684b2e1408ba229addc
|
tests/test_cookiecutter_invocation.py
|
tests/test_cookiecutter_invocation.py
|
# -*- coding: utf-8 -*-
"""
test_cookiecutter_invocation
----------------------------
Tests to make sure that cookiecutter can be called from the cli without
using the entry point set up for the package.
"""
import pytest
import subprocess
def test_should_raise_error_without_template_arg(capfd):
with pytest.raises(subprocess.CalledProcessError):
subprocess.check_call(['python', '-m', 'cookiecutter.cli'])
_, err = capfd.readouterr()
exp_message = 'Error: Missing argument "template".'
assert exp_message in err
|
# -*- coding: utf-8 -*-
"""
test_cookiecutter_invocation
----------------------------
Tests to make sure that cookiecutter can be called from the cli without
using the entry point set up for the package.
"""
import os
import pytest
import subprocess
from cookiecutter import utils
def test_should_raise_error_without_template_arg(capfd):
with pytest.raises(subprocess.CalledProcessError):
subprocess.check_call(['python', '-m', 'cookiecutter.cli'])
_, err = capfd.readouterr()
exp_message = 'Error: Missing argument "template".'
assert exp_message in err
@pytest.fixture
def project_dir(request):
"""Remove the rendered project directory created by the test."""
rendered_dir = 'fake-project-templated'
def remove_generated_project():
if os.path.isdir(rendered_dir):
utils.rmtree(rendered_dir)
request.addfinalizer(remove_generated_project)
return rendered_dir
def test_should_invoke_main(project_dir):
subprocess.check_call([
'python',
'-m',
'cookiecutter.cli',
'tests/fake-repo-tmpl',
'--no-input'
])
assert os.path.isdir(project_dir)
|
Implement test to make sure cookiecutter main is called
|
Implement test to make sure cookiecutter main is called
|
Python
|
bsd-3-clause
|
michaeljoseph/cookiecutter,luzfcb/cookiecutter,benthomasson/cookiecutter,atlassian/cookiecutter,kkujawinski/cookiecutter,christabor/cookiecutter,audreyr/cookiecutter,Springerle/cookiecutter,takeflight/cookiecutter,cguardia/cookiecutter,moi65/cookiecutter,christabor/cookiecutter,pjbull/cookiecutter,michaeljoseph/cookiecutter,ramiroluz/cookiecutter,ramiroluz/cookiecutter,pjbull/cookiecutter,Springerle/cookiecutter,hackebrot/cookiecutter,sp1rs/cookiecutter,benthomasson/cookiecutter,takeflight/cookiecutter,dajose/cookiecutter,agconti/cookiecutter,atlassian/cookiecutter,dajose/cookiecutter,venumech/cookiecutter,venumech/cookiecutter,kkujawinski/cookiecutter,stevepiercy/cookiecutter,willingc/cookiecutter,agconti/cookiecutter,luzfcb/cookiecutter,Vauxoo/cookiecutter,moi65/cookiecutter,stevepiercy/cookiecutter,cguardia/cookiecutter,Vauxoo/cookiecutter,terryjbates/cookiecutter,terryjbates/cookiecutter,sp1rs/cookiecutter,audreyr/cookiecutter,willingc/cookiecutter,hackebrot/cookiecutter
|
---
+++
@@ -8,8 +8,11 @@
using the entry point set up for the package.
"""
+import os
import pytest
import subprocess
+
+from cookiecutter import utils
def test_should_raise_error_without_template_arg(capfd):
@@ -19,3 +22,27 @@
_, err = capfd.readouterr()
exp_message = 'Error: Missing argument "template".'
assert exp_message in err
+
+
+@pytest.fixture
+def project_dir(request):
+ """Remove the rendered project directory created by the test."""
+ rendered_dir = 'fake-project-templated'
+
+ def remove_generated_project():
+ if os.path.isdir(rendered_dir):
+ utils.rmtree(rendered_dir)
+ request.addfinalizer(remove_generated_project)
+
+ return rendered_dir
+
+
+def test_should_invoke_main(project_dir):
+ subprocess.check_call([
+ 'python',
+ '-m',
+ 'cookiecutter.cli',
+ 'tests/fake-repo-tmpl',
+ '--no-input'
+ ])
+ assert os.path.isdir(project_dir)
|
5eaca14a3ddf7515f5b855aee4b58d21048ca9a9
|
avena/utils.py
|
avena/utils.py
|
#!/usr/bin/env python
from os.path import exists, splitext
from random import randint
_depth = lambda x, y, z=1: z
_invert_dict = lambda d: dict((v, k) for k, v in list(d.items()))
_PREFERRED_RGB = {
'R': 0,
'G': 1,
'B': 2,
}
def depth(array):
'''Return the depth (the third dimension) of an array.'''
return _depth(*array.shape)
def rand_filename(filename, ext=None):
'''Return a unique file name based on the given file name.'''
file_name, file_ext = splitext(filename)
if ext is None:
ext = file_ext
while True:
rand_file_name = file_name
rand_file_name += '-'
rand_file_name += str(randint(0, 10000))
rand_file_name += ext
if not exists(rand_file_name):
break
return rand_file_name
def swap_rgb(img, current, to):
'''Swap the RBG channels of an image array.'''
if depth(img) == 3 and not current == to:
current_indices = list(map(current.get, ('R', 'G', 'B')))
to_indices = list(map(to.get, ('R', 'G', 'B')))
img[:, :, current_indices] = img[:, :, to_indices]
if __name__ == '__main__':
pass
|
#!/usr/bin/env python
from os.path import exists, splitext
from random import randint
def _depth(x, y, z=1):
return z
_invert_dict = lambda d: dict((v, k) for k, v in list(d.items()))
_PREFERRED_RGB = {
'R': 0,
'G': 1,
'B': 2,
}
def depth(array):
'''Return the depth (the third dimension) of an array.'''
return _depth(*array.shape)
def rand_filename(filename, ext=None):
'''Return a unique file name based on the given file name.'''
file_name, file_ext = splitext(filename)
if ext is None:
ext = file_ext
while True:
rand_file_name = file_name
rand_file_name += '-'
rand_file_name += str(randint(0, 10000))
rand_file_name += ext
if not exists(rand_file_name):
break
return rand_file_name
def swap_rgb(img, current, to):
'''Swap the RBG channels of an image array.'''
if depth(img) == 3 and not current == to:
current_indices = list(map(current.get, ('R', 'G', 'B')))
to_indices = list(map(to.get, ('R', 'G', 'B')))
img[:, :, current_indices] = img[:, :, to_indices]
if __name__ == '__main__':
pass
|
Use a function instead of a lambda expression.
|
Use a function instead of a lambda expression.
|
Python
|
isc
|
eliteraspberries/avena
|
---
+++
@@ -4,7 +4,8 @@
from random import randint
-_depth = lambda x, y, z=1: z
+def _depth(x, y, z=1):
+ return z
_invert_dict = lambda d: dict((v, k) for k, v in list(d.items()))
|
e36caab07168d3884b55970e5fa6ee5146df1b1c
|
src/waldur_mastermind/booking/processors.py
|
src/waldur_mastermind/booking/processors.py
|
import mock
BookingCreateProcessor = mock.MagicMock()
BookingDeleteProcessor = mock.MagicMock()
|
from waldur_mastermind.marketplace import processors
class BookingCreateProcessor(processors.CreateResourceProcessor):
def get_serializer_class(self):
pass
def get_viewset(self):
pass
def get_post_data(self):
pass
def get_scope_from_response(self, response):
pass
class BookingDeleteProcessor(processors.CreateResourceProcessor):
def get_viewset(self):
pass
def get_post_data(self):
pass
def get_scope_from_response(self, response):
pass
def get_serializer_class(self):
pass
|
Fix using mock in production
|
Fix using mock in production [WAL-2530]
|
Python
|
mit
|
opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur
|
---
+++
@@ -1,4 +1,29 @@
-import mock
+from waldur_mastermind.marketplace import processors
-BookingCreateProcessor = mock.MagicMock()
-BookingDeleteProcessor = mock.MagicMock()
+
+class BookingCreateProcessor(processors.CreateResourceProcessor):
+ def get_serializer_class(self):
+ pass
+
+ def get_viewset(self):
+ pass
+
+ def get_post_data(self):
+ pass
+
+ def get_scope_from_response(self, response):
+ pass
+
+
+class BookingDeleteProcessor(processors.CreateResourceProcessor):
+ def get_viewset(self):
+ pass
+
+ def get_post_data(self):
+ pass
+
+ def get_scope_from_response(self, response):
+ pass
+
+ def get_serializer_class(self):
+ pass
|
48f15196bdbdf6c86491ff4ab966f4ae82932b80
|
libact/labelers/interactive_labeler.py
|
libact/labelers/interactive_labeler.py
|
"""Interactive Labeler
This module includes an InteractiveLabeler.
"""
import matplotlib.pyplot as plt
from libact.base.interfaces import Labeler
from libact.utils import inherit_docstring_from
class InteractiveLabeler(Labeler):
"""Interactive Labeler
InteractiveLabeler is a Labeler object that shows the feature through image
using matplotlib and lets human label each feature through command line
interface.
Parameters
----------
label_name: list
Let the label space be from 0 to len(label_name)-1, this list
corresponds to each label's name.
"""
def __init__(self, **kwargs):
self.label_name = kwargs.pop('label_name', None)
@inherit_docstring_from(Labeler)
def label(self, feature):
plt.imshow(feature, cmap=plt.cm.gray_r, interpolation='nearest')
plt.draw()
banner = "Enter the associated label with the image: "
if self.label_name is not None:
banner += str(self.label_name) + ' '
lbl = input(banner)
while (self.label_name is not None) and (lbl not in self.label_name):
print('Invalid label, please re-enter the associated label.')
lbl = input(banner)
return self.label_name.index(lbl)
|
"""Interactive Labeler
This module includes an InteractiveLabeler.
"""
import matplotlib.pyplot as plt
from libact.base.interfaces import Labeler
from libact.utils import inherit_docstring_from
class InteractiveLabeler(Labeler):
"""Interactive Labeler
InteractiveLabeler is a Labeler object that shows the feature through image
using matplotlib and lets human label each feature through command line
interface.
Parameters
----------
label_name: list
Let the label space be from 0 to len(label_name)-1, this list
corresponds to each label's name.
"""
def __init__(self, **kwargs):
self.label_name = kwargs.pop('label_name', None)
@inherit_docstring_from(Labeler)
def label(self, feature):
plt.imshow(feature, cmap=plt.cm.gray_r, interpolation='nearest')
plt.draw()
banner = "Enter the associated label with the image: "
if self.label_name is not None:
banner += str(self.label_name) + ' '
try: input = raw_input # input fix for python 2.x
except NameError: pass
lbl = input(banner)
while (self.label_name is not None) and (lbl not in self.label_name):
print('Invalid label, please re-enter the associated label.')
lbl = input(banner)
return self.label_name.index(lbl)
|
Fix compatibility issues with "input()" in python2
|
Fix compatibility issues with "input()" in python2
override input with raw_input if in python2
|
Python
|
bsd-2-clause
|
ntucllab/libact,ntucllab/libact,ntucllab/libact
|
---
+++
@@ -36,6 +36,10 @@
if self.label_name is not None:
banner += str(self.label_name) + ' '
+
+ try: input = raw_input # input fix for python 2.x
+ except NameError: pass
+
lbl = input(banner)
while (self.label_name is not None) and (lbl not in self.label_name):
|
c26ebf61079fc783d23000ee4e023e1111d8a75e
|
blog/manage.py
|
blog/manage.py
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
if socket.gethostname() == 'blog':
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.production")
else:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.local"
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
if socket.gethostname() == 'blog':
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.base")
else:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.base")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
Switch settings used to just settings/base.py
|
Switch settings used to just settings/base.py
|
Python
|
bsd-3-clause
|
giovannicode/giovanniblog,giovannicode/giovanniblog
|
---
+++
@@ -4,9 +4,9 @@
if __name__ == "__main__":
if socket.gethostname() == 'blog':
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.production")
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.base")
else:
- os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.local"
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.base")
from django.core.management import execute_from_command_line
|
270b1a1d970d866b5de7e3b742166e2e0d13c513
|
patrol_mission.py
|
patrol_mission.py
|
#!/usr/bin/python
"""
Cyril Robin -- LAAS-CNRS -- 2014
TODO Descriptif
"""
from mission import *
from constant import *
from sys import argv, exit
from timer import Timer
if __name__ == "__main__":
with Timer('Loading mission file'):
json_mission = loaded_mission(argv[1])
mission = Mission ( json_mission )
#with Timer('Sampling observable points'):
#mission.sample_objective()
#with Timer('Sampling positions'):
#mission.sample_all_positions()
#print "Solving..."
#with Timer('Solving'):
#mission.solve()
##mission.solve('Position-based TSP')
#print "Displaying..."
#for robot in mission.team:
#robot.display_weighted_map()
#mission.display_situation()
#print "Updating poses and map"
#mission.update_poses()
#mission.update_map()
print "Starting Loop !"
#mission.loop_once()
mission.loop(10)
mission.update()
mission.display_situation()
print "Done."
|
#!/usr/bin/python
"""
Cyril Robin -- LAAS-CNRS -- 2014
TODO Descriptif
"""
from mission import *
from constant import *
from sys import argv, exit
from timer import Timer
if __name__ == "__main__":
with Timer('Loading mission file'):
json_mission = loaded_mission(argv[1])
mission = Mission ( json_mission )
#with Timer('Sampling observable points'):
#mission.sample_objective()
#with Timer('Sampling positions'):
#mission.sample_all_positions()
#print "Solving..."
#with Timer('Solving'):
#mission.solve()
##mission.solve('Position-based TSP')
#print "Displaying..."
#for robot in mission.team:
#robot.display_weighted_map()
#mission.display_situation()
#print "Updating poses and map"
#mission.update_poses()
#mission.update_map()
print "Starting Loop !"
#mission.loop_once()
#mission.loop(5,True)
mission.loop(10)
mission.update()
#for robot in mission.team:
#robot.display_weighted_map()
mission.display_situation()
mission.print_metrics()
print "Done."
|
Update launcher for new features
|
Update launcher for new features
|
Python
|
bsd-3-clause
|
cyrobin/patrolling,cyrobin/patrolling
|
---
+++
@@ -40,9 +40,14 @@
print "Starting Loop !"
#mission.loop_once()
+ #mission.loop(5,True)
mission.loop(10)
mission.update()
+ #for robot in mission.team:
+ #robot.display_weighted_map()
mission.display_situation()
+ mission.print_metrics()
+
print "Done."
|
f5c41e3f85db152028dab7026c13958269e7b6d9
|
nazs/test_settings.py
|
nazs/test_settings.py
|
from .settings import * # noqa
DEBUG = True
TEMPLATE_DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite',
},
'volatile': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
# Non root user (root under development)
RUN_AS_USER = 'nobody'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': '%(asctime)s [%(levelname)s] %(module)s - %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'console': {
'level': 'DEBUG',
'formatter': 'default',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'': {
'handlers': ['null'],
'level': 'DEBUG',
'propagate': True,
},
'django.db.backends': {
'handlers': ['null'],
'propagate': False,
'level': 'DEBUG',
},
}
}
|
from .settings import * # noqa
DEBUG = True
TEMPLATE_DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db.sqlite',
},
'volatile': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
# Non root user, ROOT for current one
RUN_AS_USER = None
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': '%(asctime)s [%(levelname)s] %(module)s - %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'console': {
'level': 'DEBUG',
'formatter': 'default',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'': {
'handlers': ['null'],
'level': 'DEBUG',
'propagate': True,
},
'django.db.backends': {
'handlers': ['null'],
'propagate': False,
'level': 'DEBUG',
},
}
}
|
Use current user for tests
|
Use current user for tests
|
Python
|
agpl-3.0
|
exekias/droplet,exekias/droplet,exekias/droplet
|
---
+++
@@ -14,8 +14,8 @@
}
}
-# Non root user (root under development)
-RUN_AS_USER = 'nobody'
+# Non root user, ROOT for current one
+RUN_AS_USER = None
LOGGING = {
'version': 1,
|
3f59fd3762c45f4d8b56576103b1d5664f7ea426
|
openedx/features/job_board/models.py
|
openedx/features/job_board/models.py
|
from django.db import models
from django_countries.fields import CountryField
from model_utils.models import TimeStampedModel
from .constants import JOB_COMPENSATION_CHOICES, JOB_HOURS_CHOICES, JOB_TYPE_CHOICES
class Job(TimeStampedModel):
"""
This model contains all the fields related to a job being
posted on the job board.
"""
title = models.CharField(max_length=255)
company = models.CharField(max_length=255)
type = models.CharField(max_length=255, choices=JOB_TYPE_CHOICES)
compensation = models.CharField(max_length=255, choices=JOB_COMPENSATION_CHOICES)
hours = models.CharField(max_length=255, choices=JOB_HOURS_CHOICES)
city = models.CharField(max_length=255)
country = CountryField()
description = models.TextField()
function = models.TextField(blank=True, null=True)
responsibilities = models.TextField(blank=True, null=True)
website_link = models.URLField(max_length=255, blank=True, null=True)
contact_email = models.EmailField(max_length=255)
logo = models.ImageField(upload_to="job-board/uploaded-logos/", blank=True, null=True)
|
from django.db import models
from django_countries.fields import CountryField
from model_utils.models import TimeStampedModel
from .constants import JOB_COMPENSATION_CHOICES, JOB_HOURS_CHOICES, JOB_TYPE_CHOICES
class Job(TimeStampedModel):
"""
This model contains all the fields related to a job being
posted on the job board.
"""
title = models.CharField(max_length=255)
company = models.CharField(max_length=255)
type = models.CharField(max_length=255, choices=JOB_TYPE_CHOICES)
compensation = models.CharField(max_length=255, choices=JOB_COMPENSATION_CHOICES)
hours = models.CharField(max_length=255, choices=JOB_HOURS_CHOICES)
city = models.CharField(max_length=255)
country = CountryField()
description = models.TextField()
function = models.TextField(blank=True, null=True)
responsibilities = models.TextField(blank=True, null=True)
website_link = models.URLField(max_length=255, blank=True, null=True)
contact_email = models.EmailField(max_length=255)
logo = models.ImageField(upload_to='job-board/uploaded-logos/', blank=True, null=True)
|
Replace double quotes with single quotes as requested
|
Replace double quotes with single quotes as requested
|
Python
|
agpl-3.0
|
philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform
|
---
+++
@@ -23,5 +23,5 @@
responsibilities = models.TextField(blank=True, null=True)
website_link = models.URLField(max_length=255, blank=True, null=True)
contact_email = models.EmailField(max_length=255)
- logo = models.ImageField(upload_to="job-board/uploaded-logos/", blank=True, null=True)
+ logo = models.ImageField(upload_to='job-board/uploaded-logos/', blank=True, null=True)
|
4e378dc4a44781e59bc63abb64c0fffb114a5adc
|
spacy/tests/regression/test_issue1506.py
|
spacy/tests/regression/test_issue1506.py
|
# coding: utf8
from __future__ import unicode_literals
import gc
from ...lang.en import English
def test_issue1506():
nlp = English()
def string_generator():
for _ in range(10001):
yield "It's sentence produced by that bug."
yield "Oh snap."
for _ in range(10001):
yield "I erase lemmas."
for _ in range(10001):
yield "It's sentence produced by that bug."
for _ in range(10001):
yield "It's sentence produced by that bug."
anchor = None
remember = None
for i, d in enumerate(nlp.pipe(string_generator())):
if i == 9999:
anchor = d
elif 10001 == i:
remember = d
elif i == 10002:
del anchor
gc.collect()
# We should run cleanup more than one time to actually cleanup data.
# In first run — clean up only mark strings as «not hitted».
if i == 20000 or i == 30000:
gc.collect()
for t in d:
str(t.lemma_)
assert remember.text == 'Oh snap.'
|
# coding: utf8
from __future__ import unicode_literals
import gc
from ...lang.en import English
def test_issue1506():
nlp = English()
def string_generator():
for _ in range(10001):
yield "It's sentence produced by that bug."
for _ in range(10001):
yield "I erase lemmas."
for _ in range(10001):
yield "It's sentence produced by that bug."
for _ in range(10001):
yield "It's sentence produced by that bug."
for i, d in enumerate(nlp.pipe(string_generator())):
# We should run cleanup more than one time to actually cleanup data.
# In first run — clean up only mark strings as «not hitted».
if i == 10000 or i == 20000 or i == 30000:
gc.collect()
for t in d:
str(t.lemma_)
|
Remove all obsolete code and test only initial problem
|
Remove all obsolete code and test only initial problem
|
Python
|
mit
|
explosion/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,recognai/spaCy,explosion/spaCy,honnibal/spaCy,recognai/spaCy,explosion/spaCy,honnibal/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,aikramer2/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,aikramer2/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy
|
---
+++
@@ -13,8 +13,6 @@
for _ in range(10001):
yield "It's sentence produced by that bug."
- yield "Oh snap."
-
for _ in range(10001):
yield "I erase lemmas."
@@ -24,23 +22,11 @@
for _ in range(10001):
yield "It's sentence produced by that bug."
- anchor = None
- remember = None
for i, d in enumerate(nlp.pipe(string_generator())):
- if i == 9999:
- anchor = d
- elif 10001 == i:
- remember = d
- elif i == 10002:
- del anchor
- gc.collect()
-
# We should run cleanup more than one time to actually cleanup data.
# In first run — clean up only mark strings as «not hitted».
- if i == 20000 or i == 30000:
+ if i == 10000 or i == 20000 or i == 30000:
gc.collect()
for t in d:
str(t.lemma_)
-
- assert remember.text == 'Oh snap.'
|
432bbebbfa6376779bc605a45857ccdf5fef4b59
|
soundgen.py
|
soundgen.py
|
from wavebender import *
import sys
start = 10
final = 200
end_time= 10
def val(i):
time = float(i) / 44100
k = (final - start) / end_time
return math.sin(2.0 * math.pi * (start * time + ((k * time * time) / 2)))
def sweep():
return (val(i) for i in count(0))
channels = ((sweep(),),)
samples = compute_samples(channels, 44100 * 60 * 1)
write_wavefile(sys.stdout, samples, 44100 * 60 * 1, nchannels=1)
|
from wavebender import *
import sys
from common import *
def sweep():
return (val(i) for i in count(0))
channels = ((sweep(),),)
samples = compute_samples(channels, 44100 * 60 * 1)
write_wavefile(sys.stdout, samples, 44100 * 60 * 1, nchannels=1)
|
Make sound generator use common
|
Make sound generator use common
Signed-off-by: Ian Macalinao <57a33a5496950fec8433e4dd83347673459dcdfc@giza.us>
|
Python
|
isc
|
simplyianm/resonance-finder
|
---
+++
@@ -1,15 +1,6 @@
from wavebender import *
import sys
-
-start = 10
-final = 200
-
-end_time= 10
-
-def val(i):
- time = float(i) / 44100
- k = (final - start) / end_time
- return math.sin(2.0 * math.pi * (start * time + ((k * time * time) / 2)))
+from common import *
def sweep():
return (val(i) for i in count(0))
|
1237e75486ac0ae5c9665ec10d6701c530d601e8
|
src/petclaw/__init__.py
|
src/petclaw/__init__.py
|
# =====================================================================
# Package: petclaw
# File: __init__.py
# Authors: Amal Alghamdi
# David Ketcheson
# Aron Ahmadia
# ======================================================================
"""Main petclaw package"""
import os
import logging, logging.config
# Default logging configuration file
_DEFAULT_LOG_CONFIG_PATH = os.path.join(os.path.dirname(__file__),'log.config')
del os
# Setup loggers
logging.config.fileConfig(_DEFAULT_LOG_CONFIG_PATH)
__all__ = []
# Module imports
__all__.extend(['Controller','Data','Dimension','Grid','Solution','State','riemann'])
from controller import Controller
from grid import Dimension
from pyclaw.grid import Grid
from pyclaw.data import Data
from pyclaw.solution import Solution
from state import State
__all__.extend(['ClawSolver1D','ClawSolver2D','SharpClawSolver1D','SharpClawSolver2D'])
from clawpack import ClawSolver1D
from clawpack import ClawSolver2D
from sharpclaw import SharpClawSolver1D
from sharpclaw import SharpClawSolver2D
__all__.append('BC')
from pyclaw.solver import BC
# Sub-packages
import limiters
from limiters import *
__all__.extend(limiters.__all__)
import plot
__all__.append('plot')
|
# =====================================================================
# Package: petclaw
# File: __init__.py
# Authors: Amal Alghamdi
# David Ketcheson
# Aron Ahmadia
# ======================================================================
"""Main petclaw package"""
import os
import logging, logging.config
# Default logging configuration file
_DEFAULT_LOG_CONFIG_PATH = os.path.join(os.path.dirname(__file__),'log.config')
del os
# Setup loggers
logging.config.fileConfig(_DEFAULT_LOG_CONFIG_PATH)
__all__ = []
# Module imports
__all__.extend(['Controller','Data','Dimension','Grid','Solution','State','riemann'])
from controller import Controller
from grid import Dimension
from pyclaw.grid import Grid
from pyclaw.data import Data
from pyclaw.solution import Solution
from state import State
__all__.extend(['ClawSolver1D','ClawSolver2D','SharpClawSolver1D','SharpClawSolver2D'])
from clawpack import ClawSolver1D
from clawpack import ClawSolver2D
from sharpclaw import SharpClawSolver1D
from sharpclaw import SharpClawSolver2D
from implicitclawpack import ImplicitClawSolver1D
__all__.append('BC')
from pyclaw.solver import BC
# Sub-packages
import limiters
from limiters import *
__all__.extend(limiters.__all__)
import plot
__all__.append('plot')
|
Add ImplicitClawSolver1D to base namespace
|
Add ImplicitClawSolver1D to base namespace
|
Python
|
bsd-3-clause
|
unterweg/peanoclaw,unterweg/peanoclaw,unterweg/peanoclaw,unterweg/peanoclaw,unterweg/peanoclaw,unterweg/peanoclaw
|
---
+++
@@ -33,6 +33,7 @@
from clawpack import ClawSolver2D
from sharpclaw import SharpClawSolver1D
from sharpclaw import SharpClawSolver2D
+from implicitclawpack import ImplicitClawSolver1D
__all__.append('BC')
from pyclaw.solver import BC
|
40f9f82289d0b15c1bc42415460325ce2a447eaf
|
cla_backend/apps/cla_eventlog/management/commands/find_and_delete_old_cases.py
|
cla_backend/apps/cla_eventlog/management/commands/find_and_delete_old_cases.py
|
from django.core.management.base import BaseCommand
from dateutil.relativedelta import relativedelta
from legalaid.models import Case
from cla_butler.tasks import DeleteOldData
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
two_years = self.now - relativedelta(years=2)
return Case.objects.filter(created__lte=two_years).exclude(log__created__gte=two_years)
class Command(BaseCommand):
help = "Find and delete cases that are 2 years old or over that were not deleted prior to the task command being fixed"
def handle(self, *args, **kwargs):
FindAndDeleteCasesUsingCreationTime().run()
|
from django.core.management.base import BaseCommand
from dateutil.relativedelta import relativedelta
from legalaid.models import Case
from cla_butler.tasks import DeleteOldData
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
super(FindAndDeleteCasesUsingCreationTime, self)._setup()
two_years = self.now - relativedelta(years=2)
return Case.objects.filter(created__lte=two_years).exclude(log__created__gte=two_years)
class Command(BaseCommand):
help = "Find and delete cases that are 2 years old or over that were not deleted prior to the task command being fixed"
def handle(self, *args, **kwargs):
FindAndDeleteCasesUsingCreationTime().run()
|
Refactor class so the now time is always defined
|
Refactor class so the now time is always defined
Added code to class to run the setup method which assigns a variable to self.now (ie. defines a time for now)
|
Python
|
mit
|
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
|
---
+++
@@ -7,6 +7,7 @@
class FindAndDeleteCasesUsingCreationTime(DeleteOldData):
def get_eligible_cases(self):
+ super(FindAndDeleteCasesUsingCreationTime, self)._setup()
two_years = self.now - relativedelta(years=2)
return Case.objects.filter(created__lte=two_years).exclude(log__created__gte=two_years)
|
682fa674d63120c10b99b357e4370d3490ea234d
|
xanmel_web/settings/env/production.py
|
xanmel_web/settings/env/production.py
|
DEBUG = False
ALLOWED_HOSTS = ['xon.teichisma.info', 'portal.exe.pub']
|
DEBUG = False
ALLOWED_HOSTS = ['xon.teichisma.info', 'portal.exe.pub', 'samovar.teichisma.info']
|
Add samovar as allowed host
|
Add samovar as allowed host
|
Python
|
agpl-3.0
|
nsavch/xanmel-web
|
---
+++
@@ -1,3 +1,3 @@
DEBUG = False
-ALLOWED_HOSTS = ['xon.teichisma.info', 'portal.exe.pub']
+ALLOWED_HOSTS = ['xon.teichisma.info', 'portal.exe.pub', 'samovar.teichisma.info']
|
a87d927acc42ba2fe4a82004ce919882024039a9
|
kboard/board/forms.py
|
kboard/board/forms.py
|
from django import forms
from django.forms.utils import ErrorList
from django_summernote.widgets import SummernoteWidget
from .models import Post
EMPTY_TITLE_ERROR = "제목을 입력하세요"
EMPTY_CONTENT_ERROR = "내용을 입력하세요"
class DivErrorList(ErrorList):
def __str__(self):
return self.as_divs()
def as_divs(self):
if not self:
return ''
return '<div class="form-group has-error">%s</div>' % ''.join(['<div class="help-block">%s</div>' % e for e in self])
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'content', 'file')
widgets = {
'title': forms.TextInput(attrs={'id': 'id_post_title', 'class': 'form-control', 'name': 'post_title_text', 'placeholder': 'Insert Title'}),
'content': SummernoteWidget(),
}
error_messages = {
'title': {'required': EMPTY_TITLE_ERROR},
'content': {'required': EMPTY_CONTENT_ERROR}
}
def __init__(self, *args, **kwargs):
kwargs_new = {'error_class': DivErrorList}
kwargs_new.update(kwargs)
super(PostForm, self).__init__(*args, **kwargs_new)
self.fields['file'].required = False
|
from django import forms
from django.forms.utils import ErrorList
from django_summernote.widgets import SummernoteWidget
from .models import Post
EMPTY_TITLE_ERROR = "제목을 입력하세요"
EMPTY_CONTENT_ERROR = "내용을 입력하세요"
class DivErrorList(ErrorList):
def __str__(self):
return self.as_divs()
def as_divs(self):
if not self:
return ''
return '<div class="form-group has-error">%s</div>' % ''.join(['<div class="help-block">%s</div>' % e for e in self])
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'content', 'file')
widgets = {
'title': forms.TextInput(attrs={'id': 'id_post_title', 'class': 'form-control', 'placeholder': 'Insert Title'}),
'content': SummernoteWidget(),
}
error_messages = {
'title': {'required': EMPTY_TITLE_ERROR},
'content': {'required': EMPTY_CONTENT_ERROR}
}
def __init__(self, *args, **kwargs):
kwargs_new = {'error_class': DivErrorList}
kwargs_new.update(kwargs)
super(PostForm, self).__init__(*args, **kwargs_new)
self.fields['file'].required = False
|
Remove unnecessary attrs 'name' in title
|
Remove unnecessary attrs 'name' in title
|
Python
|
mit
|
hyesun03/k-board,cjh5414/kboard,guswnsxodlf/k-board,hyesun03/k-board,darjeeling/k-board,cjh5414/kboard,kboard/kboard,kboard/kboard,kboard/kboard,guswnsxodlf/k-board,hyesun03/k-board,cjh5414/kboard,guswnsxodlf/k-board
|
---
+++
@@ -23,7 +23,7 @@
model = Post
fields = ('title', 'content', 'file')
widgets = {
- 'title': forms.TextInput(attrs={'id': 'id_post_title', 'class': 'form-control', 'name': 'post_title_text', 'placeholder': 'Insert Title'}),
+ 'title': forms.TextInput(attrs={'id': 'id_post_title', 'class': 'form-control', 'placeholder': 'Insert Title'}),
'content': SummernoteWidget(),
}
error_messages = {
|
c39163bd6e91ca17f123c5919885b90105efc7c4
|
SimPEG/Mesh/__init__.py
|
SimPEG/Mesh/__init__.py
|
from TensorMesh import TensorMesh
from CylMesh import CylMesh
from Cyl1DMesh import Cyl1DMesh
from LogicallyRectMesh import LogicallyRectMesh
from TreeMesh import TreeMesh
|
from TensorMesh import TensorMesh
from CylMesh import CylMesh
from Cyl1DMesh import Cyl1DMesh
from LogicallyRectMesh import LogicallyRectMesh
from TreeMesh import TreeMesh
from BaseMesh import BaseMesh
|
Add BaseMesh to the init file.
|
Add BaseMesh to the init file.
|
Python
|
mit
|
simpeg/discretize,simpeg/simpeg,simpeg/discretize,simpeg/discretize
|
---
+++
@@ -3,3 +3,4 @@
from Cyl1DMesh import Cyl1DMesh
from LogicallyRectMesh import LogicallyRectMesh
from TreeMesh import TreeMesh
+from BaseMesh import BaseMesh
|
eba0a56f4334d95e37da3946a6a0b053dbe2e19f
|
tfx/orchestration/test_pipelines/custom_exit_handler.py
|
tfx/orchestration/test_pipelines/custom_exit_handler.py
|
# Copyright 2021 Google LLC. All Rights Reserved.
#
# 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.
"""Custom component for exit handler."""
from tfx.orchestration.kubeflow.v2 import decorators
from tfx.utils import io_utils
import tfx.v1 as tfx
@decorators.exit_handler
def test_exit_handler(final_status: tfx.dsl.components.Parameter[str],
file_dir: tfx.dsl.components.Parameter[str]):
io_utils.write_string_file(file_dir, final_status)
|
# Copyright 2021 Google LLC. All Rights Reserved.
#
# 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.
"""Custom component for exit handler."""
from tfx.orchestration.kubeflow import decorators
from tfx.utils import io_utils
import tfx.v1 as tfx
@decorators.exit_handler
def test_exit_handler(final_status: tfx.dsl.components.Parameter[str],
file_dir: tfx.dsl.components.Parameter[str]):
io_utils.write_string_file(file_dir, final_status)
|
Test fix for exit handler
|
Test fix for exit handler
PiperOrigin-RevId: 436937697
|
Python
|
apache-2.0
|
tensorflow/tfx,tensorflow/tfx
|
---
+++
@@ -13,7 +13,7 @@
# limitations under the License.
"""Custom component for exit handler."""
-from tfx.orchestration.kubeflow.v2 import decorators
+from tfx.orchestration.kubeflow import decorators
from tfx.utils import io_utils
import tfx.v1 as tfx
@@ -23,4 +23,3 @@
file_dir: tfx.dsl.components.Parameter[str]):
io_utils.write_string_file(file_dir, final_status)
-
|
a319691a057423a610d91521e2f569250117db09
|
run_migrations.py
|
run_migrations.py
|
"""
Run all migrations
"""
import imp
import os
import sys
import pymongo
from os.path import join
import logging
from backdrop.core.database import Database
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
def load_config(env):
config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config')
fp = None
try:
sys.path.append(config_path)
fp, pathname, description = imp.find_module(
"backdrop/write/config/%s" % env)
return imp.load_module(env, fp, pathname, description)
finally:
sys.path.pop()
if fp:
fp.close()
def get_database(config):
return Database(
config.MONGO_HOSTS, config.MONGO_PORT, config.DATABASE_NAME)
def get_migrations():
migrations_path = join(ROOT_PATH, 'migrations')
for migration_file in os.listdir(migrations_path):
if migration_file.endswith('.py'):
migration_path = join(migrations_path, migration_file)
yield imp.load_source('migration', migration_path)
if __name__ == '__main__':
config = load_config(os.getenv('GOVUK_ENV', 'development'))
database = get_database(config)
for migration in get_migrations():
log.info("Running migration %s" % migration)
migration.up(database)
|
"""
Run all migrations
"""
import imp
import os
import re
import sys
from os.path import join
import logging
from backdrop.core.database import Database
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
def load_config(env):
config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config')
fp = None
try:
sys.path.append(config_path)
fp, pathname, description = imp.find_module(
"backdrop/write/config/%s" % env)
return imp.load_module(env, fp, pathname, description)
finally:
sys.path.pop()
if fp:
fp.close()
def get_database(config):
return Database(
config.MONGO_HOSTS, config.MONGO_PORT, config.DATABASE_NAME)
def get_migrations(migration_files):
migrations_path = join(ROOT_PATH, 'migrations')
for migration_file in os.listdir(migrations_path):
if migration_files is None or migration_file in migration_files:
migration_path = join(migrations_path, migration_file)
yield imp.load_source('migration', migration_path)
if __name__ == '__main__':
config = load_config(os.getenv('GOVUK_ENV', 'development'))
database = get_database(config)
migration_files = sys.argv[1:] or None
for migration in get_migrations(migration_files):
log.info("Running migration %s" % migration)
migration.up(database)
|
Allow specific migrations to be run
|
Allow specific migrations to be run
|
Python
|
mit
|
alphagov/backdrop,alphagov/backdrop,alphagov/backdrop
|
---
+++
@@ -3,8 +3,8 @@
"""
import imp
import os
+import re
import sys
-import pymongo
from os.path import join
import logging
from backdrop.core.database import Database
@@ -34,10 +34,10 @@
config.MONGO_HOSTS, config.MONGO_PORT, config.DATABASE_NAME)
-def get_migrations():
+def get_migrations(migration_files):
migrations_path = join(ROOT_PATH, 'migrations')
for migration_file in os.listdir(migrations_path):
- if migration_file.endswith('.py'):
+ if migration_files is None or migration_file in migration_files:
migration_path = join(migrations_path, migration_file)
yield imp.load_source('migration', migration_path)
@@ -48,6 +48,8 @@
config = load_config(os.getenv('GOVUK_ENV', 'development'))
database = get_database(config)
- for migration in get_migrations():
+ migration_files = sys.argv[1:] or None
+
+ for migration in get_migrations(migration_files):
log.info("Running migration %s" % migration)
migration.up(database)
|
ee649468df406877ccc51a1042e5657f11caa57d
|
oauthenticator/tests/test_openshift.py
|
oauthenticator/tests/test_openshift.py
|
from pytest import fixture, mark
from ..openshift import OpenShiftOAuthenticator
from .mocks import setup_oauth_mock
def user_model(username):
"""Return a user model"""
return {
'metadata': {
'name': username,
}
}
@fixture
def openshift_client(client):
setup_oauth_mock(client,
host=['localhost'],
access_token_path='/oauth/token',
user_path='/oapi/v1/users/~',
)
return client
async def test_openshift(openshift_client):
authenticator = OpenShiftOAuthenticator()
handler = openshift_client.handler_for_user(user_model('wash'))
user_info = await authenticator.authenticate(handler)
assert sorted(user_info) == ['auth_state', 'name']
name = user_info['name']
assert name == 'wash'
auth_state = user_info['auth_state']
assert 'access_token' in auth_state
assert 'openshift_user' in auth_state
|
from pytest import fixture, mark
from ..openshift import OpenShiftOAuthenticator
from .mocks import setup_oauth_mock
def user_model(username):
"""Return a user model"""
return {
'metadata': {
'name': username,
}
}
@fixture
def openshift_client(client):
setup_oauth_mock(client,
host=['localhost'],
access_token_path='/oauth/token',
user_path='/apis/user.openshift.io/v1/users/~',
)
return client
async def test_openshift(openshift_client):
authenticator = OpenShiftOAuthenticator()
handler = openshift_client.handler_for_user(user_model('wash'))
user_info = await authenticator.authenticate(handler)
assert sorted(user_info) == ['auth_state', 'name']
name = user_info['name']
assert name == 'wash'
auth_state = user_info['auth_state']
assert 'access_token' in auth_state
assert 'openshift_user' in auth_state
|
Update test harness to use new REST API path for OpenShift.
|
Update test harness to use new REST API path for OpenShift.
|
Python
|
bsd-3-clause
|
minrk/oauthenticator,NickolausDS/oauthenticator,jupyter/oauthenticator,jupyter/oauthenticator,maltevogl/oauthenticator,jupyterhub/oauthenticator
|
---
+++
@@ -19,7 +19,7 @@
setup_oauth_mock(client,
host=['localhost'],
access_token_path='/oauth/token',
- user_path='/oapi/v1/users/~',
+ user_path='/apis/user.openshift.io/v1/users/~',
)
return client
|
60759f310f0354d4940c66f826e899bf4c2b76b4
|
src/foremast/app/aws.py
|
src/foremast/app/aws.py
|
"""AWS Spinnaker Application."""
from pprint import pformat
from foremast.app import base
from foremast.utils import wait_for_task
class SpinnakerApp(base.BaseApp):
"""Create AWS Spinnaker Application."""
provider = 'aws'
def create(self):
"""Send a POST to spinnaker to create a new application with class variables.
Raises:
AssertionError: Application creation failed.
"""
self.appinfo['accounts'] = self.get_accounts()
self.log.debug('Pipeline Config\n%s', pformat(self.pipeline_config))
self.log.debug('App info:\n%s', pformat(self.appinfo))
jsondata = self.render_application_template()
wait_for_task(jsondata)
self.log.info("Successfully created %s application", self.appname)
return
def delete(self):
"""Delete AWS Spinnaker Application."""
return False
def update(self):
"""Update AWS Spinnaker Application."""
return False
|
"""AWS Spinnaker Application."""
from pprint import pformat
from foremast.app import base
from foremast.utils import wait_for_task
class SpinnakerApp(base.BaseApp):
"""Create AWS Spinnaker Application."""
provider = 'aws'
def create(self):
"""Send a POST to spinnaker to create a new application with class variables.
Raises:
AssertionError: Application creation failed.
"""
self.appinfo['accounts'] = self.get_accounts()
self.log.debug('Pipeline Config\n%s', pformat(self.pipeline_config))
self.log.debug('App info:\n%s', pformat(self.appinfo))
jsondata = self.render_application_template()
wait_for_task(jsondata)
self.log.info("Successfully created %s application", self.appname)
return jsondata
def delete(self):
"""Delete AWS Spinnaker Application."""
return False
def update(self):
"""Update AWS Spinnaker Application."""
return False
|
Return useful data from App creation
|
fix: Return useful data from App creation
|
Python
|
apache-2.0
|
gogoair/foremast,gogoair/foremast
|
---
+++
@@ -24,7 +24,7 @@
wait_for_task(jsondata)
self.log.info("Successfully created %s application", self.appname)
- return
+ return jsondata
def delete(self):
"""Delete AWS Spinnaker Application."""
|
47970281f9cdf10f8429cfb88c7fffc3c9c27f2a
|
python/testData/inspections/PyArgumentListInspection/dictFromKeys.py
|
python/testData/inspections/PyArgumentListInspection/dictFromKeys.py
|
print(dict.fromkeys(<warning descr="Parameter 'seq' unfilled">)</warning>)
print(dict.fromkeys(['foo', 'bar']))
|
print(dict.fromkeys(<warning descr="Parameter(s) unfilledPossible callees:dict.fromkeys(seq: Sequence[TypeVar('_T')])dict.fromkeys(seq: Sequence[TypeVar('_T')], value: TypeVar('_S'))">)</warning>)
print(dict.fromkeys(['foo', 'bar']))
|
Fix test data for PyArgumentListInspectionTest.testDictFromKeys.
|
Fix test data for PyArgumentListInspectionTest.testDictFromKeys.
|
Python
|
apache-2.0
|
signed/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,da1z/intellij-community,allotria/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ibinti/intellij-community,semonte/intellij-community,semonte/intellij-community,apixandru/intellij-community,allotria/intellij-community,FHannes/intellij-community,apixandru/intellij-community,asedunov/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,asedunov/intellij-community,signed/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,asedunov/intellij-community,ibinti/intellij-community,xfournet/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,allotria/intellij-community,ibinti/intellij-community,xfournet/intellij-community,signed/intellij-community,suncycheng/intellij-community,allotria/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,semonte/intellij-community,semonte/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,allotria/intellij-community,signed/intellij-community,apixandru/intellij-community,semonte/intellij-community,semonte/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,xfournet/intellij-community,ibinti/intellij-community,semonte/intellij-community,semonte/intellij-community,xfournet/intellij-community,asedunov/intellij-community,signed/intellij-community,ibinti/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,signed/intellij-community,da1z/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,asedunov/intellij-community,apixandru/intellij-community,asedunov/intellij-community,semonte/intellij-community,signed/intellij-community,suncycheng/intellij-community,signed/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,apixandru/intellij-community,apixandru/intellij-community,FHannes/intellij-community,semonte/intellij-community,apixandru/intellij-community,xfournet/intellij-community,da1z/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,FHannes/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,da1z/intellij-community,da1z/intellij-community,ibinti/intellij-community,semonte/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,FHannes/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,apixandru/intellij-community,semonte/intellij-community,allotria/intellij-community,signed/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,ibinti/intellij-community,apixandru/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,da1z/intellij-community,signed/intellij-community,signed/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,xfournet/intellij-community,semonte/intellij-community,FHannes/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community
|
---
+++
@@ -1,2 +1,2 @@
-print(dict.fromkeys(<warning descr="Parameter 'seq' unfilled">)</warning>)
+print(dict.fromkeys(<warning descr="Parameter(s) unfilledPossible callees:dict.fromkeys(seq: Sequence[TypeVar('_T')])dict.fromkeys(seq: Sequence[TypeVar('_T')], value: TypeVar('_S'))">)</warning>)
print(dict.fromkeys(['foo', 'bar']))
|
64d00e0c17855baaef6562c08f26f30b17ce38bf
|
panopticon/gtkvlc.py
|
panopticon/gtkvlc.py
|
"""Container classes for VLC under GTK"""
import gtk
import sys
# pylint: disable-msg=R0904
class VLCSlave(gtk.DrawingArea):
"""VLCSlave provides a playback window with an underlying player
Its player can be controlled through the 'player' attribute, which
is a vlc.MediaPlayer() instance.
"""
def __init__(self, instance, name, width=320, height=200):
"""Generate a new VLC container using vlc instance "instance" and
the given name variable for later referencing. Width/Height are self
explanatory."""
self.wname = name
gtk.DrawingArea.__init__(self)
self.player = instance.media_player_new()
def handle_embed(*args):
"""Args are ignored, but left here in case."""
# pylint: disable-msg=W0613
if sys.platform == 'win32':
self.player.set_hwnd(self.window.handle)
else:
self.player.set_xwindow(self.window.xid)
return True
self.connect("map", handle_embed)
self.set_size_request(width, height)
|
"""Container classes for VLC under GTK"""
import gtk
import sys
# pylint: disable-msg=R0904
class VLCSlave(gtk.DrawingArea):
"""VLCSlave provides a playback window with an underlying player
Its player can be controlled through the 'player' attribute, which
is a vlc.MediaPlayer() instance.
"""
def __init__(self, instance, name, width=320, height=200):
"""Generate a new VLC container using vlc instance "instance" and
the given name variable for later referencing. Width/Height are self
explanatory."""
self.wname = name
gtk.DrawingArea.__init__(self)
self.player = instance.media_player_new()
def handle_embed(*args):
"""Args are ignored, but left here in case."""
# pylint: disable-msg=W0613
if sys.platform == 'win32':
self.player.set_hwnd(self.window.handle)
else:
self.player.set_xwindow(self.window.xid)
return True
self.connect("map", handle_embed)
self.set_size_request(width, height)
def actions(self, action):
if hasattr(self.player, action):
return getattr(self.player, action)
else:
return lambda x: None
def deferred_action(self, delay = 0, action='play', *args):
"""Start playing in the background."""
from twisted.internet.task import deferLater
from twisted.internet import reactor
return deferLater(reactor, delay, self.actions(action), *args)
|
Refactor and add playback funcs.
|
Refactor and add playback funcs.
|
Python
|
agpl-3.0
|
armyofevilrobots/Panopticon
|
---
+++
@@ -27,3 +27,16 @@
return True
self.connect("map", handle_embed)
self.set_size_request(width, height)
+
+ def actions(self, action):
+ if hasattr(self.player, action):
+ return getattr(self.player, action)
+ else:
+ return lambda x: None
+
+ def deferred_action(self, delay = 0, action='play', *args):
+ """Start playing in the background."""
+ from twisted.internet.task import deferLater
+ from twisted.internet import reactor
+ return deferLater(reactor, delay, self.actions(action), *args)
+
|
d608ba0892da052f2515d6796e88013c0730dc0b
|
corehq/ex-submodules/auditcare/management/commands/gdpr_scrub_user_auditcare.py
|
corehq/ex-submodules/auditcare/management/commands/gdpr_scrub_user_auditcare.py
|
from __future__ import absolute_import
from __future__ import unicode_literals
from corehq.util.log import with_progress_bar
from corehq.util.couch import iter_update, DocUpdate
from django.core.management.base import BaseCommand
from auditcare.utils.export import navigation_event_ids_by_user
import logging
from auditcare.models import NavigationEventAudit
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = """Scrub a username from auditcare for GDPR compliance"""
def add_arguments(self, parser):
parser.add_argument('username', help="Username to scrub")
def handle(self, username, **options):
def update_username(event_dict):
audit_doc = NavigationEventAudit.wrap(event_dict)
audit_doc.user = new_username
event_dict['user'] = new_username
return DocUpdate(doc=audit_doc)
new_username = "Redacted User (GDPR)"
event_ids = navigation_event_ids_by_user(username)
iter_update(NavigationEventAudit.get_db(), update_username, with_progress_bar(event_ids, len(event_ids)))
|
from __future__ import absolute_import
from __future__ import unicode_literals
from corehq.util.log import with_progress_bar
from corehq.util.couch import iter_update, DocUpdate
from django.core.management.base import BaseCommand
from auditcare.utils.export import navigation_event_ids_by_user
import logging
from auditcare.models import NavigationEventAudit
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = """Scrub a username from auditcare for GDPR compliance"""
def add_arguments(self, parser):
parser.add_argument('username', help="Username to scrub")
def handle(self, username, **options):
def update_username(event_dict):
event_dict['user'] = new_username
return DocUpdate(doc=event_dict)
new_username = "Redacted User (GDPR)"
event_ids = navigation_event_ids_by_user(username)
iter_update(NavigationEventAudit.get_db(), update_username, with_progress_bar(event_ids, len(event_ids)))
|
Update dict instead of doc
|
Update dict instead of doc
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
|
---
+++
@@ -19,10 +19,8 @@
def handle(self, username, **options):
def update_username(event_dict):
- audit_doc = NavigationEventAudit.wrap(event_dict)
- audit_doc.user = new_username
event_dict['user'] = new_username
- return DocUpdate(doc=audit_doc)
+ return DocUpdate(doc=event_dict)
new_username = "Redacted User (GDPR)"
event_ids = navigation_event_ids_by_user(username)
|
a7ba0c94b656346ee1ceb4a34f62650898cc3428
|
abe/document_models/label_documents.py
|
abe/document_models/label_documents.py
|
#!/usr/bin/env python3
"""Document models for mongoengine"""
from mongoengine import *
from bson import ObjectId
class Label(Document):
"""Model for labels of events"""
name = StringField(required=True, unique=True) # TODO: set to primary key?
description = StringField()
url = URLField()
|
#!/usr/bin/env python3
"""Document models for mongoengine"""
from mongoengine import *
from bson import ObjectId
class Label(Document):
"""Model for labels of events"""
name = StringField(required=True, unique=True) # TODO: set to primary key?
description = StringField()
url = URLField()
default = BooleanField(default=False) # suggested to display by default
parent_labels = ListField(StringField()) # rudimentary hierarchy of labels
color = StringField() # suggested color for label
visibility = StringField() # suggested visibility
|
Add new fields to label document
|
Add new fields to label document
- Make default default value False
|
Python
|
agpl-3.0
|
olinlibrary/ABE,olinlibrary/ABE,olinlibrary/ABE
|
---
+++
@@ -9,3 +9,7 @@
name = StringField(required=True, unique=True) # TODO: set to primary key?
description = StringField()
url = URLField()
+ default = BooleanField(default=False) # suggested to display by default
+ parent_labels = ListField(StringField()) # rudimentary hierarchy of labels
+ color = StringField() # suggested color for label
+ visibility = StringField() # suggested visibility
|
a96eae8333104f11974f8944f93c66c0f70275d7
|
telemetry/telemetry/core/platform/power_monitor/ippet_power_monitor_unittest.py
|
telemetry/telemetry/core/platform/power_monitor/ippet_power_monitor_unittest.py
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import unittest
from telemetry import decorators
from telemetry.core.platform import win_platform_backend
from telemetry.core.platform.power_monitor import ippet_power_monitor
class IppetPowerMonitorTest(unittest.TestCase):
@decorators.Enabled('win')
def testFindOrInstallIppet(self):
self.assertTrue(ippet_power_monitor.IppetPath())
@decorators.Enabled('win')
def testIppetRunsWithoutErrors(self):
# Very basic test, doesn't validate any output data.
platform_backend = win_platform_backend.WinPlatformBackend()
power_monitor = ippet_power_monitor.IppetPowerMonitor(platform_backend)
if not power_monitor.CanMonitorPower():
logging.warning('Test not supported on this platform.')
return
power_monitor.StartMonitoringPower(None)
statistics = power_monitor.StopMonitoringPower()
self.assertEqual(statistics['identifier'], 'ippet')
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import unittest
from telemetry import decorators
from telemetry.core.platform import win_platform_backend
from telemetry.core.platform.power_monitor import ippet_power_monitor
class IppetPowerMonitorTest(unittest.TestCase):
@decorators.Disabled
def testFindOrInstallIppet(self):
self.assertTrue(ippet_power_monitor.IppetPath())
@decorators.Enabled('win')
def testIppetRunsWithoutErrors(self):
# Very basic test, doesn't validate any output data.
platform_backend = win_platform_backend.WinPlatformBackend()
power_monitor = ippet_power_monitor.IppetPowerMonitor(platform_backend)
if not power_monitor.CanMonitorPower():
logging.warning('Test not supported on this platform.')
return
power_monitor.StartMonitoringPower(None)
statistics = power_monitor.StopMonitoringPower()
self.assertEqual(statistics['identifier'], 'ippet')
|
Disable IppetPowerMonitorTest.testFindOrInstallIppet which is failing on new trybots.
|
Disable IppetPowerMonitorTest.testFindOrInstallIppet which is failing on new trybots.
BUG=424027
TBR=dtu@chromium.org
Review URL: https://codereview.chromium.org/643763005
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#299833}
|
Python
|
bsd-3-clause
|
catapult-project/catapult,catapult-project/catapult-csm,sahiljain/catapult,benschmaus/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult,sahiljain/catapult,catapult-project/catapult-csm,SummerLW/Perf-Insight-Report,catapult-project/catapult,benschmaus/catapult,catapult-project/catapult-csm,sahiljain/catapult,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult,SummerLW/Perf-Insight-Report,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult,catapult-project/catapult,SummerLW/Perf-Insight-Report,SummerLW/Perf-Insight-Report,catapult-project/catapult,SummerLW/Perf-Insight-Report,benschmaus/catapult,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult-csm
|
---
+++
@@ -11,7 +11,7 @@
class IppetPowerMonitorTest(unittest.TestCase):
- @decorators.Enabled('win')
+ @decorators.Disabled
def testFindOrInstallIppet(self):
self.assertTrue(ippet_power_monitor.IppetPath())
|
8aa0813402f5083cb230ba3d457b76dafc371fe5
|
cache_purge_hooks/backends/varnishbackend.py
|
cache_purge_hooks/backends/varnishbackend.py
|
import varnish
import logging
from django.conf import settings
#STUB config options here
VARNISH_HOST = settings.VARNISH_HOST
VARNISH_PORT = settings.VARNISH_PORT
VARNISH_DEBUG = settings.DEBUG
VARNISH_SITE_DOMAIN = ".*"
class VarnishManager(object):
def __init__(self):
self.handler = varnish.VarnishHandler([VARNISH_HOST, VARNISH_PORT])
def __send_command(self, command):
if VARNISH_DEBUG:
logging.info("unrun cache command (debug on): {0}".format(command))
else:
self.handler.fetch(command.encode('utf-8'))
def close(self):
self.handler.close()
def purge(self, command):
cmd = r'ban req.http.host ~ "{host}" && req.url ~ "{url}"'.format(
host = VARNISH_SITE_DOMAIN.encode('ascii'),
url = command.encode('ascii'),
)
self.__send_command(cmd)
def purge_all(self):
return self.expire('.*')
|
import varnish
import logging
from django.conf import settings
#STUB config options here
VARNISH_HOST = settings.VARNISH_HOST
VARNISH_PORT = settings.VARNISH_PORT
VARNISH_DEBUG = settings.DEBUG
VARNISH_SECRET = settings.VARNISH_SECRET or None
VARNISH_SITE_DOMAIN = settings.VARNISH_SITE_DOMAIN or '.*'
class VarnishManager(object):
def __init__(self):
varnish_url = "{host}:{port}".format(host=VARNISH_HOST, port=VARNISH_PORT)
self.handler = varnish.VarnishHandler(varnish_url, secret=VARNISH_SECRET)
def __send_command(self, command):
if VARNISH_DEBUG:
logging.info("unrun cache command (debug on): {0}".format(command))
else:
self.handler.fetch(command.encode('utf-8'))
def close(self):
self.handler.close()
def purge(self, command):
cmd = r'ban req.http.host ~ "{host}" && req.url ~ "{url}"'.format(
host = VARNISH_SITE_DOMAIN.encode('ascii'),
url = command.encode('ascii'),
)
self.__send_command(cmd)
def purge_all(self):
return self.expire('.*')
|
Add support for varnish backend secret and pass a domain when it's defined in settings
|
Add support for varnish backend secret and pass a domain when it's defined in settings
|
Python
|
mit
|
RealGeeks/django-cache-purge-hooks,RealGeeks/django-cache-purge-hooks
|
---
+++
@@ -5,14 +5,14 @@
#STUB config options here
VARNISH_HOST = settings.VARNISH_HOST
VARNISH_PORT = settings.VARNISH_PORT
-
VARNISH_DEBUG = settings.DEBUG
-
-VARNISH_SITE_DOMAIN = ".*"
+VARNISH_SECRET = settings.VARNISH_SECRET or None
+VARNISH_SITE_DOMAIN = settings.VARNISH_SITE_DOMAIN or '.*'
class VarnishManager(object):
def __init__(self):
- self.handler = varnish.VarnishHandler([VARNISH_HOST, VARNISH_PORT])
+ varnish_url = "{host}:{port}".format(host=VARNISH_HOST, port=VARNISH_PORT)
+ self.handler = varnish.VarnishHandler(varnish_url, secret=VARNISH_SECRET)
def __send_command(self, command):
if VARNISH_DEBUG:
@@ -32,3 +32,4 @@
def purge_all(self):
return self.expire('.*')
+
|
568dce643d9e88ebd9e5b395accb3027e02febb7
|
backend/conferences/models/duration.py
|
backend/conferences/models/duration.py
|
from django.core.validators import MinValueValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Duration(models.Model):
conference = models.ForeignKey(
"conferences.Conference",
on_delete=models.CASCADE,
verbose_name=_("conference"),
related_name="durations",
)
name = models.CharField(_("name"), max_length=100)
duration = models.PositiveIntegerField(
_("duration"), validators=[MinValueValidator(1)]
)
notes = models.TextField(_("notes"), blank=True)
allowed_submission_types = models.ManyToManyField(
"submissions.SubmissionType", verbose_name=_("allowed submission types")
)
def __str__(self):
return f"{self.name} - {self.duration} mins ({self.conference_id})"
class Meta:
verbose_name = _("Duration")
verbose_name_plural = _("Durations")
|
from django.core.validators import MinValueValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Duration(models.Model):
conference = models.ForeignKey(
"conferences.Conference",
on_delete=models.CASCADE,
verbose_name=_("conference"),
related_name="durations",
)
name = models.CharField(_("name"), max_length=100)
duration = models.PositiveIntegerField(
_("duration"), validators=[MinValueValidator(1)]
)
notes = models.TextField(_("notes"), blank=True)
allowed_submission_types = models.ManyToManyField(
"submissions.SubmissionType", verbose_name=_("allowed submission types")
)
def __str__(self):
return (
f"{self.name} - {self.duration} mins (at Conference "
f"{self.conference.name} <{self.conference.code}>)"
)
class Meta:
verbose_name = _("Duration")
verbose_name_plural = _("Durations")
|
Fix Duration.__str__ to show Conference name and code
|
Fix Duration.__str__ to show Conference name and code
|
Python
|
mit
|
patrick91/pycon,patrick91/pycon
|
---
+++
@@ -21,7 +21,10 @@
)
def __str__(self):
- return f"{self.name} - {self.duration} mins ({self.conference_id})"
+ return (
+ f"{self.name} - {self.duration} mins (at Conference "
+ f"{self.conference.name} <{self.conference.code}>)"
+ )
class Meta:
verbose_name = _("Duration")
|
f909d0a49e0e455e34673f2b6efc517bc76738d2
|
build/fbcode_builder/specs/fbthrift.py
|
build/fbcode_builder/specs/fbthrift.py
|
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
builder.add_option('krb5/krb5:git_hash', 'krb5-1.16.1-final')
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.github_project_workdir('krb5/krb5', 'src'),
builder.autoconf_install('krb5/krb5'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import specs.sodium as sodium
import specs.wangle as wangle
import specs.zstd as zstd
from shell_quoting import ShellQuoted
def fbcode_builder_spec(builder):
# This API should change rarely, so build the latest tag instead of master.
builder.add_option(
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
Cut fbcode_builder dep for thrift on krb5
|
Cut fbcode_builder dep for thrift on krb5
Summary: [Thrift] Cut `fbcode_builder` dep for `thrift` on `krb5`. In the past, Thrift depended on Kerberos and the `krb5` implementation for its transport-layer security. However, Thrift has since migrated fully to Transport Layer Security for its transport-layer security and no longer has any build-time dependency on `krb5`. Clean this up.
Reviewed By: stevegury, vitaut
Differential Revision: D14814205
fbshipit-source-id: dca469d22098e34573674194facaaac6c4c6aa32
|
Python
|
mit
|
facebook/bistro,facebook/bistro,facebook/bistro,facebook/bistro,facebook/bistro,facebook/bistro
|
---
+++
@@ -21,15 +21,12 @@
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
- builder.add_option('krb5/krb5:git_hash', 'krb5-1.16.1-final')
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This isn't a separete spec, since only fbthrift uses mstch.
builder.github_project_workdir('no1msd/mstch', 'build'),
builder.cmake_install('no1msd/mstch'),
- builder.github_project_workdir('krb5/krb5', 'src'),
- builder.autoconf_install('krb5/krb5'),
builder.fb_github_cmake_install('fbthrift/thrift'),
],
}
|
ad042127cadc2fd779bdea4d6853102b5d8d0ad0
|
api/tests/test_login.py
|
api/tests/test_login.py
|
import unittest
from api.test import BaseTestCase
class TestLogin(BaseTestCase):
@unittest.skip("")
def test_login(self):
login_credentials = {
"password": "qwerty@123",
"username": "EdwinKato"
}
response = self.client.post('/api/v1/auth/login',
data=json.dumps(login_credentials),
content_type='application/json')
self.assertEqual(response.status_code, 200)
|
import unittest
import json
from api.test import BaseTestCase
class TestLogin(BaseTestCase):
@unittest.skip("")
def test_login(self):
login_credentials = {
"password": "qwerty@123",
"username": "EdwinKato"
}
response = self.client.post('/api/v1/auth/login',
data=json.dumps(login_credentials),
content_type='application/json')
self.assertEqual(response.status_code, 200)
def test_non_registered_user_login(self):
""" Test for login of non-registered user """
with self.client:
response = self.client.post(
'/api/v1/auth/login',
data=json.dumps(dict(
email='edwin@andela.com',
password='123456'
)),
content_type='application/json'
)
data = json.loads(response.data.decode())
self.assertTrue(data['status'] == 'fail')
self.assertTrue(response.content_type == 'application/json')
self.assertEqual(response.status_code, 404)
|
Add test for non-registered user
|
Add test for non-registered user
|
Python
|
mit
|
EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list
|
---
+++
@@ -1,4 +1,5 @@
import unittest
+import json
from api.test import BaseTestCase
@@ -16,3 +17,21 @@
data=json.dumps(login_credentials),
content_type='application/json')
self.assertEqual(response.status_code, 200)
+
+
+def test_non_registered_user_login(self):
+ """ Test for login of non-registered user """
+ with self.client:
+ response = self.client.post(
+ '/api/v1/auth/login',
+ data=json.dumps(dict(
+ email='edwin@andela.com',
+ password='123456'
+ )),
+ content_type='application/json'
+ )
+ data = json.loads(response.data.decode())
+ self.assertTrue(data['status'] == 'fail')
+ self.assertTrue(response.content_type == 'application/json')
+ self.assertEqual(response.status_code, 404)
+
|
b9c175059f0f2f3321ffd495fd46c6f5770afd22
|
bluebottle/payouts_dorado/adapters.py
|
bluebottle/payouts_dorado/adapters.py
|
import json
import requests
from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from requests.exceptions import MissingSchema
from bluebottle.clients import properties
class PayoutValidationError(Exception):
pass
class PayoutCreationError(Exception):
pass
class DoradoPayoutAdapter(object):
def __init__(self, project):
self.settings = getattr(properties, 'PAYOUT_SERVICE', None)
self.project = project
self.tenant = connection.tenant
def trigger_payout(self):
# Send the signal to Dorado
data = {
'project_id': self.project.id,
'tenant': self.tenant.schema_name
}
try:
response = requests.post(self.settings['url'], data)
response.raise_for_status()
self.project.payout_status = 'created'
self.project.save()
except requests.HTTPError:
try:
raise PayoutValidationError(json.loads(response.content))
except ValueError:
raise PayoutCreationError(response.content)
except MissingSchema:
raise ImproperlyConfigured("Incorrect Payout URL")
except IOError, e:
raise PayoutCreationError(unicode(e))
except TypeError:
raise ImproperlyConfigured("Invalid Payout settings")
|
import json
import requests
from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from requests.exceptions import MissingSchema
from bluebottle.clients import properties
class PayoutValidationError(Exception):
pass
class PayoutCreationError(Exception):
pass
class DoradoPayoutAdapter(object):
def __init__(self, project):
self.settings = getattr(properties, 'PAYOUT_SERVICE', None)
self.project = project
self.tenant = connection.tenant
def trigger_payout(self):
# Send the signal to Dorado
data = {
'project_id': self.project.id,
'tenant': self.tenant.schema_name
}
try:
self.project.payout_status = 'created'
self.project.save()
response = requests.post(self.settings['url'], data)
response.raise_for_status()
except requests.HTTPError:
try:
raise PayoutValidationError(json.loads(response.content))
except ValueError:
raise PayoutCreationError(response.content)
except MissingSchema:
raise ImproperlyConfigured("Incorrect Payout URL")
except IOError, e:
raise PayoutCreationError(unicode(e))
except TypeError:
raise ImproperlyConfigured("Invalid Payout settings")
|
Set the payout status to created BEFORE we call out to dorado. This way we do not override that status that dorado set.
|
Set the payout status to created BEFORE we call out to dorado. This way
we do not override that status that dorado set.
BB-9471 #resolve
|
Python
|
bsd-3-clause
|
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
|
---
+++
@@ -31,11 +31,11 @@
}
try:
+ self.project.payout_status = 'created'
+ self.project.save()
+
response = requests.post(self.settings['url'], data)
response.raise_for_status()
-
- self.project.payout_status = 'created'
- self.project.save()
except requests.HTTPError:
try:
raise PayoutValidationError(json.loads(response.content))
|
a9052428e1eee8ec566bd496e1247dae0873d9c9
|
test/wordfilter_test.py
|
test/wordfilter_test.py
|
import nose
from lib.wordfilter import Wordfilter
# Run with `python -m test.wordfilter_test`
class Wordfilter_test:
def setup(self):
self.wordfilter = Wordfilter()
def teardown(self):
self.wordfilter = []
def test_loading(self):
assert type(self.wordfilter.blacklist) is list
def test_badWords(self):
assert self.wordfilter.blacklisted('this string contains the word skank')
assert self.wordfilter.blacklisted('this string contains the word SkAnK')
assert self.wordfilter.blacklisted('this string contains the wordskank')
assert self.wordfilter.blacklisted('this string contains the skankword')
assert not self.wordfilter.blacklisted('this string is clean!')
def test_addWords(self):
self.wordfilter.addWords(['clean'])
assert self.wordfilter.blacklisted('this string contains the word skank')
assert self.wordfilter.blacklisted('this string is clean!')
def test_clearList(self):
self.wordfilter.clearList();
assert not self.wordfilter.blacklisted('this string contains the word skank')
self.wordfilter.addWords(['skank'])
assert self.wordfilter.blacklisted('this string contains the word skank')
if __name__ == "__main__":
nose.main()
|
import nose
from lib.wordfilter import Wordfilter
# Run with `python -m test.wordfilter_test`
class Wordfilter_test:
def setup(self):
self.wordfilter = Wordfilter()
def teardown(self):
self.wordfilter = []
def test_loading(self):
assert type(self.wordfilter.blacklist) is list
def test_badWords(self):
assert self.wordfilter.blacklisted('this string contains the word skank')
assert self.wordfilter.blacklisted('this string contains the word SkAnK')
assert self.wordfilter.blacklisted('this string contains the wordskank')
assert self.wordfilter.blacklisted('this string contains the skankword')
assert not self.wordfilter.blacklisted('this string is clean!')
def test_addWords(self):
self.wordfilter.addWords(['clean'])
assert self.wordfilter.blacklisted('this string contains the word skank')
assert self.wordfilter.blacklisted('this string is clean!')
def test_clearList(self):
self.wordfilter.clearList()
assert not self.wordfilter.blacklisted('this string contains the word skank')
self.wordfilter.addWords(['skank'])
assert self.wordfilter.blacklisted('this string contains the word skank')
def test_add_multiple_words(self):
# Arrange
self.wordfilter.clearList()
# Act
self.wordfilter.addWords(['zebra','elephant'])
# Assert
assert self.wordfilter.blacklisted('this string has zebra in it')
assert self.wordfilter.blacklisted('this string has elephant in it')
assert not self.wordfilter.blacklisted('this string has nothing in it')
if __name__ == "__main__":
nose.main()
|
Add another test case - add multiple words
|
Add another test case - add multiple words
|
Python
|
mit
|
dariusk/wordfilter,dariusk/wordfilter,mwatson/wordfilter,hugovk/wordfilter,mwatson/wordfilter,dariusk/wordfilter,hugovk/wordfilter,mwatson/wordfilter,hugovk/wordfilter,dariusk/wordfilter,hugovk/wordfilter,mwatson/wordfilter
|
---
+++
@@ -25,11 +25,23 @@
assert self.wordfilter.blacklisted('this string is clean!')
def test_clearList(self):
- self.wordfilter.clearList();
+ self.wordfilter.clearList()
assert not self.wordfilter.blacklisted('this string contains the word skank')
self.wordfilter.addWords(['skank'])
assert self.wordfilter.blacklisted('this string contains the word skank')
+ def test_add_multiple_words(self):
+ # Arrange
+ self.wordfilter.clearList()
+
+ # Act
+ self.wordfilter.addWords(['zebra','elephant'])
+
+ # Assert
+ assert self.wordfilter.blacklisted('this string has zebra in it')
+ assert self.wordfilter.blacklisted('this string has elephant in it')
+ assert not self.wordfilter.blacklisted('this string has nothing in it')
+
if __name__ == "__main__":
nose.main()
|
0a6072621570464522cbfa6d939dffccc0fa6503
|
spacy/cli/converters/iob2json.py
|
spacy/cli/converters/iob2json.py
|
# coding: utf8
from __future__ import unicode_literals
import cytoolz
from ...gold import iob_to_biluo
def iob2json(input_data, n_sents=10, *args, **kwargs):
"""
Convert IOB files into JSON format for use with train cli.
"""
docs = []
for group in cytoolz.partition_all(n_sents, docs):
group = list(group)
first = group.pop(0)
to_extend = first["paragraphs"][0]["sentences"]
for sent in group[1:]:
to_extend.extend(sent["paragraphs"][0]["sentences"])
docs.append(first)
return docs
def read_iob(raw_sents):
sentences = []
for line in raw_sents:
if not line.strip():
continue
tokens = [t.split("|") for t in line.split()]
if len(tokens[0]) == 3:
words, pos, iob = zip(*tokens)
else:
words, iob = zip(*tokens)
pos = ["-"] * len(words)
biluo = iob_to_biluo(iob)
sentences.append(
[
{"orth": w, "tag": p, "ner": ent}
for (w, p, ent) in zip(words, pos, biluo)
]
)
sentences = [{"tokens": sent} for sent in sentences]
paragraphs = [{"sentences": [sent]} for sent in sentences]
docs = [{"id": 0, "paragraphs": [para]} for para in paragraphs]
return docs
|
# coding: utf8
from __future__ import unicode_literals
from ...gold import iob_to_biluo
from ...util import minibatch
def iob2json(input_data, n_sents=10, *args, **kwargs):
"""
Convert IOB files into JSON format for use with train cli.
"""
docs = []
for group in minibatch(docs, n_sents):
group = list(group)
first = group.pop(0)
to_extend = first["paragraphs"][0]["sentences"]
for sent in group[1:]:
to_extend.extend(sent["paragraphs"][0]["sentences"])
docs.append(first)
return docs
def read_iob(raw_sents):
sentences = []
for line in raw_sents:
if not line.strip():
continue
tokens = [t.split("|") for t in line.split()]
if len(tokens[0]) == 3:
words, pos, iob = zip(*tokens)
else:
words, iob = zip(*tokens)
pos = ["-"] * len(words)
biluo = iob_to_biluo(iob)
sentences.append(
[
{"orth": w, "tag": p, "ner": ent}
for (w, p, ent) in zip(words, pos, biluo)
]
)
sentences = [{"tokens": sent} for sent in sentences]
paragraphs = [{"sentences": [sent]} for sent in sentences]
docs = [{"id": 0, "paragraphs": [para]} for para in paragraphs]
return docs
|
Remove cytoolz usage in CLI
|
Remove cytoolz usage in CLI
|
Python
|
mit
|
explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy
|
---
+++
@@ -1,9 +1,8 @@
# coding: utf8
from __future__ import unicode_literals
-import cytoolz
-
from ...gold import iob_to_biluo
+from ...util import minibatch
def iob2json(input_data, n_sents=10, *args, **kwargs):
@@ -11,7 +10,7 @@
Convert IOB files into JSON format for use with train cli.
"""
docs = []
- for group in cytoolz.partition_all(n_sents, docs):
+ for group in minibatch(docs, n_sents):
group = list(group)
first = group.pop(0)
to_extend = first["paragraphs"][0]["sentences"]
|
fb837585264e6abe4b0488e3a9dd5c5507e69bf6
|
tensorflow/python/distribute/__init__.py
|
tensorflow/python/distribute/__init__.py
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Distribution Strategy library."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import
from tensorflow.python.distribute import cluster_resolver
from tensorflow.python.distribute import cross_device_ops
from tensorflow.python.distribute import distribute_lib
from tensorflow.python.distribute import distribution_strategy_context
from tensorflow.python.distribute import mirrored_strategy
from tensorflow.python.distribute import one_device_strategy
from tensorflow.python.distribute.client import parameter_server_client
from tensorflow.python.distribute.experimental import collective_all_reduce_strategy
from tensorflow.python.distribute.experimental import parameter_server_strategy
# pylint: enable=unused-import
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Distribution Strategy library."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import
from tensorflow.python.distribute import cluster_resolver
from tensorflow.python.distribute import cross_device_ops
from tensorflow.python.distribute import distribute_lib
from tensorflow.python.distribute import distribution_strategy_context
from tensorflow.python.distribute import mirrored_strategy
from tensorflow.python.distribute import one_device_strategy
from tensorflow.python.distribute.experimental import collective_all_reduce_strategy
from tensorflow.python.distribute.experimental import parameter_server_strategy
# pylint: enable=unused-import
|
Fix asan test for various targets.
|
PSv2: Fix asan test for various targets.
PiperOrigin-RevId: 325441069
Change-Id: I1fa1b2b10670f34739323292eab623d5b538142e
|
Python
|
apache-2.0
|
aam-at/tensorflow,cxxgtxy/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,aldian/tensorflow,sarvex/tensorflow,aldian/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,karllessard/tensorflow,Intel-tensorflow/tensorflow,davidzchen/tensorflow,yongtang/tensorflow,yongtang/tensorflow,yongtang/tensorflow,davidzchen/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,freedomtan/tensorflow,aam-at/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,Intel-Corporation/tensorflow,annarev/tensorflow,gautam1858/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,freedomtan/tensorflow,karllessard/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,aldian/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,aam-at/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,Intel-Corporation/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,sarvex/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,annarev/tensorflow,Intel-Corporation/tensorflow,petewarden/tensorflow,cxxgtxy/tensorflow,aldian/tensorflow,frreiss/tensorflow-fred,freedomtan/tensorflow,aldian/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_saved_model,petewarden/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,freedomtan/tensorflow,cxxgtxy/tensorflow,freedomtan/tensorflow,annarev/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aam-at/tensorflow,annarev/tensorflow,aldian/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,annarev/tensorflow,Intel-Corporation/tensorflow,cxxgtxy/tensorflow,davidzchen/tensorflow,frreiss/tensorflow-fred,cxxgtxy/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,aldian/tensorflow,gautam1858/tensorflow,davidzchen/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,karllessard/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,aam-at/tensorflow,petewarden/tensorflow,sarvex/tensorflow,cxxgtxy/tensorflow,aldian/tensorflow,annarev/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,paolodedios/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,karllessard/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,petewarden/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,davidzchen/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,petewarden/tensorflow,annarev/tensorflow,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,aam-at/tensorflow,karllessard/tensorflow,petewarden/tensorflow,davidzchen/tensorflow,sarvex/tensorflow,sarvex/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,sarvex/tensorflow,frreiss/tensorflow-fred,aam-at/tensorflow,freedomtan/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,davidzchen/tensorflow,paolodedios/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,petewarden/tensorflow,karllessard/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,frreiss/tensorflow-fred,petewarden/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,paolodedios/tensorflow,yongtang/tensorflow,gautam1858/tensorflow
|
---
+++
@@ -25,7 +25,6 @@
from tensorflow.python.distribute import distribution_strategy_context
from tensorflow.python.distribute import mirrored_strategy
from tensorflow.python.distribute import one_device_strategy
-from tensorflow.python.distribute.client import parameter_server_client
from tensorflow.python.distribute.experimental import collective_all_reduce_strategy
from tensorflow.python.distribute.experimental import parameter_server_strategy
# pylint: enable=unused-import
|
35fe7bb6411c8009253bf66fb7739a5d49a7028d
|
scuole/counties/management/commands/bootstrapcounties.py
|
scuole/counties/management/commands/bootstrapcounties.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import csv
import os
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.text import slugify
from ...models import County
from scuole.states.models import State
class Command(BaseCommand):
help = 'Bootstraps County models using DSHS county list.'
def handle(self, *args, **options):
self.texas = State.objects.get(name='Texas')
counties_file = os.path.join(
settings.DATA_FOLDER, 'counties', 'counties.csv')
with open(counties_file, 'rU') as f:
reader = csv.DictReader(f)
counties = []
for row in reader:
counties.append(self.create_county(row))
County.objects.bulk_create(counties)
def create_county(self, county):
return County(
name=county['County Name'],
slug=slugify(county['County Name']),
fips=county['FIPS #'],
state=self.texas,
)
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import csv
import os
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.text import slugify
from ...models import County
from scuole.states.models import State
class Command(BaseCommand):
help = 'Bootstraps County models using DSHS county list.'
def handle(self, *args, **options):
self.texas = State.objects.get(name='Texas')
counties_file = os.path.join(
settings.DATA_FOLDER, 'counties', 'counties.csv')
with open(counties_file, 'rU') as f:
reader = csv.DictReader(f)
counties = []
for row in reader:
counties.append(self.create_county(row))
County.objects.bulk_create(counties)
def create_county(self, county):
self.stdout.write(
'Creating {} County...'.format(county['County Name']))
return County(
name=county['County Name'],
slug=slugify(county['County Name']),
fips=county['FIPS #'],
state=self.texas,
)
|
Add feedback during county loader
|
Add feedback during county loader
|
Python
|
mit
|
texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole
|
---
+++
@@ -32,6 +32,9 @@
County.objects.bulk_create(counties)
def create_county(self, county):
+ self.stdout.write(
+ 'Creating {} County...'.format(county['County Name']))
+
return County(
name=county['County Name'],
slug=slugify(county['County Name']),
|
4e2cbe770161e9d88acb68e95698b4ec184be7e0
|
tests/testapp/manage.py
|
tests/testapp/manage.py
|
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
try:
import dynamic_admin #@UnusedImport
except ImportError:
import sys, os
sys.path.append(os.path.abspath('%s/../..' % os.getcwd()))
if __name__ == "__main__":
execute_manager(settings)
|
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
try:
import dynamic_admin #@UnusedImport
except ImportError:
import sys, os
sys.path.insert(0, os.path.abspath('%s/../..' % os.getcwd()))
if __name__ == "__main__":
execute_manager(settings)
|
Make sure current dynamic_choices module has priority over possible installed one for tests.
|
Make sure current dynamic_choices module has priority over possible installed one for tests.
|
Python
|
mit
|
charettes/django-dynamic-choices,charettes/django-dynamic-choices,charettes/django-dynamic-choices
|
---
+++
@@ -11,7 +11,7 @@
import dynamic_admin #@UnusedImport
except ImportError:
import sys, os
- sys.path.append(os.path.abspath('%s/../..' % os.getcwd()))
+ sys.path.insert(0, os.path.abspath('%s/../..' % os.getcwd()))
if __name__ == "__main__":
execute_manager(settings)
|
388d6feb2703b1badb3cb194b58deff831681a0a
|
toga_cocoa/widgets/progressbar.py
|
toga_cocoa/widgets/progressbar.py
|
from __future__ import print_function, absolute_import, division, unicode_literals
from ..libs import *
from .base import Widget
class ProgressBar(Widget):
def __init__(self, max=None, value=None, **style):
super(ProgressBar, self).__init__(**style)
self.max = max
self.startup()
self.value = value
def startup(self):
self._impl = NSProgressIndicator.new()
self._impl.setStyle_(NSProgressIndicatorBarStyle)
self._impl.setDisplayedWhenStopped_(False)
if self.max:
self._impl.setIndeterminate_(False)
self._impl.setMaxValue_(self.max)
else:
self._impl.setIndeterminate_(True)
# Disable all autolayout functionality
self._impl.setTranslatesAutoresizingMaskIntoConstraints_(False)
self._impl.setAutoresizesSubviews_(False)
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
self._running = self._value is not None
if value is not None:
self._impl.setDoubleValue_(value)
def start(self):
if self._impl and not self._running:
self._impl.startAnimation_(self._impl)
self._running = True
def stop(self):
if self._impl and self._running:
self._impl.stopAnimation_(self._impl)
self._running = False
|
from __future__ import print_function, absolute_import, division, unicode_literals
from ..libs import *
from .base import Widget
class ProgressBar(Widget):
def __init__(self, max=None, value=None, **style):
super(ProgressBar, self).__init__(**style)
self.max = max
self.startup()
self.value = value
def startup(self):
self._impl = NSProgressIndicator.new()
self._impl.setStyle_(NSProgressIndicatorBarStyle)
self._impl.setDisplayedWhenStopped_(True)
if self.max:
self._impl.setIndeterminate_(False)
self._impl.setMaxValue_(self.max)
else:
self._impl.setIndeterminate_(True)
# Disable all autolayout functionality
self._impl.setTranslatesAutoresizingMaskIntoConstraints_(False)
self._impl.setAutoresizesSubviews_(False)
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = value
self._running = self._value is not None
if value is not None:
self._impl.setDoubleValue_(value)
def start(self):
if self._impl and not self._running:
self._impl.startAnimation_(self._impl)
self._running = True
def stop(self):
if self._impl and self._running:
self._impl.stopAnimation_(self._impl)
self._running = False
|
Make progress bar visible by default.
|
Make progress bar visible by default.
|
Python
|
bsd-3-clause
|
pybee-attic/toga-cocoa,pybee/toga-cocoa
|
---
+++
@@ -16,7 +16,7 @@
def startup(self):
self._impl = NSProgressIndicator.new()
self._impl.setStyle_(NSProgressIndicatorBarStyle)
- self._impl.setDisplayedWhenStopped_(False)
+ self._impl.setDisplayedWhenStopped_(True)
if self.max:
self._impl.setIndeterminate_(False)
self._impl.setMaxValue_(self.max)
|
63241b7fb62166f4a31ef7ece38edf8b36129f63
|
dictionary/management/commands/writeLiblouisTables.py
|
dictionary/management/commands/writeLiblouisTables.py
|
from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables
from daisyproducer.dictionary.models import Word
from daisyproducer.documents.models import Document
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = ''
help = 'Write Liblouis tables from the confirmed words in the dictionary'
def handle(self, *args, **options):
# write new global white lists
if options['verbosity'] >= 2:
self.stderr.write('Writing new global white lists...\n')
writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated'))
# update local tables
if options['verbosity'] >= 2:
self.stderr.write('Updating local tables...\n')
writeLocalTables(Document.objects.all())
|
from daisyproducer.dictionary.brailleTables import writeWhiteListTables, writeLocalTables
from daisyproducer.dictionary.models import Word
from daisyproducer.documents.models import Document
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = ''
help = 'Write Liblouis tables from the confirmed words in the dictionary'
def handle(self, *args, **options):
# write new global white lists
verbosity = int(options['verbosity'])
if verbosity >= 2:
self.stderr.write('Writing new global white lists...\n')
writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated'))
# update local tables
if verbosity >= 2:
self.stderr.write('Updating local tables...\n')
writeLocalTables(Document.objects.all())
|
Make sure the verbosity stuff actually works
|
Make sure the verbosity stuff actually works
|
Python
|
agpl-3.0
|
sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer
|
---
+++
@@ -9,10 +9,11 @@
def handle(self, *args, **options):
# write new global white lists
- if options['verbosity'] >= 2:
+ verbosity = int(options['verbosity'])
+ if verbosity >= 2:
self.stderr.write('Writing new global white lists...\n')
writeWhiteListTables(Word.objects.filter(isConfirmed=True).filter(isLocal=False).order_by('untranslated'))
# update local tables
- if options['verbosity'] >= 2:
+ if verbosity >= 2:
self.stderr.write('Updating local tables...\n')
writeLocalTables(Document.objects.all())
|
69ade2e8dfcaac3769d0b75929eb89cf3e775a74
|
tests/unit/test_util.py
|
tests/unit/test_util.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from ava.util import time_uuid, base_path, defines, misc
class TestTimeUUID(object):
def test_uuids_should_be_in_alaphabetical_order(self):
old = time_uuid.oid()
for i in range(100):
t = time_uuid.oid()
assert t > old
old = t
def test_base_path_should_contain_pod_folder():
basedir = base_path()
source_pod_folder = os.path.join(basedir, defines.POD_FOLDER_NAME)
assert os.path.exists(source_pod_folder)
assert os.path.isdir(source_pod_folder)
def test_is_frizon_should_return_false():
assert not misc.is_frozen()
def test_get_app_dir():
app_dir = misc.get_app_dir('TestApp')
assert 'TestApp' in app_dir
def test_get_app_dir_via_env():
os.environ.setdefault('AVA_POD', '/test/folder')
app_dir = misc.get_app_dir()
assert app_dir == '/test/folder'
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from ava.util import time_uuid, base_path, defines, misc
class TestTimeUUID(object):
def test_uuids_should_be_in_alaphabetical_order(self):
old = time_uuid.oid()
for i in range(100):
t = time_uuid.oid()
assert t > old
old = t
def test_base_path_should_contain_pod_folder():
basedir = base_path()
source_pod_folder = os.path.join(basedir, defines.POD_FOLDER_NAME)
assert os.path.exists(source_pod_folder)
assert os.path.isdir(source_pod_folder)
def test_is_frizon_should_return_false():
assert not misc.is_frozen()
def test_get_app_dir():
app_dir = misc.get_app_dir('TestApp')
assert 'TestApp'.lower() in app_dir.lower()
def test_get_app_dir_via_env():
os.environ.setdefault('AVA_POD', '/test/folder')
app_dir = misc.get_app_dir()
assert app_dir == '/test/folder'
|
Fix issue in get_app_dir() test which is caused by platfrom-dependent problem
|
Fix issue in get_app_dir() test which is caused by platfrom-dependent problem
|
Python
|
apache-2.0
|
eavatar/eavatar-me,eavatar/eavatar-me,eavatar/eavatar-me,eavatar/eavatar-me
|
---
+++
@@ -30,7 +30,7 @@
def test_get_app_dir():
app_dir = misc.get_app_dir('TestApp')
- assert 'TestApp' in app_dir
+ assert 'TestApp'.lower() in app_dir.lower()
def test_get_app_dir_via_env():
|
d8af86a0fedb8e7225e5ad97f69cd40c9c2abd8f
|
nimp/commands/cis_wwise_build_banks.py
|
nimp/commands/cis_wwise_build_banks.py
|
# -*- coding: utf-8 -*-
from nimp.commands._cis_command import *
from nimp.utilities.wwise import *
#-------------------------------------------------------------------------------
class BuildWwiseBanksCommand(CisCommand):
abstract = 0
#---------------------------------------------------------------------------
def __init__(self):
CisCommand.__init__(self, 'cis-wwise-build-banks', 'Builds Wwise Banks')
#---------------------------------------------------------------------------
def cis_configure_arguments(self, env, parser):
parser.add_argument('platform',
help = 'Platform to build',
metavar = '<PLATFORM>')
parser.add_argument('--checkin',
help = 'Automatically checkin result',
action = "store_true",
default = False)
return True
#---------------------------------------------------------------------------
def _cis_run(self, env):
return build_wwise_banks(env)
|
# -*- coding: utf-8 -*-
from nimp.commands._cis_command import *
from nimp.utilities.wwise import *
#-------------------------------------------------------------------------------
class BuildWwiseBanksCommand(CisCommand):
abstract = 0
#---------------------------------------------------------------------------
def __init__(self):
CisCommand.__init__(self, 'cis-wwise-build-banks', 'Builds Wwise Banks')
#---------------------------------------------------------------------------
def cis_configure_arguments(self, env, parser):
parser.add_argument('-p',
'--platform',
help = 'Platform to build',
metavar = '<platform>')
parser.add_argument('--checkin',
help = 'Automatically checkin result',
action = "store_true",
default = False)
return True
#---------------------------------------------------------------------------
def _cis_run(self, env):
return build_wwise_banks(env)
|
Replace "<platform>" with "-p <platform>" in CIS wwise command.
|
Replace "<platform>" with "-p <platform>" in CIS wwise command.
This is what the Buildbot configuration uses, and it makes sense. It
used to not break because we were ignoring unknown commandline flags.
|
Python
|
mit
|
dontnod/nimp
|
---
+++
@@ -12,9 +12,10 @@
#---------------------------------------------------------------------------
def cis_configure_arguments(self, env, parser):
- parser.add_argument('platform',
+ parser.add_argument('-p',
+ '--platform',
help = 'Platform to build',
- metavar = '<PLATFORM>')
+ metavar = '<platform>')
parser.add_argument('--checkin',
help = 'Automatically checkin result',
|
99c0804edebd94e0054e324833028ba450806f7f
|
documentchain/server.py
|
documentchain/server.py
|
from flask import Flask, jsonify, request
from .chain import DocumentChain
from .storage import DiskStorage
app = Flask(__name__)
chain = DocumentChain(DiskStorage('data/'))
@app.route('/entries', methods=['GET', 'POST'])
def entries():
if request.method == 'POST':
if not request.json:
return '', 400
id = chain.add(request.json)
res = jsonify({"id": id})
res.status_code = 201
return res
else:
return jsonify({'entries': [e.serialize() for e in chain.all()]})
|
from flask import Flask, jsonify, request
from .chain import DocumentChain
from .storage import DiskStorage
app = Flask(__name__)
chain = DocumentChain(DiskStorage('data/'))
@app.route('/entries', methods=['GET', 'POST'])
def entry_list():
if request.method == 'POST':
if not request.json:
return '', 400
id = chain.add(request.json)
res = jsonify({"id": id})
res.status_code = 201
return res
else:
return jsonify({'entries': [e.serialize() for e in chain.all()]})
@app.route('/entries/<entry_id>', methods=['GET'])
def entry_detail(entry_id):
return jsonify(chain.get(entry_id).serialize())
|
Add entry detail HTTP endpoint
|
Add entry detail HTTP endpoint
|
Python
|
mit
|
LandRegistry-Attic/concept-system-of-record,LandRegistry-Attic/concept-system-of-record,LandRegistry-Attic/concept-system-of-record
|
---
+++
@@ -6,7 +6,7 @@
chain = DocumentChain(DiskStorage('data/'))
@app.route('/entries', methods=['GET', 'POST'])
-def entries():
+def entry_list():
if request.method == 'POST':
if not request.json:
return '', 400
@@ -16,3 +16,8 @@
return res
else:
return jsonify({'entries': [e.serialize() for e in chain.all()]})
+
+
+@app.route('/entries/<entry_id>', methods=['GET'])
+def entry_detail(entry_id):
+ return jsonify(chain.get(entry_id).serialize())
|
581f16e30aeb465f80fd28a77404b0375bd197d4
|
code/python/knub/thesis/topic_model.py
|
code/python/knub/thesis/topic_model.py
|
import logging, gensim, bz2
from knub.thesis.util.memory import limit_memory
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
def main():
logging.info("Starting Wikipedia LDA")
# limit memory to 32 GB
limit_memory(32000)
id2word = gensim.corpora.Dictionary.load_from_text(bz2.BZ2File("/data/wikipedia/2016-06-21/gensim_wordids.txt.bz2"))
mm = gensim.corpora.MmCorpus("/data/wikipedia/2016-06-21/gensim_tfidf.mm")
print mm
lda = gensim.models.ldamodel.LdaModel(corpus=mm, num_topics=100, id2word=id2word, chunksize=10000, passes=1)
# lda = gensim.models.ldamodel.LdaModel(corpus=mm, num_topics=100, id2word=id2word, workers=3)
lda.save("/data/wikipedia/2016-06-21/topics.model")
lda.print_topics()
logging.info("Finished Wikipedia LDA")
if __name__ == "__main__":
main()
|
import logging, gensim, bz2
import mkl
from knub.thesis.util.memory import limit_memory
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
mkl.set_num_threads(8)
def main():
logging.info("Starting Wikipedia LDA")
# limit memory to 32 GB
limit_memory(32000)
id2word = gensim.corpora.Dictionary.load_from_text(bz2.BZ2File("/data/wikipedia/2016-06-21/gensim_wordids.txt.bz2"))
mm = gensim.corpora.MmCorpus("/data/wikipedia/2016-06-21/gensim_tfidf.mm")
print mm
lda = gensim.models.ldamodel.LdaModel(corpus=mm, num_topics=100, id2word=id2word, chunksize=10000, passes=1)
# lda = gensim.models.ldamodel.LdaModel(corpus=mm, num_topics=100, id2word=id2word, workers=3)
lda.save("/data/wikipedia/2016-06-21/topics.model")
lda.print_topics()
logging.info("Finished Wikipedia LDA")
if __name__ == "__main__":
main()
|
Set max threads for MKL.
|
Set max threads for MKL.
|
Python
|
apache-2.0
|
knub/master-thesis,knub/master-thesis,knub/master-thesis,knub/master-thesis
|
---
+++
@@ -1,7 +1,9 @@
import logging, gensim, bz2
+import mkl
from knub.thesis.util.memory import limit_memory
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
+mkl.set_num_threads(8)
def main():
logging.info("Starting Wikipedia LDA")
|
d000a2e3991c54b319bc7166d9d178b739170a46
|
polling_stations/apps/data_collection/management/commands/import_sheffield.py
|
polling_stations/apps/data_collection/management/commands/import_sheffield.py
|
"""
Import Sheffield
"""
from data_collection.management.commands import BaseShpShpImporter
class Command(BaseShpShpImporter):
"""
Imports the Polling Station data from Sheffield
"""
council_id = 'E08000019'
districts_name = 'SCCPollingDistricts2015'
stations_name = 'SCCPollingStations2015.shp'
def district_record_to_dict(self, record):
return {
'internal_council_id': record[0],
'name': record[1],
}
def station_record_to_dict(self, record):
address = record[1]
# remove postcode from end of address if present
postcode_offset = -len(record[2])
if address[postcode_offset:] == record[2]:
address = address[:postcode_offset].strip()
# remove trailing comma if present
if address[-1:] == ',':
address = address[:-1]
# replace commas with \n
address = "\n".join(map(lambda x: x.strip(), address.split(',')))
return {
'internal_council_id': record[0],
'postcode' : record[2],
'address' : address
}
|
"""
Import Sheffield
"""
from data_collection.management.commands import BaseShpShpImporter
class Command(BaseShpShpImporter):
"""
Imports the Polling Station data from Sheffield
"""
council_id = 'E08000019'
districts_name = 'SCCPollingDistricts2015'
stations_name = 'SCCPollingStations2015.shp'
def district_record_to_dict(self, record):
return {
'internal_council_id': record[1],
'extra_id': record[0],
'name': record[1],
}
def station_record_to_dict(self, record):
address = record[1]
# remove postcode from end of address if present
postcode_offset = -len(record[2])
if address[postcode_offset:] == record[2]:
address = address[:postcode_offset].strip()
# remove trailing comma if present
if address[-1:] == ',':
address = address[:-1]
# replace commas with \n
address = "\n".join(map(lambda x: x.strip(), address.split(',')))
return {
'internal_council_id': record[0],
'postcode' : record[2],
'address' : address,
'polling_district_id': record[-1]
}
|
Add polling_district_id in Sheffield import script
|
Add polling_district_id in Sheffield import script
|
Python
|
bsd-3-clause
|
DemocracyClub/UK-Polling-Stations,andylolz/UK-Polling-Stations,andylolz/UK-Polling-Stations,andylolz/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations
|
---
+++
@@ -13,8 +13,9 @@
def district_record_to_dict(self, record):
return {
- 'internal_council_id': record[0],
- 'name': record[1],
+ 'internal_council_id': record[1],
+ 'extra_id': record[0],
+ 'name': record[1],
}
def station_record_to_dict(self, record):
@@ -36,5 +37,6 @@
return {
'internal_council_id': record[0],
'postcode' : record[2],
- 'address' : address
+ 'address' : address,
+ 'polling_district_id': record[-1]
}
|
4f351f34f3a0d5d2870639bb972d41b459595704
|
settei/version.py
|
settei/version.py
|
""":mod:`settei.version` --- Version data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 0.2.0
"""
#: (:class:`typing.Tuple`\ [:class:`int`, :class:`int`, :class:`int`])
#: The triple of version numbers e.g. ``(1, 2, 3)``.
VERSION_INFO = (0, 5, 3)
#: (:class:`str`) The version string e.g. ``'1.2.3'``.
VERSION = '{}.{}.{}'.format(*VERSION_INFO)
if __name__ == '__main__':
print(VERSION)
|
""":mod:`settei.version` --- Version data
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 0.2.0
"""
#: (:class:`typing.Tuple`\ [:class:`int`, :class:`int`, :class:`int`])
#: The triple of version numbers e.g. ``(1, 2, 3)``.
VERSION_INFO = (0, 5, 2)
#: (:class:`str`) The version string e.g. ``'1.2.3'``.
VERSION = '{}.{}.{}'.format(*VERSION_INFO)
if __name__ == '__main__':
print(VERSION)
|
Revert "Bump up to 0.5.3"
|
Revert "Bump up to 0.5.3"
This reverts commit bc8e02970ee80a6cd0a57f4fe1553cc8faf092dc.
|
Python
|
apache-2.0
|
spoqa/settei
|
---
+++
@@ -7,7 +7,7 @@
#: (:class:`typing.Tuple`\ [:class:`int`, :class:`int`, :class:`int`])
#: The triple of version numbers e.g. ``(1, 2, 3)``.
-VERSION_INFO = (0, 5, 3)
+VERSION_INFO = (0, 5, 2)
#: (:class:`str`) The version string e.g. ``'1.2.3'``.
VERSION = '{}.{}.{}'.format(*VERSION_INFO)
|
c1330851105df14367bec5ed87fc3c45b71932fd
|
project_euler/solutions/problem_35.py
|
project_euler/solutions/problem_35.py
|
from typing import List
from ..library.sqrt import fsqrt
from ..library.number_theory.primes import is_prime, prime_sieve
def is_circular_prime(n: int, sieve: List[int]) -> bool:
for i in range(len(str(n))):
if not is_prime(int(str(n)[i:] + str(n)[:i]), sieve):
return False
print(n)
return True
def solve(digits: int=6) -> int:
bound = 10 ** digits
sieve = prime_sieve(fsqrt(bound))
return sum(1 for prime in range(bound) if is_circular_prime(prime, sieve))
|
from typing import List
from ..library.base import number_to_list, list_to_number
from ..library.sqrt import fsqrt
from ..library.number_theory.primes import is_prime, prime_sieve
def is_circular_prime(n: int, sieve: List[int]) -> bool:
rep_n = number_to_list(n)
for i in range(len(rep_n)):
if not is_prime(list_to_number(rep_n[i:] + rep_n[:i]), sieve):
return False
print(n)
return True
def solve(digits: int=6) -> int:
bound = 10 ** digits
sieve = prime_sieve(fsqrt(bound))
return sum(1 for prime in range(1, bound)
if is_circular_prime(prime, sieve))
|
Make 35 use number_to_list and inverse
|
Make 35 use number_to_list and inverse
|
Python
|
mit
|
cryvate/project-euler,cryvate/project-euler
|
---
+++
@@ -1,13 +1,15 @@
from typing import List
-
+from ..library.base import number_to_list, list_to_number
from ..library.sqrt import fsqrt
from ..library.number_theory.primes import is_prime, prime_sieve
def is_circular_prime(n: int, sieve: List[int]) -> bool:
- for i in range(len(str(n))):
- if not is_prime(int(str(n)[i:] + str(n)[:i]), sieve):
+ rep_n = number_to_list(n)
+
+ for i in range(len(rep_n)):
+ if not is_prime(list_to_number(rep_n[i:] + rep_n[:i]), sieve):
return False
print(n)
@@ -19,4 +21,5 @@
bound = 10 ** digits
sieve = prime_sieve(fsqrt(bound))
- return sum(1 for prime in range(bound) if is_circular_prime(prime, sieve))
+ return sum(1 for prime in range(1, bound)
+ if is_circular_prime(prime, sieve))
|
299fadcde71558bc1e77ba396cc544619373c2b1
|
conditional/blueprints/spring_evals.py
|
conditional/blueprints/spring_evals.py
|
from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'committee_meetings': 24,
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'major_project': 'open_container',
'major_project_passed': True,
'comments': "please don't fail me",
'result': 'Pending'
},
{
'name': "Julien Eid",
'committee_meetings': 69,
'house_meetings_missed': [],
'major_project': 'wii-u shit',
'major_project_passed': True,
'comments': "imdabes",
'result': 'Passed'
}
]
# return names in 'first last (username)' format
return render_template('spring_evals.html',
username = user_name,
members = members)
|
from flask import Blueprint
from flask import render_template
from flask import request
spring_evals_bp = Blueprint('spring_evals_bp', __name__)
@spring_evals_bp.route('/spring_evals/')
def display_spring_evals():
# get user data
user_name = request.headers.get('x-webauth-user')
members = [
{
'name': "Liam Middlebrook",
'committee_meetings': 24,
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'major_project': 'open_container',
'major_project_passed': True,
'social_events': "",
'comments': "please don't fail me",
'result': 'Pending'
},
{
'name': "Julien Eid",
'committee_meetings': 69,
'house_meetings_missed': [],
'major_project': 'wii-u shit',
'major_project_passed': True,
'social_events': "Manipulation and Opportunism",
'comments': "imdabes",
'result': 'Passed'
}
]
# return names in 'first last (username)' format
return render_template('spring_evals.html',
username = user_name,
members = members)
|
Add social events to spring evals 😿
|
Add social events to spring evals 😿
|
Python
|
mit
|
RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional
|
---
+++
@@ -17,6 +17,7 @@
'house_meetings_missed': [{'date': "aprial fools fayas ads", 'reason': "I was playing videogames"}],
'major_project': 'open_container',
'major_project_passed': True,
+ 'social_events': "",
'comments': "please don't fail me",
'result': 'Pending'
},
@@ -26,6 +27,7 @@
'house_meetings_missed': [],
'major_project': 'wii-u shit',
'major_project_passed': True,
+ 'social_events': "Manipulation and Opportunism",
'comments': "imdabes",
'result': 'Passed'
}
|
8194f327032c064fe71ba3dc918e28ee2a586b12
|
sqlalchemy_mixins/serialize.py
|
sqlalchemy_mixins/serialize.py
|
from collections.abc import Iterable
from .inspection import InspectionMixin
class SerializeMixin(InspectionMixin):
"""Mixin to make model serializable."""
__abstract__ = True
def to_dict(self,nested = False, hybrid_attributes = False, exclude = None):
"""Return dict object with model's data.
:param nested: flag to return nested relationships' data if true
:type: bool
:param include_hybrid: flag to include hybrid attributes if true
:return: dict
"""
result = dict()
if exclude is None:
view_cols = self.columns
else :
view_cols = filter(lambda e: e not in exclude, self.columns)
for key in view_cols :
result[key] = getattr(self, key)
if hybrid_attributes:
for key in self.hybrid_properties:
result[key] = getattr(self, key)
if nested:
for key in self.relations:
obj = getattr(self, key)
if isinstance(obj, SerializeMixin):
result[key] = obj.to_dict(hybrid_attributes=hybrid_attributes)
elif isinstance(obj, Iterable):
result[key] = [o.to_dict(hybrid_attributes=hybrid_attributes) for o in obj]
return result
|
from collections.abc import Iterable
from .inspection import InspectionMixin
class SerializeMixin(InspectionMixin):
"""Mixin to make model serializable."""
__abstract__ = True
def to_dict(self,nested = False, hybrid_attributes = False, exclude = None):
"""Return dict object with model's data.
:param nested: flag to return nested relationships' data if true
:type: bool
:param include_hybrid: flag to include hybrid attributes if true
:return: dict
"""
result = dict()
if exclude is None:
view_cols = self.columns
else :
view_cols = filter(lambda e: e not in exclude, self.columns)
for key in view_cols :
result[key] = getattr(self, key)
if hybrid_attributes:
for key in self.hybrid_properties:
result[key] = getattr(self, key)
if nested:
for key in self.relations:
obj = getattr(self, key)
if isinstance(obj, SerializeMixin):
result[key] = obj.to_dict(hybrid_attributes=hybrid_attributes)
elif isinstance(obj, Iterable):
result[key] = [
o.to_dict(hybrid_attributes=hybrid_attributes) for o in obj
if isinstance(o, SerializeMixin)
]
return result
|
Check if relation objects are class of SerializeMixin
|
Check if relation objects are class of SerializeMixin
|
Python
|
mit
|
absent1706/sqlalchemy-mixins
|
---
+++
@@ -37,6 +37,9 @@
if isinstance(obj, SerializeMixin):
result[key] = obj.to_dict(hybrid_attributes=hybrid_attributes)
elif isinstance(obj, Iterable):
- result[key] = [o.to_dict(hybrid_attributes=hybrid_attributes) for o in obj]
+ result[key] = [
+ o.to_dict(hybrid_attributes=hybrid_attributes) for o in obj
+ if isinstance(o, SerializeMixin)
+ ]
return result
|
5a6c8b1c9c13078462bec7ba254c6a6f95dd3c42
|
contrib/linux/tests/test_action_dig.py
|
contrib/linux/tests/test_action_dig.py
|
#!/usr/bin/env python
# Copyright 2020 The StackStorm Authors.
#
# 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.
from __future__ import absolute_import
from st2tests.base import BaseActionTestCase
from dig import DigAction
class DigActionTestCase(BaseActionTestCase):
action_cls = DigAction
def test_run(self):
action = self.get_action_instance()
# Use the defaults from dig.yaml
result = action.run(rand=False, count=0, nameserver=None, hostname='', queryopts='short')
self.assertIsInstance(result, list)
self.assertEqual(len(result), 0)
result = action.run(rand=False, count=0, nameserver=None, hostname='google.com',
queryopts='')
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
|
#!/usr/bin/env python
# Copyright 2020 The StackStorm Authors.
#
# 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.
from __future__ import absolute_import
from st2tests.base import BaseActionTestCase
from dig import DigAction
class DigActionTestCase(BaseActionTestCase):
action_cls = DigAction
def test_run(self):
action = self.get_action_instance()
# Use the defaults from dig.yaml
result = action.run(rand=False, count=0, nameserver=None, hostname='', queryopts='short')
self.assertIsInstance(result, list)
self.assertEqual(len(result), 0)
result = action.run(rand=False, count=0, nameserver=None, hostname='google.com',
queryopts='')
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
first_result = result[0]
self.assertIsInstance(first_result, str)
self.assertGreater(len(first_result))
|
Test that returned result is a str instance
|
Test that returned result is a str instance
|
Python
|
apache-2.0
|
nzlosh/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,Plexxi/st2,StackStorm/st2,StackStorm/st2,nzlosh/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2
|
---
+++
@@ -35,3 +35,7 @@
queryopts='')
self.assertIsInstance(result, list)
self.assertGreater(len(result), 0)
+
+ first_result = result[0]
+ self.assertIsInstance(first_result, str)
+ self.assertGreater(len(first_result))
|
0ba7c20f3ddea73f8d1f92c66b3ab0abf1ea8861
|
asciimatics/__init__.py
|
asciimatics/__init__.py
|
__author__ = 'Peter Brittain'
from .version import version
__version__ = version
|
__author__ = 'Peter Brittain'
try:
from .version import version
except ImportError:
# Someone is running straight from the GIT repo - dummy out the version
version = "0.0.0"
__version__ = version
|
Patch up version for direct running of code in repo.
|
Patch up version for direct running of code in repo.
|
Python
|
apache-2.0
|
peterbrittain/asciimatics,peterbrittain/asciimatics
|
---
+++
@@ -1,4 +1,9 @@
__author__ = 'Peter Brittain'
-from .version import version
+try:
+ from .version import version
+except ImportError:
+ # Someone is running straight from the GIT repo - dummy out the version
+ version = "0.0.0"
+
__version__ = version
|
4f24071185140ef98167e470dbac97dcdfc65b90
|
via/requests_tools/error_handling.py
|
via/requests_tools/error_handling.py
|
"""Helpers for capturing requests exceptions."""
from functools import wraps
from requests import RequestException, exceptions
from via.exceptions import BadURL, UnhandledException, UpstreamServiceError
REQUESTS_BAD_URL = (
exceptions.MissingSchema,
exceptions.InvalidSchema,
exceptions.InvalidURL,
exceptions.URLRequired,
)
REQUESTS_UPSTREAM_SERVICE = (
exceptions.ConnectionError,
exceptions.Timeout,
exceptions.TooManyRedirects,
exceptions.SSLError,
)
def handle_errors(inner):
"""Translate errors into our application errors."""
@wraps(inner)
def deco(*args, **kwargs):
try:
return inner(*args, **kwargs)
except REQUESTS_BAD_URL as err:
raise BadURL() from err
except REQUESTS_UPSTREAM_SERVICE as err:
raise UpstreamServiceError() from err
except RequestException as err:
raise UnhandledException() from err
return deco
def iter_handle_errors(inner):
"""Translate errors into our application errors."""
@wraps(inner)
def deco(*args, **kwargs):
try:
yield from inner(*args, **kwargs)
except REQUESTS_BAD_URL as err:
raise BadURL(err.args[0]) from None
except REQUESTS_UPSTREAM_SERVICE as err:
raise UpstreamServiceError(err.args[0]) from None
except RequestException as err:
raise UnhandledException(err.args[0]) from None
return deco
|
"""Helpers for capturing requests exceptions."""
from functools import wraps
from requests import RequestException, exceptions
from via.exceptions import BadURL, UnhandledException, UpstreamServiceError
REQUESTS_BAD_URL = (
exceptions.MissingSchema,
exceptions.InvalidSchema,
exceptions.InvalidURL,
exceptions.URLRequired,
)
REQUESTS_UPSTREAM_SERVICE = (
exceptions.ConnectionError,
exceptions.Timeout,
exceptions.TooManyRedirects,
exceptions.SSLError,
)
def _get_message(err):
return err.args[0] if err.args else None
def handle_errors(inner):
"""Translate errors into our application errors."""
@wraps(inner)
def deco(*args, **kwargs):
try:
return inner(*args, **kwargs)
except REQUESTS_BAD_URL as err:
raise BadURL(_get_message(err)) from err
except REQUESTS_UPSTREAM_SERVICE as err:
raise UpstreamServiceError(_get_message(err)) from err
except RequestException as err:
raise UnhandledException(_get_message(err)) from err
return deco
def iter_handle_errors(inner):
"""Translate errors into our application errors."""
@wraps(inner)
def deco(*args, **kwargs):
try:
yield from inner(*args, **kwargs)
except REQUESTS_BAD_URL as err:
raise BadURL(_get_message(err)) from None
except REQUESTS_UPSTREAM_SERVICE as err:
raise UpstreamServiceError(_get_message(err)) from None
except RequestException as err:
raise UnhandledException(_get_message(err)) from None
return deco
|
Fix error handling to show error messages
|
Fix error handling to show error messages
We removed this during a refactor, but it means we get very generic
messages in the UI instead of the actual error string.
|
Python
|
bsd-2-clause
|
hypothesis/via,hypothesis/via,hypothesis/via
|
---
+++
@@ -20,6 +20,10 @@
)
+def _get_message(err):
+ return err.args[0] if err.args else None
+
+
def handle_errors(inner):
"""Translate errors into our application errors."""
@@ -29,13 +33,13 @@
return inner(*args, **kwargs)
except REQUESTS_BAD_URL as err:
- raise BadURL() from err
+ raise BadURL(_get_message(err)) from err
except REQUESTS_UPSTREAM_SERVICE as err:
- raise UpstreamServiceError() from err
+ raise UpstreamServiceError(_get_message(err)) from err
except RequestException as err:
- raise UnhandledException() from err
+ raise UnhandledException(_get_message(err)) from err
return deco
@@ -49,12 +53,12 @@
yield from inner(*args, **kwargs)
except REQUESTS_BAD_URL as err:
- raise BadURL(err.args[0]) from None
+ raise BadURL(_get_message(err)) from None
except REQUESTS_UPSTREAM_SERVICE as err:
- raise UpstreamServiceError(err.args[0]) from None
+ raise UpstreamServiceError(_get_message(err)) from None
except RequestException as err:
- raise UnhandledException(err.args[0]) from None
+ raise UnhandledException(_get_message(err)) from None
return deco
|
a0aab3a12cae251cbdef3f1da4aadcad930ef975
|
telemetry/telemetry/internal/backends/chrome_inspector/inspector_console_unittest.py
|
telemetry/telemetry/internal/backends/chrome_inspector/inspector_console_unittest.py
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import absolute_import
import re
from telemetry.testing import tab_test_case
import py_utils
class TabConsoleTest(tab_test_case.TabTestCase):
def testConsoleOutputStream(self):
self.Navigate('page_that_logs_to_console.html')
initial = self._tab.EvaluateJavaScript('window.__logCount')
def GotLog():
current = self._tab.EvaluateJavaScript('window.__logCount')
return current > initial
py_utils.WaitFor(GotLog, 5)
console_output = (
self._tab._inspector_backend.GetCurrentConsoleOutputBuffer())
lines = [l for l in console_output.split('\n') if len(l)]
self.assertTrue(len(lines) >= 1)
for line in lines:
prefix = 'http://(.+)/page_that_logs_to_console.html:9'
expected_line = r'\(log\) %s: Hello, world' % prefix
self.assertTrue(re.match(expected_line, line))
|
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import absolute_import
import re
from telemetry.testing import tab_test_case
import py_utils
class TabConsoleTest(tab_test_case.TabTestCase):
def testConsoleOutputStream(self):
self.Navigate('page_that_logs_to_console.html')
initial = self._tab.EvaluateJavaScript('window.__logCount')
def GotLog():
current = self._tab.EvaluateJavaScript('window.__logCount')
return current > initial
py_utils.WaitFor(GotLog, 10)
console_output = (
self._tab._inspector_backend.GetCurrentConsoleOutputBuffer())
lines = [l for l in console_output.split('\n') if len(l)]
self.assertTrue(len(lines) >= 1)
for line in lines:
prefix = 'http://(.+)/page_that_logs_to_console.html:9'
expected_line = r'\(log\) %s: Hello, world' % prefix
self.assertTrue(re.match(expected_line, line))
|
Increase timeout in TabConsoleTest.testConsoleOutputStream twice.
|
Increase timeout in TabConsoleTest.testConsoleOutputStream twice.
On machines with low performance this test can fail by timeout.
Increasing timeout improves stability of this unittest passing.
Change-Id: I83a97022bbf96a4aaca349211ae7cfb9d19359b1
Reviewed-on: https://chromium-review.googlesource.com/c/catapult/+/2909584
Reviewed-by: John Chen <334fbfbb4df7c78f091ea1b77c69ca6ac731a3f3@chromium.org>
Commit-Queue: John Chen <334fbfbb4df7c78f091ea1b77c69ca6ac731a3f3@chromium.org>
|
Python
|
bsd-3-clause
|
catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult
|
---
+++
@@ -18,7 +18,7 @@
def GotLog():
current = self._tab.EvaluateJavaScript('window.__logCount')
return current > initial
- py_utils.WaitFor(GotLog, 5)
+ py_utils.WaitFor(GotLog, 10)
console_output = (
self._tab._inspector_backend.GetCurrentConsoleOutputBuffer())
|
7ab465aaaf69ba114b3411204dd773781a147c41
|
longclaw/project_template/products/models.py
|
longclaw/project_template/products/models.py
|
from django.db import models
from wagtail.wagtailcore.fields import RichTextField
from longclaw.longclawproducts.models import ProductVariantBase
class ProductVariant(ProductVariantBase):
# Enter your custom product variant fields here
# e.g. colour, size, stock and so on.
# Remember, ProductVariantBase provides 'price', 'ref', 'slug' fields
# and the parental key to the Product model.
description = RichTextField()
stock = models.IntegerField(default=0)
|
from django.db import models
from wagtail.wagtailcore.fields import RichTextField
from longclaw.longclawproducts.models import ProductVariantBase
class ProductVariant(ProductVariantBase):
# Enter your custom product variant fields here
# e.g. colour, size, stock and so on.
# Remember, ProductVariantBase provides 'price', 'ref', 'slug' fields
# and the parental key to the Product model.
description = RichTextField()
|
Remove 'stock' field from template products
|
Remove 'stock' field from template products
|
Python
|
mit
|
JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw
|
---
+++
@@ -9,4 +9,3 @@
# Remember, ProductVariantBase provides 'price', 'ref', 'slug' fields
# and the parental key to the Product model.
description = RichTextField()
- stock = models.IntegerField(default=0)
|
0feb1810b1e3ca61ef15deb71aec9fd1eab3f2da
|
py101/introduction/__init__.py
|
py101/introduction/__init__.py
|
""""
Introduction Adventure
Author: Ignacio Avas (iavas@sophilabs.com)
"""
import codecs
import io
import sys
import unittest
from story.adventures import AdventureVerificationError, BaseAdventure
from story.translation import gettext as _
class TestOutput(unittest.TestCase):
"Introduction Adventure test"
def __init__(self, sourcefile):
"Inits the test"
super(TestOutput, self).__init__()
self.sourcefile = sourcefile
def setUp(self):
self.__old_stdout = sys.stdout
sys.stdout = self.__mockstdout = io.StringIO()
def tearDown(self):
sys.stdout = self.__old_stdout
self.__mockstdout.close()
@staticmethod
def mock_print(stringy):
"Mock function"
pass
def runTest(self):
"Makes a simple test of the output"
raw_program = codecs.open(self.sourcefile).read()
code = compile(raw_program, self.sourcefile, 'exec', optimize=0)
exec(code)
self.assertEqual(
self.__mockstdout.getvalue().lower().strip(),
'hello world',
"Should have printed 'Hello World'"
)
class Adventure(BaseAdventure):
"Introduction Adventure"
title = _('Introduction')
@classmethod
def test(cls, sourcefile):
"Test against the provided file"
suite = unittest.TestSuite()
suite.addTest(TestOutput(sourcefile))
result = unittest.TextTestRunner().run(suite)
if not result.wasSuccessful():
raise AdventureVerificationError()
|
""""
Introduction Adventure
Author: Ignacio Avas (iavas@sophilabs.com)
"""
import codecs
import io
import sys
import unittest
from story.adventures import AdventureVerificationError, BaseAdventure
from story.translation import gettext as _
class TestOutput(unittest.TestCase):
"Introduction Adventure test"
def __init__(self, candidate_code, file_name='<inline>'):
"""Init the test"""
super(TestOutput, self).__init__()
self.candidate_code = candidate_code
self.file_name = file_name
def setUp(self):
self.__old_stdout = sys.stdout
sys.stdout = self.__mockstdout = io.StringIO()
def tearDown(self):
sys.stdout = self.__old_stdout
self.__mockstdout.close()
@staticmethod
def mock_print(stringy):
"Mock function"
pass
def runTest(self):
"Makes a simple test of the output"
code = compile(self.candidate_code, self.file_name, 'exec', optimize=0)
exec(code)
self.assertEqual(
self.__mockstdout.getvalue().lower().strip(),
'hello world',
"Should have printed 'Hello World'"
)
class Adventure(BaseAdventure):
title = _('Introduction')
@classmethod
def test(cls, sourcefile):
"""Test against the provided file"""
suite = unittest.TestSuite()
raw_program = codecs.open(sourcefile).read()
suite.addTest(TestOutput(raw_program, sourcefile))
result = unittest.TextTestRunner().run(suite)
if not result.wasSuccessful():
raise AdventureVerificationError()
|
Refactor introduction to make it the same as the other tests
|
Refactor introduction to make it the same as the other tests
|
Python
|
mit
|
sophilabs/py101
|
---
+++
@@ -13,10 +13,11 @@
class TestOutput(unittest.TestCase):
"Introduction Adventure test"
- def __init__(self, sourcefile):
- "Inits the test"
+ def __init__(self, candidate_code, file_name='<inline>'):
+ """Init the test"""
super(TestOutput, self).__init__()
- self.sourcefile = sourcefile
+ self.candidate_code = candidate_code
+ self.file_name = file_name
def setUp(self):
self.__old_stdout = sys.stdout
@@ -33,8 +34,7 @@
def runTest(self):
"Makes a simple test of the output"
- raw_program = codecs.open(self.sourcefile).read()
- code = compile(raw_program, self.sourcefile, 'exec', optimize=0)
+ code = compile(self.candidate_code, self.file_name, 'exec', optimize=0)
exec(code)
self.assertEqual(
self.__mockstdout.getvalue().lower().strip(),
@@ -44,14 +44,16 @@
class Adventure(BaseAdventure):
- "Introduction Adventure"
title = _('Introduction')
@classmethod
def test(cls, sourcefile):
- "Test against the provided file"
+ """Test against the provided file"""
suite = unittest.TestSuite()
- suite.addTest(TestOutput(sourcefile))
+ raw_program = codecs.open(sourcefile).read()
+ suite.addTest(TestOutput(raw_program, sourcefile))
result = unittest.TextTestRunner().run(suite)
if not result.wasSuccessful():
raise AdventureVerificationError()
+
+
|
8c159ee5fa6aa1d10cef2268a373b90f6cb72896
|
px/px_loginhistory.py
|
px/px_loginhistory.py
|
def get_users_at(timestamp, last_output=None, now=None):
"""
Return a set of strings corresponding to which users were logged in from
which addresses at a given timestamp.
Optional argument last_output is the output of "last". Will be filled in by
actually executing "last" if not provided.
Optional argument now is the current timestamp for parsing last_output. Will
be taken from the system clock if not provided.
"""
return None
|
import sys
import re
USERNAME_PART = "([^ ]+)"
DEVICE_PART = "([^ ]+)"
ADDRESS_PART = "([^ ]+)?"
FROM_PART = "(.*)"
DASH_PART = " . "
TO_PART = "(.*)"
DURATION_PART = "([0-9+:]+)"
LAST_RE = re.compile(
USERNAME_PART +
" +" +
DEVICE_PART +
" +" +
ADDRESS_PART +
" +" +
FROM_PART +
DASH_PART +
TO_PART +
" *\(" +
DURATION_PART +
"\)"
)
def get_users_at(timestamp, last_output=None, now=None):
"""
Return a set of strings corresponding to which users were logged in from
which addresses at a given timestamp.
Optional argument last_output is the output of "last". Will be filled in by
actually executing "last" if not provided.
Optional argument now is the current timestamp for parsing last_output. Will
be taken from the system clock if not provided.
"""
users = set()
for line in last_output.splitlines():
match = LAST_RE.match(line)
if not match:
sys.stderr.write(
"WARNING: Please report unmatched last line at {}: <{}>\n".format(
"https://github.com/walles/px/issues/new", line))
continue
# username = match.group(1)
# device = match.group(2)
# address = match.group(3)
# from_s = match.group(4)
# to_s = match.group(5)
# duration_s = match.group(6)
return users
|
Create regexp to match at least some last lines
|
Create regexp to match at least some last lines
|
Python
|
mit
|
walles/px,walles/px
|
---
+++
@@ -1,3 +1,30 @@
+import sys
+
+import re
+
+USERNAME_PART = "([^ ]+)"
+DEVICE_PART = "([^ ]+)"
+ADDRESS_PART = "([^ ]+)?"
+FROM_PART = "(.*)"
+DASH_PART = " . "
+TO_PART = "(.*)"
+DURATION_PART = "([0-9+:]+)"
+LAST_RE = re.compile(
+ USERNAME_PART +
+ " +" +
+ DEVICE_PART +
+ " +" +
+ ADDRESS_PART +
+ " +" +
+ FROM_PART +
+ DASH_PART +
+ TO_PART +
+ " *\(" +
+ DURATION_PART +
+ "\)"
+)
+
+
def get_users_at(timestamp, last_output=None, now=None):
"""
Return a set of strings corresponding to which users were logged in from
@@ -9,4 +36,20 @@
Optional argument now is the current timestamp for parsing last_output. Will
be taken from the system clock if not provided.
"""
- return None
+ users = set()
+ for line in last_output.splitlines():
+ match = LAST_RE.match(line)
+ if not match:
+ sys.stderr.write(
+ "WARNING: Please report unmatched last line at {}: <{}>\n".format(
+ "https://github.com/walles/px/issues/new", line))
+ continue
+
+ # username = match.group(1)
+ # device = match.group(2)
+ # address = match.group(3)
+ # from_s = match.group(4)
+ # to_s = match.group(5)
+ # duration_s = match.group(6)
+
+ return users
|
daca2bb7810b4c8eaf9f6a0598d8c6b41e0f2e10
|
froide_theme/settings.py
|
froide_theme/settings.py
|
# -*- coding: utf-8 -*-
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
class CustomThemeBase(ThemeBase):
FROIDE_THEME = 'froide_theme.theme'
SITE_NAME = "My Froide"
SITE_EMAIL = "info@example.com"
SITE_URL = 'http://localhost:8000'
SECRET_URLS = {
"admin": "admin",
}
class Dev(CustomThemeBase, Base):
pass
class ThemeHerokuPostmark(CustomThemeBase, HerokuPostmark):
pass
class ThemeHerokuPostmarkS3(CustomThemeBase, HerokuPostmarkS3):
pass
try:
from .local_settings import * # noqa
except ImportError:
pass
|
# -*- coding: utf-8 -*-
import os
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
class CustomThemeBase(ThemeBase):
FROIDE_THEME = 'froide_theme.theme'
SITE_NAME = "My Froide"
SITE_EMAIL = "info@example.com"
SITE_URL = 'http://localhost:8000'
SECRET_URLS = {
"admin": "admin",
}
@property
def LOCALE_PATHS(self):
return list(super(CustomThemeBase, self).LOCALE_PATHS.default) + [
os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', "locale")
)
]
class Dev(CustomThemeBase, Base):
pass
class ThemeHerokuPostmark(CustomThemeBase, HerokuPostmark):
pass
class ThemeHerokuPostmarkS3(CustomThemeBase, HerokuPostmarkS3):
pass
try:
from .local_settings import * # noqa
except ImportError:
pass
|
Add own locale directory to LOCALE_PATHS
|
Add own locale directory to LOCALE_PATHS
|
Python
|
mit
|
CodeforHawaii/uipa_org,CodeforHawaii/uipa_org,CodeforHawaii/uipa_org,okfde/froide-theme
|
---
+++
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
+import os
+
from froide.settings import Base, ThemeBase, HerokuPostmark, HerokuPostmarkS3 # noqa
@@ -12,6 +14,14 @@
SECRET_URLS = {
"admin": "admin",
}
+
+ @property
+ def LOCALE_PATHS(self):
+ return list(super(CustomThemeBase, self).LOCALE_PATHS.default) + [
+ os.path.abspath(
+ os.path.join(os.path.dirname(__file__), '..', "locale")
+ )
+ ]
class Dev(CustomThemeBase, Base):
|
fb22d49ca3ef41a22a5bb68261c77f24d6d39f7b
|
froide/helper/search.py
|
froide/helper/search.py
|
from haystack.fields import NgramField
try:
from .elasticsearch import SuggestField
except ImportError:
class SuggestField(NgramField):
pass
class SearchQuerySetWrapper(object):
"""
Decorates a SearchQuerySet object using a generator for efficient iteration
"""
def __init__(self, sqs, model):
self.sqs = sqs
self.model = model
def count(self):
return self.sqs.count()
def __iter__(self):
for result in self.sqs:
yield result.object
def __getitem__(self, key):
if isinstance(key, int) and (key >= 0 or key < self.count()):
# return the object at the specified position
return self.sqs[key].object
# Pass the slice/range on to the delegate
return SearchQuerySetWrapper(self.sqs[key], self.model)
|
from haystack.fields import NgramField
try:
from .elasticsearch import SuggestField
except ImportError:
class SuggestField(NgramField):
pass
class SearchQuerySetWrapper(object):
"""
Decorates a SearchQuerySet object using a generator for efficient iteration
"""
def __init__(self, sqs, model):
self.sqs = sqs
self.model = model
def count(self):
return self.sqs.count()
def __iter__(self):
for result in self.sqs:
if result is not None:
yield result.object
def __getitem__(self, key):
if isinstance(key, int) and (key >= 0 or key < self.count()):
# return the object at the specified position
return self.sqs[key].object
# Pass the slice/range on to the delegate
return SearchQuerySetWrapper(self.sqs[key], self.model)
|
Fix object access on None
|
Fix object access on None
|
Python
|
mit
|
fin/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide
|
---
+++
@@ -21,7 +21,8 @@
def __iter__(self):
for result in self.sqs:
- yield result.object
+ if result is not None:
+ yield result.object
def __getitem__(self, key):
if isinstance(key, int) and (key >= 0 or key < self.count()):
|
3203d685479ba3803a81bd2101afa7f5bced754d
|
rplugin/python3/deoplete/sources/go.py
|
rplugin/python3/deoplete/sources/go.py
|
import deoplete.util
from .base import Base
class Source(Base):
def __init__(self, vim):
Base.__init__(self, vim)
self.name = 'go'
self.mark = '[go]'
self.filetypes = ['go']
self.min_pattern_length = 0
self.is_bytepos = True
def get_complete_api(self, findstart):
complete_api = self.vim.vars['deoplete#sources#go']
if complete_api == 'gocode':
return self.vim.call('gocomplete#Complete', findstart, 0)
elif complete_api == 'vim-go':
return self.vim.call('go#complete#Complete', findstart, 0)
else:
return deoplete.util.error(self.vim, "g:deoplete#sources#go must be 'gocode' or 'vim-go'")
def get_complete_position(self, context):
return self.get_complete_api(1)
def gather_candidates(self, context):
return self.get_complete_api(0)
|
import deoplete.util
from .base import Base
class Source(Base):
def __init__(self, vim):
Base.__init__(self, vim)
self.name = 'go'
self.mark = '[go]'
self.filetypes = ['go']
self.input_pattern = '[^. \t0-9]\.\w*'
self.is_bytepos = True
def get_complete_api(self, findstart):
complete_api = self.vim.vars['deoplete#sources#go']
if complete_api == 'gocode':
return self.vim.call('gocomplete#Complete', findstart, 0)
elif complete_api == 'vim-go':
return self.vim.call('go#complete#Complete', findstart, 0)
else:
return deoplete.util.error(self.vim, "g:deoplete#sources#go must be 'gocode' or 'vim-go'")
def get_complete_position(self, context):
return self.get_complete_api(1)
def gather_candidates(self, context):
return self.get_complete_api(0)
|
Add input_pattern instead of min_pattern_length
|
Add input_pattern instead of min_pattern_length
Signed-off-by: Koichi Shiraishi <13fbd79c3d390e5d6585a21e11ff5ec1970cff0c@zchee.io>
|
Python
|
mit
|
zchee/deoplete-go,zchee/deoplete-go
|
---
+++
@@ -9,7 +9,7 @@
self.name = 'go'
self.mark = '[go]'
self.filetypes = ['go']
- self.min_pattern_length = 0
+ self.input_pattern = '[^. \t0-9]\.\w*'
self.is_bytepos = True
def get_complete_api(self, findstart):
|
cb73b357d50603a1bce1184b28266fb55a4fd4ae
|
django_ethereum_events/web3_service.py
|
django_ethereum_events/web3_service.py
|
from django.conf import settings
from web3 import HTTPProvider, Web3
from web3.middleware import geth_poa_middleware
from .utils import Singleton
class Web3Service(metaclass=Singleton):
"""Creates a `web3` instance based on the given Provider."""
def __init__(self, *args, **kwargs):
"""Initializes the `web3` object.
Args:
rpc_provider (HTTPProvider): Valid `web3` HTTPProvider instance (optional)
"""
rpc_provider = kwargs.pop('rpc_provider', None)
if not rpc_provider:
timeout = getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10)
uri = "{scheme}://{host}:{port}".format(
host=settings.ETHEREUM_NODE_HOST,
port=settings.ETHEREUM_NODE_PORT,
scheme="https" if settings.ETHEREUM_NODE_SSL else "http",
)
rpc_provider = HTTPProvider(
endpoint_uri=uri,
request_kwargs={
"timeout": timeout
}
)
self.web3 = Web3(rpc_provider)
# If running in a network with PoA consensus, inject the middleware
if getattr(settings, "ETHEREUM_GETH_POA", False):
self.web3.middleware_stack.inject(geth_poa_middleware, layer=0)
super(Web3Service, self).__init__()
|
from django.conf import settings
from web3 import HTTPProvider, Web3
from web3.middleware import geth_poa_middleware
from .utils import Singleton
class Web3Service(metaclass=Singleton):
"""Creates a `web3` instance based on the given Provider."""
def __init__(self, *args, **kwargs):
"""Initializes the `web3` object.
Args:
rpc_provider (HTTPProvider): Valid `web3` HTTPProvider instance (optional)
"""
rpc_provider = kwargs.pop('rpc_provider', None)
if not rpc_provider:
timeout = getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10)
uri = settings.ETHEREUM_NODE_PORT
rpc_provider = HTTPProvider(
endpoint_uri=uri,
request_kwargs={
"timeout": timeout
}
)
self.web3 = Web3(rpc_provider)
# If running in a network with PoA consensus, inject the middleware
if getattr(settings, "ETHEREUM_GETH_POA", False):
self.web3.middleware_stack.inject(geth_poa_middleware, layer=0)
super(Web3Service, self).__init__()
|
Change env variables for node setup to single URI varieable
|
Change env variables for node setup to single URI varieable
|
Python
|
mit
|
artemistomaras/django-ethereum-events,artemistomaras/django-ethereum-events
|
---
+++
@@ -1,5 +1,4 @@
from django.conf import settings
-
from web3 import HTTPProvider, Web3
from web3.middleware import geth_poa_middleware
@@ -19,11 +18,7 @@
if not rpc_provider:
timeout = getattr(settings, "ETHEREUM_NODE_TIMEOUT", 10)
- uri = "{scheme}://{host}:{port}".format(
- host=settings.ETHEREUM_NODE_HOST,
- port=settings.ETHEREUM_NODE_PORT,
- scheme="https" if settings.ETHEREUM_NODE_SSL else "http",
- )
+ uri = settings.ETHEREUM_NODE_PORT
rpc_provider = HTTPProvider(
endpoint_uri=uri,
request_kwargs={
|
ee3428d98d9cf322233ac9abfa9cd81513b530e0
|
medical_medicament_us/__manifest__.py
|
medical_medicament_us/__manifest__.py
|
# -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Medical Medicament - US Locale',
'version': '10.0.1.0.0',
'author': "LasLabs, Odoo Community Association (OCA)",
'category': 'Medical',
'depends': [
'medical_base_us',
'medical_medication',
],
'website': 'https://laslabs.com',
'license': 'AGPL-3',
'data': [
'views/medical_medicament_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'auto_install': True,
}
|
# -*- coding: utf-8 -*-
# © 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Medical Medicament - US Locale',
'version': '10.0.1.0.0',
'author': "LasLabs, Odoo Community Association (OCA)",
'category': 'Medical',
'depends': [
'medical_base_us',
'medical_medication',
'medical_manufacturer',
],
'website': 'https://laslabs.com',
'license': 'AGPL-3',
'data': [
'views/medical_medicament_view.xml',
'security/ir.model.access.csv',
],
'installable': True,
'auto_install': True,
}
|
Add missing dependency * medical.medicament.ndc relates to medical.manufacturer, which does not exist without it defined as a dependency.
|
[FIX] medical_medicament_us: Add missing dependency
* medical.medicament.ndc relates to medical.manufacturer, which does not exist without it defined as a dependency.
|
Python
|
agpl-3.0
|
laslabs/vertical-medical,laslabs/vertical-medical
|
---
+++
@@ -11,6 +11,7 @@
'depends': [
'medical_base_us',
'medical_medication',
+ 'medical_manufacturer',
],
'website': 'https://laslabs.com',
'license': 'AGPL-3',
|
ca6a8f554dcde5e570a61459da63ff9037dfceae
|
cumulusci/tasks/tests/test_apexdoc.py
|
cumulusci/tasks/tests/test_apexdoc.py
|
import mock
import re
import unittest
from cumulusci.core.config import BaseGlobalConfig
from cumulusci.core.config import BaseProjectConfig
from cumulusci.core.config import TaskConfig
from cumulusci.core.config import OrgConfig
from cumulusci.tasks.apexdoc import GenerateApexDocs
class TestGenerateApexDocs(unittest.TestCase):
def setUp(self):
self.global_config = BaseGlobalConfig()
self.project_config = BaseProjectConfig(self.global_config)
self.task_config = TaskConfig({"options": {"version": "1.0"}})
self.org_config = OrgConfig({}, "test")
def test_task(self):
task = GenerateApexDocs(self.project_config, self.task_config, self.org_config)
task._run_command = mock.Mock()
task()
self.assertTrue(
re.match(
r"java -jar .*/apexdoc.jar -s .*/src/classes -t .*",
task.options["command"],
)
)
|
import mock
import re
import unittest
from cumulusci.core.config import BaseGlobalConfig
from cumulusci.core.config import BaseProjectConfig
from cumulusci.core.config import TaskConfig
from cumulusci.core.config import OrgConfig
from cumulusci.tasks.apexdoc import GenerateApexDocs
class TestGenerateApexDocs(unittest.TestCase):
def setUp(self):
self.global_config = BaseGlobalConfig()
self.project_config = BaseProjectConfig(self.global_config)
self.task_config = TaskConfig({"options": {"version": "1.0"}})
self.org_config = OrgConfig({}, "test")
def test_task(self):
task = GenerateApexDocs(self.project_config, self.task_config, self.org_config)
task._run_command = mock.Mock()
task()
self.assertTrue(
re.match(
r"java -jar .*.apexdoc.jar -s .*.src.classes -t .*",
task.options["command"],
)
)
|
Update TestGenerateApexDocs regex to fix windows test
|
Update TestGenerateApexDocs regex to fix windows test
This commit updates the test regex to match either windows or unix file
separators.
The command generated on Windows:
java -jar c:\users\ieuser\appdata\local\temp\tmp9splyd\apexdoc.jar -s \Users\IEUser\Documents\GitHub\CumulusCI-Test\src\classes -t \Users\IEUser\Documents\GitHub\CumulusCI-Test -p "global;public;private;testmethod;webService"
|
Python
|
bsd-3-clause
|
SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI
|
---
+++
@@ -22,7 +22,7 @@
task()
self.assertTrue(
re.match(
- r"java -jar .*/apexdoc.jar -s .*/src/classes -t .*",
+ r"java -jar .*.apexdoc.jar -s .*.src.classes -t .*",
task.options["command"],
)
)
|
6cbfe86677b108181deb756ecf8276fe9521f691
|
mopidy/internal/gi.py
|
mopidy/internal/gi.py
|
from __future__ import absolute_import, print_function, unicode_literals
import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import GLib, GObject, Gst, GstPbutils
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python package was not found.
Mopidy requires GStreamer to work. GStreamer is a C library with a
number of dependencies itself, and cannot be installed with the regular
Python tools like pip.
Please see http://docs.mopidy.com/en/latest/installation/ for
instructions on how to install the required dependencies.
"""))
raise
else:
Gst.is_initialized() or Gst.init()
REQUIRED_GST_VERSION = (1, 2, 3)
if Gst.version() < REQUIRED_GST_VERSION:
sys.exit(
'ERROR: Mopidy requires GStreamer >= %s, but found %s.' % (
'.'.join(map(str, REQUIRED_GST_VERSION)), Gst.version_string()))
__all__ = [
'GLib',
'GObject',
'Gst',
'GstPbutils',
'gi',
]
|
from __future__ import absolute_import, print_function, unicode_literals
import sys
import textwrap
try:
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import GLib, GObject, Gst, GstPbutils
except ImportError:
print(textwrap.dedent("""
ERROR: A GObject Python package was not found.
Mopidy requires GStreamer to work. GStreamer is a C library with a
number of dependencies itself, and cannot be installed with the regular
Python tools like pip.
Please see http://docs.mopidy.com/en/latest/installation/ for
instructions on how to install the required dependencies.
"""))
raise
else:
Gst.is_initialized() or Gst.init([])
REQUIRED_GST_VERSION = (1, 2, 3)
if Gst.version() < REQUIRED_GST_VERSION:
sys.exit(
'ERROR: Mopidy requires GStreamer >= %s, but found %s.' % (
'.'.join(map(str, REQUIRED_GST_VERSION)), Gst.version_string()))
__all__ = [
'GLib',
'GObject',
'Gst',
'GstPbutils',
'gi',
]
|
Send in an argument to Gst.init
|
gst1: Send in an argument to Gst.init
As of gst-python 1.5.2, the init call requires one argument. The
argument is a list of the command line options. I don't think we need to
send any.
This relates to #1432.
|
Python
|
apache-2.0
|
tkem/mopidy,adamcik/mopidy,vrs01/mopidy,ZenithDK/mopidy,vrs01/mopidy,tkem/mopidy,mokieyue/mopidy,kingosticks/mopidy,jodal/mopidy,tkem/mopidy,kingosticks/mopidy,jodal/mopidy,mopidy/mopidy,kingosticks/mopidy,mokieyue/mopidy,adamcik/mopidy,vrs01/mopidy,mokieyue/mopidy,jcass77/mopidy,mopidy/mopidy,adamcik/mopidy,tkem/mopidy,ZenithDK/mopidy,jcass77/mopidy,jodal/mopidy,ZenithDK/mopidy,ZenithDK/mopidy,mokieyue/mopidy,jcass77/mopidy,vrs01/mopidy,mopidy/mopidy
|
---
+++
@@ -22,7 +22,7 @@
"""))
raise
else:
- Gst.is_initialized() or Gst.init()
+ Gst.is_initialized() or Gst.init([])
REQUIRED_GST_VERSION = (1, 2, 3)
|
a4c247f5243c8ee637f1507fb9dc0281541af3b1
|
pambox/speech/__init__.py
|
pambox/speech/__init__.py
|
"""
The :mod:`pambox.speech` module gather speech intelligibility
models.
"""
from __future__ import absolute_import
from .sepsm import Sepsm
from .mrsepsm import MrSepsm
from .sii import Sii
from .material import Material
__all__ = [
'Sepsm',
'MrSepsm',
'Sii',
'Material'
]
|
"""
The :mod:`pambox.speech` module gather speech intelligibility
models.
"""
from __future__ import absolute_import
from .sepsm import Sepsm
from .mrsepsm import MrSepsm
from .sii import Sii
from .material import Material
from .experiment import Experiment
__all__ = [
'Sepsm',
'MrSepsm',
'Sii',
'Material',
'Experiment'
]
|
Add Experiment to the init file of speech module
|
Add Experiment to the init file of speech module
|
Python
|
bsd-3-clause
|
achabotl/pambox
|
---
+++
@@ -8,10 +8,12 @@
from .mrsepsm import MrSepsm
from .sii import Sii
from .material import Material
+from .experiment import Experiment
__all__ = [
'Sepsm',
'MrSepsm',
'Sii',
- 'Material'
+ 'Material',
+ 'Experiment'
]
|
e655bbd79c97473003f179a3df165e6e548f121e
|
letsencryptae/models.py
|
letsencryptae/models.py
|
# THIRD PARTY
from djangae.fields import CharField
from django.db import models
class Secret(models.Model):
created = models.DateTimeField(auto_now_add=True)
url_slug = CharField(primary_key=True)
secret = CharField()
class Meta(object):
ordering = ('-created',)
def __unicode__(self):
return self.url_slug
def clean(self, *args, **kwargs):
return_value = super(Secret, self).clean(*args, **kwargs)
if not self.secret.startswith(self.url_slug):
raise ValidationError("The URL slug and the beginning of the secret should be the same.")
|
# THIRD PARTY
from djangae.fields import CharField
from django.db import models
class Secret(models.Model):
created = models.DateTimeField(auto_now_add=True)
url_slug = CharField(primary_key=True)
secret = CharField()
class Meta(object):
ordering = ('-created',)
def __unicode__(self):
return self.url_slug
def clean(self, *args, **kwargs):
""" Check that the secret starts with the URL slug plus a dot, as that's the format that
Let's Encrypt creates them in.
"""
return_value = super(Secret, self).clean(*args, **kwargs)
if not self.secret.startswith(self.url_slug + "."):
raise ValidationError("The URL slug and the beginning of the secret should be the same.")
|
Make sure that there's a dot separating the first and second halves of the secret.
|
Make sure that there's a dot separating the first and second halves of the secret.
|
Python
|
mit
|
adamalton/letsencrypt-appengine
|
---
+++
@@ -15,6 +15,9 @@
return self.url_slug
def clean(self, *args, **kwargs):
+ """ Check that the secret starts with the URL slug plus a dot, as that's the format that
+ Let's Encrypt creates them in.
+ """
return_value = super(Secret, self).clean(*args, **kwargs)
- if not self.secret.startswith(self.url_slug):
+ if not self.secret.startswith(self.url_slug + "."):
raise ValidationError("The URL slug and the beginning of the secret should be the same.")
|
af3525bf174d0774b61464f9cc8ab8441babc7ae
|
examples/flask_alchemy/test_demoapp.py
|
examples/flask_alchemy/test_demoapp.py
|
import os
import unittest
import tempfile
import demoapp
import demoapp_factories
class DemoAppTestCase(unittest.TestCase):
def setUp(self):
demoapp.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
demoapp.app.config['TESTING'] = True
self.app = demoapp.app.test_client()
self.db = demoapp.db
self.db.create_all()
def tearDown(self):
self.db.drop_all()
def test_user_factory(self):
user = demoapp_factories.UserFactory()
self.db.session.commit()
self.assertIsNotNone(user.id)
self.assertEqual(1, len(demoapp.User.query.all()))
def test_userlog_factory(self):
userlog = demoapp_factories.UserLogFactory()
self.db.session.commit()
self.assertIsNotNone(userlog.id)
self.assertIsNotNone(userlog.user.id)
self.assertEqual(1, len(demoapp.User.query.all()))
self.assertEqual(1, len(demoapp.UserLog.query.all()))
|
import unittest
import demoapp
import demoapp_factories
class DemoAppTestCase(unittest.TestCase):
def setUp(self):
demoapp.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
demoapp.app.config['TESTING'] = True
self.app = demoapp.app.test_client()
self.db = demoapp.db
self.db.create_all()
def tearDown(self):
self.db.drop_all()
def test_user_factory(self):
user = demoapp_factories.UserFactory()
self.db.session.commit()
self.assertIsNotNone(user.id)
self.assertEqual(1, len(demoapp.User.query.all()))
def test_userlog_factory(self):
userlog = demoapp_factories.UserLogFactory()
self.db.session.commit()
self.assertIsNotNone(userlog.id)
self.assertIsNotNone(userlog.user.id)
self.assertEqual(1, len(demoapp.User.query.all()))
self.assertEqual(1, len(demoapp.UserLog.query.all()))
|
Remove useless imports from flask alchemy demo
|
Remove useless imports from flask alchemy demo
|
Python
|
mit
|
FactoryBoy/factory_boy
|
---
+++
@@ -1,9 +1,8 @@
-import os
import unittest
-import tempfile
import demoapp
import demoapp_factories
+
class DemoAppTestCase(unittest.TestCase):
|
1f1e1a78f56e890777ca6f88cc30be7710275aea
|
blackbelt/deployment.py
|
blackbelt/deployment.py
|
from subprocess import check_call
from blackbelt.handle_github import get_current_branch
from blackbelt.messages import post_message
def deploy_staging():
branch_name = get_current_branch()
post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue")
check_call(['grunt', 'deploy', '--app=apiary-staging', '--force', "--branch=%s" % branch_name])
def deploy_production():
post_message("Deploying to production", "#deploy-queue")
check_call(['grunt', 'deploy'])
|
from subprocess import check_call
from blackbelt.handle_github import get_current_branch
from blackbelt.messages import post_message
def deploy_staging():
branch_name = get_current_branch()
post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue")
check_call(['grunt', 'deploy', '--app=apiary-staging-pool1', '--force', "--branch=%s" % branch_name])
def deploy_production():
post_message("Deploying to production", "#deploy-queue")
check_call(['grunt', 'deploy'])
check_call(['grunt', 'deploy', '--app=apiary-staging'])
|
Update deploy and stage with new environ
|
feat: Update deploy and stage with new environ
|
Python
|
mit
|
apiaryio/black-belt
|
---
+++
@@ -9,9 +9,10 @@
post_message("Deploying branch %s to staging" % branch_name, "#deploy-queue")
- check_call(['grunt', 'deploy', '--app=apiary-staging', '--force', "--branch=%s" % branch_name])
+ check_call(['grunt', 'deploy', '--app=apiary-staging-pool1', '--force', "--branch=%s" % branch_name])
def deploy_production():
post_message("Deploying to production", "#deploy-queue")
check_call(['grunt', 'deploy'])
+ check_call(['grunt', 'deploy', '--app=apiary-staging'])
|
847e864df300304ac43e995a577eaa93ae452024
|
streak-podium/render.py
|
streak-podium/render.py
|
import matplotlib.pyplot as plt
import numpy as np
def horizontal_bar(sorted_streaks, sort):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort.
"""
# Only extract those users & streaks for streaks that are non-zero:
users, streaks = zip(*[(user, streak.get(sort)) for user, streak
in sorted_streaks if streak.get(sort) > 0][::-1])
title = 'Top Contributors by {} Streak'.format(sort.title())
figure = plt.figure(num=None, figsize=(6, 15))
y_pos = np.arange(len(users)) # y-location of bars
print('y_pos', y_pos)
plt.barh(y_pos, streaks, facecolor='#5555EE', edgecolor='grey', align='center')
plt.yticks(y_pos, users)
plt.xlim([0, max(streaks) + 10]) # x-limits a bit wider at right
plt.subplots_adjust(left=0.25) # Wider left margin
plt.title(title)
for format in ('png', 'svg'):
figure.savefig('temp/top_{}.{}'.format(sort, format), format=format)
|
import matplotlib.pyplot as plt
import numpy as np
def horizontal_bar(sorted_streaks, sort):
"""
Render a horizontal bar chart of streaks.
Values have already been sorted by sort.
"""
# Only extract those users & streaks for streaks that are non-zero:
users, streaks = zip(*[(user, streak.get(sort)) for user, streak
in sorted_streaks if streak.get(sort) > 0][::-1])
title = 'Top Contributors by {} Streak'.format(sort.title())
figure = plt.figure(num=None, figsize=(6, 15))
y_pos = np.arange(len(users)) # y-location of bars
print('y_pos', y_pos)
plt.barh(y_pos, streaks, facecolor='#5555EE', edgecolor='grey', align='center')
plt.yticks(y_pos, users)
plt.xlim([0, max(streaks) + 10]) # x-limits a bit wider at right
plt.subplots_adjust(left=0.25) # Wider left margin
plt.title(title)
ax = plt.gca()
ax.yaxis.set_ticks_position('none')
ax.xaxis.set_ticks_position('bottom')
for format in ('png', 'svg'):
figure.savefig('temp/top_{}.{}'.format(sort, format), format=format)
|
Remove y-axis ticks and top x-axis ticks
|
Remove y-axis ticks and top x-axis ticks
|
Python
|
mit
|
jollyra/hubot-streak-podium,jollyra/hubot-commit-streak,supermitch/streak-podium,jollyra/hubot-streak-podium,supermitch/streak-podium,jollyra/hubot-commit-streak
|
---
+++
@@ -22,6 +22,9 @@
plt.xlim([0, max(streaks) + 10]) # x-limits a bit wider at right
plt.subplots_adjust(left=0.25) # Wider left margin
plt.title(title)
+ ax = plt.gca()
+ ax.yaxis.set_ticks_position('none')
+ ax.xaxis.set_ticks_position('bottom')
for format in ('png', 'svg'):
figure.savefig('temp/top_{}.{}'.format(sort, format), format=format)
|
1ed49dae9d88e1e277a0eef879dec53ed925417a
|
highlander/exceptions.py
|
highlander/exceptions.py
|
class InvalidPidFileError(Exception):
""" An exception when an invalid PID file is read."""
class PidFileExistsError(Exception):
""" An exception when a PID file already exists."""
|
class InvalidPidFileError(Exception):
""" An exception when an invalid PID file is read."""
class PidFileExistsError(Exception):
""" An exception when a PID file already exists."""
class InvalidPidDirectoryError(Exception):
""" An exception when an invalid PID directory is detected."""
|
Add a new exception since we are making a directory now.
|
Add a new exception since we are making a directory now.
|
Python
|
mit
|
chriscannon/highlander
|
---
+++
@@ -3,3 +3,6 @@
class PidFileExistsError(Exception):
""" An exception when a PID file already exists."""
+
+class InvalidPidDirectoryError(Exception):
+ """ An exception when an invalid PID directory is detected."""
|
644df0955d1a924b72ffdceaea9d8da14100dae0
|
scipy/weave/tests/test_inline_tools.py
|
scipy/weave/tests/test_inline_tools.py
|
from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
try:
a = 1
result = inline_tools.inline(code,['a'])
assert(1) # should've thrown a ValueError
except ValueError:
pass
from distutils.errors import DistutilsError, CompileError
try:
a = 'string'
result = inline_tools.inline(code,['a'])
assert(1) # should've gotten an error
except:
# ?CompileError is the error reported, but catching it doesn't work
pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
|
from numpy import *
from numpy.testing import *
from scipy.weave import inline_tools
class TestInline(TestCase):
""" These are long running tests...
I'd like to benchmark these things somehow.
"""
@dec.slow
def test_exceptions(self):
a = 3
code = """
if (a < 2)
throw_error(PyExc_ValueError,
"the variable 'a' should not be less than 2");
else
return_val = PyInt_FromLong(a+1);
"""
result = inline_tools.inline(code,['a'])
assert(result == 4)
## Unfortunately, it is not always possible to catch distutils compiler
## errors, since SystemExit is used. Until that is fixed, these tests
## cannot be run in the same process as the test suite.
## try:
## a = 1
## result = inline_tools.inline(code,['a'])
## assert(1) # should've thrown a ValueError
## except ValueError:
## pass
## from distutils.errors import DistutilsError, CompileError
## try:
## a = 'string'
## result = inline_tools.inline(code,['a'])
## assert(1) # should've gotten an error
## except:
## # ?CompileError is the error reported, but catching it doesn't work
## pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
|
Disable weave tests that cause compilation failure, since this causes distutils to do a SystemExit, which break the test suite.
|
Disable weave tests that cause compilation failure, since this causes
distutils to do a SystemExit, which break the test suite.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5402 d6536bca-fef9-0310-8506-e4c0a848fbcf
|
Python
|
bsd-3-clause
|
scipy/scipy-svn,lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor
|
---
+++
@@ -21,21 +21,25 @@
result = inline_tools.inline(code,['a'])
assert(result == 4)
- try:
- a = 1
- result = inline_tools.inline(code,['a'])
- assert(1) # should've thrown a ValueError
- except ValueError:
- pass
+## Unfortunately, it is not always possible to catch distutils compiler
+## errors, since SystemExit is used. Until that is fixed, these tests
+## cannot be run in the same process as the test suite.
- from distutils.errors import DistutilsError, CompileError
- try:
- a = 'string'
- result = inline_tools.inline(code,['a'])
- assert(1) # should've gotten an error
- except:
- # ?CompileError is the error reported, but catching it doesn't work
- pass
+## try:
+## a = 1
+## result = inline_tools.inline(code,['a'])
+## assert(1) # should've thrown a ValueError
+## except ValueError:
+## pass
+
+## from distutils.errors import DistutilsError, CompileError
+## try:
+## a = 'string'
+## result = inline_tools.inline(code,['a'])
+## assert(1) # should've gotten an error
+## except:
+## # ?CompileError is the error reported, but catching it doesn't work
+## pass
if __name__ == "__main__":
nose.run(argv=['', __file__])
|
26e947c91980cf6ccb83a99cbb5c6fefb0837d4f
|
mopidy/backends/libspotify/library.py
|
mopidy/backends/libspotify/library.py
|
import logging
import multiprocessing
from spotify import Link
from mopidy.backends.base import BaseLibraryController
from mopidy.backends.libspotify import ENCODING
from mopidy.backends.libspotify.translator import LibspotifyTranslator
logger = logging.getLogger('mopidy.backends.libspotify.library')
class LibspotifyLibraryController(BaseLibraryController):
def find_exact(self, **query):
return self.search(**query)
def lookup(self, uri):
spotify_track = Link.from_string(uri).as_track()
return LibspotifyTranslator.to_mopidy_track(spotify_track)
def refresh(self, uri=None):
pass # TODO
def search(self, **query):
spotify_query = []
for (field, values) in query.iteritems():
if not hasattr(values, '__iter__'):
values = [values]
for value in values:
if field == u'track':
field = u'title'
if field == u'any':
spotify_query.append(value)
else:
spotify_query.append(u'%s:"%s"' % (field, value))
spotify_query = u' '.join(spotify_query)
logger.debug(u'Spotify search query: %s' % spotify_query)
my_end, other_end = multiprocessing.Pipe()
self.backend.spotify.search(spotify_query.encode(ENCODING), other_end)
my_end.poll(None)
playlist = my_end.recv()
return playlist
|
import logging
import multiprocessing
from spotify import Link
from mopidy.backends.base import BaseLibraryController
from mopidy.backends.libspotify import ENCODING
from mopidy.backends.libspotify.translator import LibspotifyTranslator
logger = logging.getLogger('mopidy.backends.libspotify.library')
class LibspotifyLibraryController(BaseLibraryController):
def find_exact(self, **query):
return self.search(**query)
def lookup(self, uri):
spotify_track = Link.from_string(uri).as_track()
# TODO Block until metadata_updated callback is called. Before that the
# track will be unloaded, unless it's already in the stored playlists.
return LibspotifyTranslator.to_mopidy_track(spotify_track)
def refresh(self, uri=None):
pass # TODO
def search(self, **query):
spotify_query = []
for (field, values) in query.iteritems():
if not hasattr(values, '__iter__'):
values = [values]
for value in values:
if field == u'track':
field = u'title'
if field == u'any':
spotify_query.append(value)
else:
spotify_query.append(u'%s:"%s"' % (field, value))
spotify_query = u' '.join(spotify_query)
logger.debug(u'Spotify search query: %s' % spotify_query)
my_end, other_end = multiprocessing.Pipe()
self.backend.spotify.search(spotify_query.encode(ENCODING), other_end)
my_end.poll(None)
playlist = my_end.recv()
return playlist
|
Add TODO on how to make a better libspotify lookup
|
Add TODO on how to make a better libspotify lookup
|
Python
|
apache-2.0
|
dbrgn/mopidy,jcass77/mopidy,pacificIT/mopidy,ali/mopidy,bacontext/mopidy,bencevans/mopidy,ali/mopidy,dbrgn/mopidy,bacontext/mopidy,kingosticks/mopidy,mokieyue/mopidy,SuperStarPL/mopidy,hkariti/mopidy,abarisain/mopidy,jmarsik/mopidy,liamw9534/mopidy,pacificIT/mopidy,vrs01/mopidy,abarisain/mopidy,glogiotatidis/mopidy,woutervanwijk/mopidy,rawdlite/mopidy,ali/mopidy,tkem/mopidy,bencevans/mopidy,rawdlite/mopidy,bencevans/mopidy,bacontext/mopidy,swak/mopidy,quartz55/mopidy,tkem/mopidy,bencevans/mopidy,swak/mopidy,rawdlite/mopidy,ZenithDK/mopidy,hkariti/mopidy,SuperStarPL/mopidy,glogiotatidis/mopidy,mokieyue/mopidy,swak/mopidy,quartz55/mopidy,ZenithDK/mopidy,SuperStarPL/mopidy,jodal/mopidy,liamw9534/mopidy,quartz55/mopidy,mopidy/mopidy,priestd09/mopidy,ZenithDK/mopidy,dbrgn/mopidy,tkem/mopidy,bacontext/mopidy,glogiotatidis/mopidy,tkem/mopidy,hkariti/mopidy,jodal/mopidy,ali/mopidy,glogiotatidis/mopidy,dbrgn/mopidy,diandiankan/mopidy,vrs01/mopidy,kingosticks/mopidy,priestd09/mopidy,SuperStarPL/mopidy,vrs01/mopidy,vrs01/mopidy,swak/mopidy,priestd09/mopidy,hkariti/mopidy,jodal/mopidy,pacificIT/mopidy,quartz55/mopidy,mopidy/mopidy,adamcik/mopidy,adamcik/mopidy,adamcik/mopidy,jcass77/mopidy,jmarsik/mopidy,diandiankan/mopidy,mokieyue/mopidy,jmarsik/mopidy,jmarsik/mopidy,woutervanwijk/mopidy,jcass77/mopidy,rawdlite/mopidy,kingosticks/mopidy,mokieyue/mopidy,diandiankan/mopidy,pacificIT/mopidy,ZenithDK/mopidy,mopidy/mopidy,diandiankan/mopidy
|
---
+++
@@ -15,6 +15,8 @@
def lookup(self, uri):
spotify_track = Link.from_string(uri).as_track()
+ # TODO Block until metadata_updated callback is called. Before that the
+ # track will be unloaded, unless it's already in the stored playlists.
return LibspotifyTranslator.to_mopidy_track(spotify_track)
def refresh(self, uri=None):
|
8a605f21e6c11b8176214ce7082c892566a6b34e
|
telethon/tl/message_container.py
|
telethon/tl/message_container.py
|
from . import TLObject, GzipPacked
from ..extensions import BinaryWriter
class MessageContainer(TLObject):
constructor_id = 0x73f1f8dc
def __init__(self, messages):
super().__init__()
self.content_related = False
self.messages = messages
def to_bytes(self):
# TODO Change this to delete the on_send from this class
with BinaryWriter() as writer:
writer.write_int(MessageContainer.constructor_id, signed=False)
writer.write_int(len(self.messages))
for m in self.messages:
writer.write(m.to_bytes())
return writer.get_bytes()
@staticmethod
def iter_read(reader):
reader.read_int(signed=False) # code
size = reader.read_int()
for _ in range(size):
inner_msg_id = reader.read_long()
inner_sequence = reader.read_int()
inner_length = reader.read_int()
yield inner_msg_id, inner_sequence, inner_length
|
import struct
from . import TLObject
class MessageContainer(TLObject):
constructor_id = 0x73f1f8dc
def __init__(self, messages):
super().__init__()
self.content_related = False
self.messages = messages
def to_bytes(self):
return struct.pack(
'<Ii', MessageContainer.constructor_id, len(self.messages)
) + b''.join(m.to_bytes() for m in self.messages)
@staticmethod
def iter_read(reader):
reader.read_int(signed=False) # code
size = reader.read_int()
for _ in range(size):
inner_msg_id = reader.read_long()
inner_sequence = reader.read_int()
inner_length = reader.read_int()
yield inner_msg_id, inner_sequence, inner_length
|
Remove BinaryWriter dependency on MessageContainer
|
Remove BinaryWriter dependency on MessageContainer
|
Python
|
mit
|
LonamiWebs/Telethon,andr-04/Telethon,LonamiWebs/Telethon,expectocode/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon
|
---
+++
@@ -1,5 +1,6 @@
-from . import TLObject, GzipPacked
-from ..extensions import BinaryWriter
+import struct
+
+from . import TLObject
class MessageContainer(TLObject):
@@ -11,14 +12,9 @@
self.messages = messages
def to_bytes(self):
- # TODO Change this to delete the on_send from this class
- with BinaryWriter() as writer:
- writer.write_int(MessageContainer.constructor_id, signed=False)
- writer.write_int(len(self.messages))
- for m in self.messages:
- writer.write(m.to_bytes())
-
- return writer.get_bytes()
+ return struct.pack(
+ '<Ii', MessageContainer.constructor_id, len(self.messages)
+ ) + b''.join(m.to_bytes() for m in self.messages)
@staticmethod
def iter_read(reader):
|
2bf0872a176fd8b97a31a15bd3feb49d7f8cf7d7
|
hubbot/Utils/timeout.py
|
hubbot/Utils/timeout.py
|
import signal
class Timeout(Exception):
"""Context manager which wraps code in a timeout.
If the timeout is exceeded, the context manager will be raised.
Example usage:
try:
with Timeout(5):
time.sleep(10)
except Timeout:
pass
"""
def __init__(self, duration):
self.duration = duration
def _handler(self, signum, frame):
raise self
def __enter__(self):
self._old_handler = signal.signal(signal.SIGALRM, self._handler)
old_alarm = signal.alarm(self.duration)
if old_alarm:
raise Exception("Timeout will not behave correctly in conjunction with other code that uses signal.alarm()")
def __exit__(self, *exc_info):
signal.alarm(0) # cancel any pending alarm
my_handler = signal.signal(signal.SIGALRM, self._old_handler)
assert my_handler == self._handler, "Wrong SIGALRM handler on __exit__, is something else messing with signal handlers?"
def __str__(self):
return "Exceeded timeout of {} seconds".format(self.duration)
|
import signal
class Timeout(Exception):
"""Context manager which wraps code in a timeout.
If the timeout is exceeded, the context manager will be raised.
Example usage:
try:
with Timeout(5):
time.sleep(10)
except Timeout:
pass
"""
def __init__(self, duration):
self.duration = duration
def _handler(self, signum, frame):
raise self
def __enter__(self):
self._old_handler = signal.signal(signal.SIGALRM, self._handler)
old_alarm = signal.alarm(self.duration)
if old_alarm:
raise Exception("Timeout will not behave correctly in conjunction with other code that uses signal.alarm()")
def __exit__(self, *exc_info):
signal.alarm(0) # cancel any pending alarm
my_handler = signal.signal(signal.SIGALRM, self._old_handler)
assert my_handler is self._handler, "Wrong SIGALRM handler on __exit__, is something else messing with signal handlers?"
def __str__(self):
return "Exceeded timeout of {} seconds".format(self.duration)
|
Revert "[Timeout] Fix an assert"
|
Revert "[Timeout] Fix an assert"
This reverts commit 05f0fb77716297114043d52de3764289a1926752.
|
Python
|
mit
|
HubbeKing/Hubbot_Twisted
|
---
+++
@@ -27,7 +27,7 @@
def __exit__(self, *exc_info):
signal.alarm(0) # cancel any pending alarm
my_handler = signal.signal(signal.SIGALRM, self._old_handler)
- assert my_handler == self._handler, "Wrong SIGALRM handler on __exit__, is something else messing with signal handlers?"
+ assert my_handler is self._handler, "Wrong SIGALRM handler on __exit__, is something else messing with signal handlers?"
def __str__(self):
return "Exceeded timeout of {} seconds".format(self.duration)
|
864d23ab3996e471b659ded6cfc13447b2497107
|
example.py
|
example.py
|
from __future__ import print_function
import io
import string
import random
from boggle.boggle import list_words
def main():
with io.open("/usr/share/dict/words", encoding='latin-1') as word_file:
english_words = set(word.strip() for word in word_file)
available_tiles = [letter for letter in string.ascii_uppercase]
available_tiles.remove('Q')
available_tiles.append('Qu')
# A boggle board is an n * n square. Set n:
size = 15
board = []
for row in range(size):
board.append([random.choice(available_tiles) for i in xrange(size)])
found_words = list_words(
word_list=english_words,
board=board,
)
print(len(found_words))
main()
|
from __future__ import print_function
import io
import string
import random
from boggle.boggle import list_words
def main():
with io.open("/usr/share/dict/words", encoding='latin-1') as word_file:
english_words = set(word.strip() for word in word_file)
available_tiles = [letter for letter in string.ascii_uppercase]
available_tiles.remove('Q')
available_tiles.append('Qu')
# A boggle board is an n * n square. Set n:
size = 10
board = []
for row in range(size):
board.append([random.choice(available_tiles) for i in range(size)])
found_words = list_words(
word_list=english_words,
board=board,
)
print(len(found_words))
main()
|
Use range instead of xrange as it is also available in python 3
|
Use range instead of xrange as it is also available in python 3
|
Python
|
mit
|
adamtheturtle/boggle-solver
|
---
+++
@@ -15,11 +15,11 @@
available_tiles.append('Qu')
# A boggle board is an n * n square. Set n:
- size = 15
+ size = 10
board = []
for row in range(size):
- board.append([random.choice(available_tiles) for i in xrange(size)])
+ board.append([random.choice(available_tiles) for i in range(size)])
found_words = list_words(
word_list=english_words,
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.